diff --git a/CHANGELOG.md b/CHANGELOG.md index 648cb15..3f216db 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,27 @@ Changelog ========= +#### 4.4 - March 1, 2018 + +**Fixes** + +- AffiliateWP integration subscribing the wrong user if affiliate ID differs from user ID. + +**Improvements** + +- Renamed "Newsletter" to "Newsletter" to match Newsletter's new branding. +- More accurate handling of timeouts for accounts with many Newsletter lists. +- UX improvements for integrations overview page. +- Validate Newsletter API key format when it's entered. +- Improved compatibility with Klarna Checkout in the WooCommerce checkout integration. +- Bumped required PHP version to 5.3 (soft requirement for now). + +**Additions** + +- Added Gutenberg block for easily adding a form to a post or page. +- Added subscriber tags setting to forms. + + #### 4.3.3 - December 31, 2018 **Fixes** diff --git a/assets/js/admin.js b/assets/js/admin.js index 3db7ea3..f29867c 100755 --- a/assets/js/admin.js +++ b/assets/js/admin.js @@ -29,7 +29,9 @@ var mount = document.getElementById('nl4wp-list-fetcher'); if (mount) { m.mount(mount, new ListFetcher()); -} // expose some things +} + +require('./admin/fields/newsletter-api-key.js'); // expose some things window.nl4wp = window.nl4wp || {}; @@ -40,7 +42,36 @@ window.nl4wp.events = events; window.nl4wp.settings = settings; window.nl4wp.tabs = tabs; -},{"./admin/helpers.js":2,"./admin/list-fetcher.js":3,"./admin/settings.js":4,"./admin/tabs.js":5,"mithril":7,"tlite":10,"wolfy87-eventemitter":11}],2:[function(require,module,exports){ +},{"./admin/fields/newsletter-api-key.js":2,"./admin/helpers.js":3,"./admin/list-fetcher.js":4,"./admin/settings.js":5,"./admin/tabs.js":6,"mithril":8,"tlite":11,"wolfy87-eventemitter":12}],2:[function(require,module,exports){ +'use strict'; + +var field; + +function validate(evt) { + var node = document.createElement('p'); + node.className = 'help red'; + node.innerText = window.nl4wp_vars.i18n.invalid_api_key; + + if (field.nextElementSibling.innerText === node.innerText) { + field.nextElementSibling.parentElement.removeChild(field.nextElementSibling); + } + + if (!field.value.match(/^[0-9a-z]+-[0-9a-z]+-[0-9a-z]+$/)) { + field.parentElement.insertBefore(node, field.nextElementSibling); + } +} + +(function () { + field = document.getElementById('newsletter_api_key'); + + if (!field) { + return; + } + + field.addEventListener('change', validate); +})(); + +},{}],3:[function(require,module,exports){ 'use strict'; var helpers = {}; @@ -133,7 +164,7 @@ helpers.debounce = function (func, wait, immediate) { module.exports = helpers; -},{}],3:[function(require,module,exports){ +},{}],4:[function(require,module,exports){ 'use strict'; var $ = window.jQuery; @@ -155,7 +186,8 @@ ListFetcher.prototype.fetch = function (e) { this.done = false; $.post(ajaxurl, { action: "nl4wp_renew_newsletter_lists", - timeout: 180000 + timeout: 600000 // 10 minutes, matching max_execution_time + }).done(function (data) { this.success = true; @@ -187,7 +219,7 @@ ListFetcher.prototype.view = function () { module.exports = ListFetcher; -},{}],4:[function(require,module,exports){ +},{}],5:[function(require,module,exports){ "use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } @@ -250,7 +282,7 @@ var Settings = function Settings(context, helpers, events) { module.exports = Settings; -},{}],5:[function(require,module,exports){ +},{}],6:[function(require,module,exports){ 'use strict'; var URL = require('./url.js'); // Tabs @@ -422,7 +454,7 @@ var Tabs = function Tabs(context) { module.exports = Tabs; -},{"./url.js":6}],6:[function(require,module,exports){ +},{"./url.js":7}],7:[function(require,module,exports){ 'use strict'; var URL = { @@ -458,7 +490,7 @@ var URL = { }; module.exports = URL; -},{}],7:[function(require,module,exports){ +},{}],8:[function(require,module,exports){ (function (global,setImmediate){ ;(function() { "use strict" @@ -1718,7 +1750,7 @@ if (typeof module !== "undefined") module["exports"] = m else window.m = m }()); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) -},{"timers":9}],8:[function(require,module,exports){ +},{"timers":10}],9:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -1904,7 +1936,7 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],9:[function(require,module,exports){ +},{}],10:[function(require,module,exports){ (function (setImmediate,clearImmediate){ var nextTick = require('process/browser.js').nextTick; var apply = Function.prototype.apply; @@ -1983,7 +2015,7 @@ exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : delete immediateIds[id]; }; }).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":8,"timers":9}],10:[function(require,module,exports){ +},{"process/browser.js":9,"timers":10}],11:[function(require,module,exports){ function tlite(getTooltipOpts) { document.addEventListener('mouseover', function (e) { var el = e.target; @@ -2119,7 +2151,7 @@ if (typeof module !== 'undefined' && module.exports) { module.exports = tlite; } -},{}],11:[function(require,module,exports){ +},{}],12:[function(require,module,exports){ /*! * EventEmitter v5.2.5 - git.io/ee * Unlicense - http://unlicense.org/ diff --git a/assets/js/admin.min.js b/assets/js/admin.min.js index 7c69e5a..1892266 100755 --- a/assets/js/admin.min.js +++ b/assets/js/admin.min.js @@ -1,2 +1,2 @@ -!function(){var l=void 0;!function o(a,l,s){function u(t,e){if(!l[t]){if(!a[t]){var n=!1;if(!e&&n)return n(t,!0);if(c)return c(t,!0);var r=new Error("Cannot find module '"+t+"'");throw r.code="MODULE_NOT_FOUND",r}var i=l[t]={exports:{}};a[t][0].call(i.exports,function(e){return u(a[t][1][e]||e)},i,i.exports,o,a,l,s)}return l[t].exports}for(var c=!1,e=0;e *");Array.prototype.forEach.call(e,function(e){var t,n,r=e.getAttribute("data-list-id");0<(t="id",n=r,o.filter(function(e){return e[t]===n})).length?e.setAttribute("class",e.getAttribute("class").replace("hidden","")):e.setAttribute("class",e.getAttribute("class")+" hidden")})}),t.bindEventToElements(r,"change",a),a(),{getSelectedLists:function(){return o}}}},{}],5:[function(e,t,n){"use strict";var d=e("./url.js");t.exports=function(i){var o=window.jQuery,e=o(i),r=e.find(".tab"),a=e.find(".nav-tab"),l=i.querySelector('input[name="_wp_http_referer"]'),s=[];function u(e){for(var t=0;t=t.length-u.length||null==u&&r;d++,E(e,m,y,i,T(t,++f,o),p,a),r&&m.tag===y.tag&&k(e,_(m),o)}else{if((m=t[h])!==y||r)if(null==m)h--;else if(null==y)d++;else{if(m.key!==y.key)break;p=null!=u&&h>=t.length-u.length||null==u&&r;E(e,m,y,i,T(t,h+1,o),p,a),(r||d=t.length-u.length||null==u&&r;E(e,m,y,i,T(t,h+1,o),p,a),r&&m.tag===y.tag&&k(e,_(m),o),null!=m.dom&&(o=m.dom),h--,v--}else{if(c||(c=A(t,h)),null!=y){var g=c[y.key];if(null!=g){var w=t[g];p=null!=u&&g>=t.length-u.length||null==u&&r;E(e,w,y,i,T(t,h+1,o),r,a),k(e,_(w),o),t[g].skip=!0,null!=w.dom&&(o=w.dom)}else{o=x(e,y,i,a,o)}}v--}else h--,v--;if(vwindow.innerHeight?(u="s",r()):"e"===u&&i.left<0?(u="w",r()):"w"===u&&i.right>window.innerWidth&&(u="e",r());return s.className+=" tlite-visible",s}(e,i,t))}return e.addEventListener("mousedown",o),e.addEventListener("mouseleave",o),e.tooltip={show:function(){i=e.title||e.getAttribute(s)||i,e.title="",e.setAttribute(s,""),i&&!r&&(r=setTimeout(a,l?150:1))},hide:function(e){if(l===e){r=clearTimeout(r);var t=n&&n.parentNode;t&&t.removeChild(n),n=void 0}}}}(e,t)).show()},u.hide=function(e,t){e.tooltip&&e.tooltip.hide(t)},void 0!==t&&t.exports&&(t.exports=u)},{}],11:[function(e,a,t){!function(e){"use strict";function t(){}var n=t.prototype,r=e.EventEmitter;function o(e,t){for(var n=e.length;n--;)if(e[n].listener===t)return n;return-1}function i(e){return function(){return this[e].apply(this,arguments)}}n.getListeners=function(e){var t,n,r=this._getEvents();if(e instanceof RegExp)for(n in t={},r)r.hasOwnProperty(n)&&e.test(n)&&(t[n]=r[n]);else t=r[e]||(r[e]=[]);return t},n.flattenListeners=function(e){var t,n=[];for(t=0;t *");Array.prototype.forEach.call(e,function(e){var t,n,r=e.getAttribute("data-list-id");0<(t="id",n=r,o.filter(function(e){return e[t]===n})).length?e.setAttribute("class",e.getAttribute("class").replace("hidden","")):e.setAttribute("class",e.getAttribute("class")+" hidden")})}),t.bindEventToElements(r,"change",a),a(),{getSelectedLists:function(){return o}}}},{}],6:[function(e,t,n){"use strict";var d=e("./url.js");t.exports=function(i){var o=window.jQuery,e=o(i),r=e.find(".tab"),a=e.find(".nav-tab"),l=i.querySelector('input[name="_wp_http_referer"]'),s=[];function u(e){for(var t=0;t=t.length-u.length||null==u&&r;d++,E(e,m,y,i,A(t,++f,o),v,a),r&&m.tag===y.tag&&k(e,T(m),o)}else{if((m=t[h])!==y||r)if(null==m)h--;else if(null==y)d++;else{if(m.key!==y.key)break;v=null!=u&&h>=t.length-u.length||null==u&&r;E(e,m,y,i,A(t,h+1,o),v,a),(r||d=t.length-u.length||null==u&&r;E(e,m,y,i,A(t,h+1,o),v,a),r&&m.tag===y.tag&&k(e,T(m),o),null!=m.dom&&(o=m.dom),h--,p--}else{if(c||(c=_(t,h)),null!=y){var g=c[y.key];if(null!=g){var w=t[g];v=null!=u&&g>=t.length-u.length||null==u&&r;E(e,w,y,i,A(t,h+1,o),r,a),k(e,T(w),o),t[g].skip=!0,null!=w.dom&&(o=w.dom)}else{o=x(e,y,i,a,o)}}p--}else h--,p--;if(pwindow.innerHeight?(u="s",r()):"e"===u&&i.left<0?(u="w",r()):"w"===u&&i.right>window.innerWidth&&(u="e",r());return s.className+=" tlite-visible",s}(e,i,t))}return e.addEventListener("mousedown",o),e.addEventListener("mouseleave",o),e.tooltip={show:function(){i=e.title||e.getAttribute(s)||i,e.title="",e.setAttribute(s,""),i&&!r&&(r=setTimeout(a,l?150:1))},hide:function(e){if(l===e){r=clearTimeout(r);var t=n&&n.parentNode;t&&t.removeChild(n),n=void 0}}}}(e,t)).show()},u.hide=function(e,t){e.tooltip&&e.tooltip.hide(t)},void 0!==t&&t.exports&&(t.exports=u)},{}],12:[function(e,a,t){!function(e){"use strict";function t(){}var n=t.prototype,r=e.EventEmitter;function o(e,t){for(var n=e.length;n--;)if(e[n].listener===t)return n;return-1}function i(e){return function(){return this[e].apply(this,arguments)}}n.getListeners=function(e){var t,n,r=this._getEvents();if(e instanceof RegExp)for(n in t={},r)r.hasOwnProperty(n)&&e.test(n)&&(t[n]=r[n]);else t=r[e]||(r[e]=[]);return t},n.flattenListeners=function(e){var t,n=[];for(t=0;t -1;\n}); // list fetcher\n\nvar ListFetcher = require('./admin/list-fetcher.js');\n\nvar mount = document.getElementById('nl4wp-list-fetcher');\n\nif (mount) {\n m.mount(mount, new ListFetcher());\n} // expose some things\n\n\nwindow.nl4wp = window.nl4wp || {};\nwindow.nl4wp.deps = window.nl4wp.deps || {};\nwindow.nl4wp.deps.mithril = m;\nwindow.nl4wp.helpers = helpers;\nwindow.nl4wp.events = events;\nwindow.nl4wp.settings = settings;\nwindow.nl4wp.tabs = tabs;\n\n},{\"./admin/helpers.js\":2,\"./admin/list-fetcher.js\":3,\"./admin/settings.js\":4,\"./admin/tabs.js\":5,\"mithril\":7,\"tlite\":10,\"wolfy87-eventemitter\":11}],2:[function(require,module,exports){\n'use strict';\n\nvar helpers = {};\n\nhelpers.toggleElement = function (selector) {\n var elements = document.querySelectorAll(selector);\n\n for (var i = 0; i < elements.length; i++) {\n var show = elements[i].clientHeight <= 0;\n elements[i].style.display = show ? '' : 'none';\n }\n};\n\nhelpers.bindEventToElement = function (element, event, handler) {\n if (element.addEventListener) {\n element.addEventListener(event, handler);\n } else if (element.attachEvent) {\n element.attachEvent('on' + event, handler);\n }\n};\n\nhelpers.bindEventToElements = function (elements, event, handler) {\n Array.prototype.forEach.call(elements, function (element) {\n helpers.bindEventToElement(element, event, handler);\n });\n}; // polling\n\n\nhelpers.debounce = function (func, wait, immediate) {\n var timeout;\n return function () {\n var context = this,\n args = arguments;\n\n var later = function later() {\n timeout = null;\n if (!immediate) func.apply(context, args);\n };\n\n var callNow = immediate && !timeout;\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n if (callNow) func.apply(context, args);\n };\n};\n/**\n * Showif.js\n */\n\n\n(function () {\n var showIfElements = document.querySelectorAll('[data-showif]'); // dependent elements\n\n Array.prototype.forEach.call(showIfElements, function (element) {\n var config = JSON.parse(element.getAttribute('data-showif'));\n var parentElements = document.querySelectorAll('[name=\"' + config.element + '\"]');\n var inputs = element.querySelectorAll('input,select,textarea:not([readonly])');\n var hide = config.hide === undefined || config.hide;\n\n function toggleElement() {\n // do nothing with unchecked radio inputs\n if (this.getAttribute('type') === \"radio\" && !this.checked) {\n return;\n }\n\n var value = this.getAttribute(\"type\") === \"checkbox\" ? this.checked : this.value;\n var conditionMet = value == config.value;\n\n if (hide) {\n element.style.display = conditionMet ? '' : 'none';\n element.style.visibility = conditionMet ? '' : 'hidden';\n } else {\n element.style.opacity = conditionMet ? '' : '0.4';\n } // disable input fields to stop sending their values to server\n\n\n Array.prototype.forEach.call(inputs, function (inputElement) {\n conditionMet ? inputElement.removeAttribute('readonly') : inputElement.setAttribute('readonly', 'readonly');\n });\n } // find checked element and call toggleElement function\n\n\n Array.prototype.forEach.call(parentElements, function (parentElement) {\n toggleElement.call(parentElement);\n }); // bind on all changes\n\n helpers.bindEventToElements(parentElements, 'change', toggleElement);\n });\n})();\n\nmodule.exports = helpers;\n\n},{}],3:[function(require,module,exports){\n'use strict';\n\nvar $ = window.jQuery;\nvar config = nl4wp_vars;\nvar i18n = config.i18n;\n\nfunction ListFetcher() {\n this.working = false;\n this.done = false; // start fetching right away when no lists but api key given\n\n if (config.newsletter.api_connected && config.newsletter.lists.length === 0) {\n this.fetch();\n }\n}\n\nListFetcher.prototype.fetch = function (e) {\n e && e.preventDefault();\n this.working = true;\n this.done = false;\n $.post(ajaxurl, {\n action: \"nl4wp_renew_newsletter_lists\",\n timeout: 180000\n }).done(function (data) {\n this.success = true;\n\n if (data) {\n window.setTimeout(function () {\n window.location.reload();\n }, 3000);\n }\n }.bind(this)).fail(function (data) {\n this.success = false;\n }.bind(this)).always(function (data) {\n this.working = false;\n this.done = true;\n m.redraw();\n }.bind(this));\n};\n\nListFetcher.prototype.view = function () {\n return m('form', {\n method: \"POST\",\n onsubmit: this.fetch.bind(this)\n }, [m('p', [m('input', {\n type: \"submit\",\n value: this.working ? i18n.fetching_newsletter_lists : i18n.renew_newsletter_lists,\n className: \"button\",\n disabled: !!this.working\n }), m.trust('   '), this.working ? [m('span.nl4wp-loader', \"Loading...\"), m.trust('   '), m('em.help', i18n.fetching_newsletter_lists_can_take_a_while)] : '', this.done ? [this.success ? m('em.help.green', i18n.fetching_newsletter_lists_done) : m('em.help.red', i18n.fetching_newsletter_lists_error)] : ''])]);\n};\n\nmodule.exports = ListFetcher;\n\n},{}],4:[function(require,module,exports){\n\"use strict\";\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar Settings = function Settings(context, helpers, events) {\n 'use strict'; // vars\n\n var form = context.querySelector('form');\n var listInputs = context.querySelectorAll('.nl4wp-list-input');\n var lists = nl4wp_vars.newsletter.lists;\n var selectedLists = []; // functions\n\n function getSelectedListsWhere(searchKey, searchValue) {\n return selectedLists.filter(function (el) {\n return el[searchKey] === searchValue;\n });\n }\n\n function getSelectedLists() {\n return selectedLists;\n }\n\n function updateSelectedLists() {\n selectedLists = [];\n Array.prototype.forEach.call(listInputs, function (input) {\n // skip unchecked checkboxes\n if (typeof input.checked === \"boolean\" && !input.checked) {\n return;\n }\n\n if (_typeof(lists[input.value]) === \"object\") {\n selectedLists.push(lists[input.value]);\n }\n });\n events.trigger('selectedLists.change', [selectedLists]);\n return selectedLists;\n }\n\n function toggleVisibleLists() {\n var rows = document.querySelectorAll('.lists--only-selected > *');\n Array.prototype.forEach.call(rows, function (el) {\n var listId = el.getAttribute('data-list-id');\n var isSelected = getSelectedListsWhere('id', listId).length > 0;\n\n if (isSelected) {\n el.setAttribute('class', el.getAttribute('class').replace('hidden', ''));\n } else {\n el.setAttribute('class', el.getAttribute('class') + \" hidden\");\n }\n });\n }\n\n events.on('selectedLists.change', toggleVisibleLists);\n helpers.bindEventToElements(listInputs, 'change', updateSelectedLists);\n updateSelectedLists();\n return {\n getSelectedLists: getSelectedLists\n };\n};\n\nmodule.exports = Settings;\n\n},{}],5:[function(require,module,exports){\n'use strict';\n\nvar URL = require('./url.js'); // Tabs\n\n\nvar Tabs = function Tabs(context) {\n // TODO: last piece of jQuery... can we get rid of it?\n var $ = window.jQuery;\n var $context = $(context);\n var $tabs = $context.find('.tab');\n var $tabNavs = $context.find('.nav-tab');\n var refererField = context.querySelector('input[name=\"_wp_http_referer\"]');\n var tabs = [];\n $.each($tabs, function (i, t) {\n var id = t.id.substring(4);\n var title = $(t).find('h2').first().text();\n tabs.push({\n id: id,\n title: title,\n element: t,\n nav: context.querySelectorAll('.nav-tab-' + id),\n open: function open() {\n return _open(id);\n }\n });\n });\n\n function get(id) {\n for (var i = 0; i < tabs.length; i++) {\n if (tabs[i].id === id) {\n return tabs[i];\n }\n }\n\n return undefined;\n }\n\n function _open(tab, updateState) {\n // make sure we have a tab object\n if (typeof tab === \"string\") {\n tab = get(tab);\n }\n\n if (!tab) {\n return false;\n } // should we update state?\n\n\n if (updateState == undefined) {\n updateState = true;\n } // hide all tabs & remove active class\n\n\n $tabs.removeClass('tab-active').css('display', 'none');\n $tabNavs.removeClass('nav-tab-active'); // add `nav-tab-active` to this tab\n\n Array.prototype.forEach.call(tab.nav, function (nav) {\n nav.className += \" nav-tab-active\";\n nav.blur();\n }); // show target tab\n\n tab.element.style.display = 'block';\n tab.element.className += \" tab-active\"; // create new URL\n\n var url = URL.setParameter(window.location.href, \"tab\", tab.id); // update hash\n\n if (history.pushState && updateState) {\n history.pushState(tab.id, '', url);\n } // update document title\n\n\n title(tab); // update referer field\n\n refererField.value = url; // if thickbox is open, close it.\n\n if (typeof tb_remove === \"function\") {\n tb_remove();\n } // refresh editor after switching tabs\n // TODO: decouple this! law of demeter etc.\n\n\n if (tab.id === 'fields' && window.nl4wp && window.nl4wp.forms && window.nl4wp.forms.editor) {\n nl4wp.forms.editor.refresh();\n }\n\n return true;\n }\n\n function title(tab) {\n var title = document.title.split('-');\n document.title = document.title.replace(title[0], tab.title + \" \");\n }\n\n function switchTab(e) {\n e = e || window.event; // get from data attribute\n\n var tabId = this.getAttribute('data-tab'); // get from classname\n\n if (!tabId) {\n var match = this.className.match(/nav-tab-(\\w+)?/);\n\n if (match) {\n tabId = match[1];\n }\n } // get from href\n\n\n if (!tabId) {\n var urlParams = URL.parse(this.href);\n\n if (!urlParams.tab) {\n return;\n }\n\n tabId = urlParams.tab;\n }\n\n var opened = _open(tabId);\n\n if (opened) {\n e.preventDefault();\n e.returnValue = false;\n return false;\n }\n\n return true;\n }\n\n function init() {\n // check for current tab\n if (!history.pushState) {\n return;\n }\n\n var activeTab = $tabs.filter(':visible').get(0);\n\n if (!activeTab) {\n return;\n }\n\n var tab = get(activeTab.id.substring(4));\n if (!tab) return; // check if tab is in html5 history\n\n if (history.replaceState && history.state === null) {\n history.replaceState(tab.id, '');\n } // update document title\n\n\n title(tab);\n }\n\n $tabNavs.click(switchTab);\n $(document.body).on('click', '.tab-link', switchTab);\n init();\n\n if (window.addEventListener && history.pushState) {\n window.addEventListener('popstate', function (e) {\n if (!e.state) return true;\n var tabId = e.state;\n return _open(tabId, false);\n });\n }\n\n return {\n open: _open,\n get: get\n };\n};\n\nmodule.exports = Tabs;\n\n},{\"./url.js\":6}],6:[function(require,module,exports){\n'use strict';\n\nvar URL = {\n parse: function parse(url) {\n var query = {};\n var a = url.split('&');\n\n for (var i in a) {\n if (!a.hasOwnProperty(i)) {\n continue;\n }\n\n var b = a[i].split('=');\n query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]);\n }\n\n return query;\n },\n build: function build(data) {\n var ret = [];\n\n for (var d in data) {\n ret.push(d + \"=\" + encodeURIComponent(data[d]));\n }\n\n return ret.join(\"&\");\n },\n setParameter: function setParameter(url, key, value) {\n var data = URL.parse(url);\n data[key] = value;\n return URL.build(data);\n }\n};\nmodule.exports = URL;\n\n},{}],7:[function(require,module,exports){\n(function (global,setImmediate){\n;(function() {\n\"use strict\"\nfunction Vnode(tag, key, attrs0, children, text, dom) {\n\treturn {tag: tag, key: key, attrs: attrs0, children: children, text: text, dom: dom, domSize: undefined, state: undefined, _state: undefined, events: undefined, instance: undefined, skip: false}\n}\nVnode.normalize = function(node) {\n\tif (Array.isArray(node)) return Vnode(\"[\", undefined, undefined, Vnode.normalizeChildren(node), undefined, undefined)\n\tif (node != null && typeof node !== \"object\") return Vnode(\"#\", undefined, undefined, node === false ? \"\" : node, undefined, undefined)\n\treturn node\n}\nVnode.normalizeChildren = function normalizeChildren(children) {\n\tfor (var i = 0; i < children.length; i++) {\n\t\tchildren[i] = Vnode.normalize(children[i])\n\t}\n\treturn children\n}\nvar selectorParser = /(?:(^|#|\\.)([^#\\.\\[\\]]+))|(\\[(.+?)(?:\\s*=\\s*(\"|'|)((?:\\\\[\"'\\]]|.)*?)\\5)?\\])/g\nvar selectorCache = {}\nvar hasOwn = {}.hasOwnProperty\nfunction isEmpty(object) {\n\tfor (var key in object) if (hasOwn.call(object, key)) return false\n\treturn true\n}\nfunction compileSelector(selector) {\n\tvar match, tag = \"div\", classes = [], attrs = {}\n\twhile (match = selectorParser.exec(selector)) {\n\t\tvar type = match[1], value = match[2]\n\t\tif (type === \"\" && value !== \"\") tag = value\n\t\telse if (type === \"#\") attrs.id = value\n\t\telse if (type === \".\") classes.push(value)\n\t\telse if (match[3][0] === \"[\") {\n\t\t\tvar attrValue = match[6]\n\t\t\tif (attrValue) attrValue = attrValue.replace(/\\\\([\"'])/g, \"$1\").replace(/\\\\\\\\/g, \"\\\\\")\n\t\t\tif (match[4] === \"class\") classes.push(attrValue)\n\t\t\telse attrs[match[4]] = attrValue === \"\" ? attrValue : attrValue || true\n\t\t}\n\t}\n\tif (classes.length > 0) attrs.className = classes.join(\" \")\n\treturn selectorCache[selector] = {tag: tag, attrs: attrs}\n}\nfunction execSelector(state, attrs, children) {\n\tvar hasAttrs = false, childList, text\n\tvar className = attrs.className || attrs.class\n\tif (!isEmpty(state.attrs) && !isEmpty(attrs)) {\n\t\tvar newAttrs = {}\n\t\tfor(var key in attrs) {\n\t\t\tif (hasOwn.call(attrs, key)) {\n\t\t\t\tnewAttrs[key] = attrs[key]\n\t\t\t}\n\t\t}\n\t\tattrs = newAttrs\n\t}\n\tfor (var key in state.attrs) {\n\t\tif (hasOwn.call(state.attrs, key)) {\n\t\t\tattrs[key] = state.attrs[key]\n\t\t}\n\t}\n\tif (className !== undefined) {\n\t\tif (attrs.class !== undefined) {\n\t\t\tattrs.class = undefined\n\t\t\tattrs.className = className\n\t\t}\n\t\tif (state.attrs.className != null) {\n\t\t\tattrs.className = state.attrs.className + \" \" + className\n\t\t}\n\t}\n\tfor (var key in attrs) {\n\t\tif (hasOwn.call(attrs, key) && key !== \"key\") {\n\t\t\thasAttrs = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif (Array.isArray(children) && children.length === 1 && children[0] != null && children[0].tag === \"#\") {\n\t\ttext = children[0].children\n\t} else {\n\t\tchildList = children\n\t}\n\treturn Vnode(state.tag, attrs.key, hasAttrs ? attrs : undefined, childList, text)\n}\nfunction hyperscript(selector) {\n\t// Because sloppy mode sucks\n\tvar attrs = arguments[1], start = 2, children\n\tif (selector == null || typeof selector !== \"string\" && typeof selector !== \"function\" && typeof selector.view !== \"function\") {\n\t\tthrow Error(\"The selector must be either a string or a component.\");\n\t}\n\tif (typeof selector === \"string\") {\n\t\tvar cached = selectorCache[selector] || compileSelector(selector)\n\t}\n\tif (attrs == null) {\n\t\tattrs = {}\n\t} else if (typeof attrs !== \"object\" || attrs.tag != null || Array.isArray(attrs)) {\n\t\tattrs = {}\n\t\tstart = 1\n\t}\n\tif (arguments.length === start + 1) {\n\t\tchildren = arguments[start]\n\t\tif (!Array.isArray(children)) children = [children]\n\t} else {\n\t\tchildren = []\n\t\twhile (start < arguments.length) children.push(arguments[start++])\n\t}\n\tvar normalized = Vnode.normalizeChildren(children)\n\tif (typeof selector === \"string\") {\n\t\treturn execSelector(cached, attrs, normalized)\n\t} else {\n\t\treturn Vnode(selector, attrs.key, attrs, normalized)\n\t}\n}\nhyperscript.trust = function(html) {\n\tif (html == null) html = \"\"\n\treturn Vnode(\"<\", undefined, undefined, html, undefined, undefined)\n}\nhyperscript.fragment = function(attrs1, children) {\n\treturn Vnode(\"[\", attrs1.key, attrs1, Vnode.normalizeChildren(children), undefined, undefined)\n}\nvar m = hyperscript\n/** @constructor */\nvar PromisePolyfill = function(executor) {\n\tif (!(this instanceof PromisePolyfill)) throw new Error(\"Promise must be called with `new`\")\n\tif (typeof executor !== \"function\") throw new TypeError(\"executor must be a function\")\n\tvar self = this, resolvers = [], rejectors = [], resolveCurrent = handler(resolvers, true), rejectCurrent = handler(rejectors, false)\n\tvar instance = self._instance = {resolvers: resolvers, rejectors: rejectors}\n\tvar callAsync = typeof setImmediate === \"function\" ? setImmediate : setTimeout\n\tfunction handler(list, shouldAbsorb) {\n\t\treturn function execute(value) {\n\t\t\tvar then\n\t\t\ttry {\n\t\t\t\tif (shouldAbsorb && value != null && (typeof value === \"object\" || typeof value === \"function\") && typeof (then = value.then) === \"function\") {\n\t\t\t\t\tif (value === self) throw new TypeError(\"Promise can't be resolved w/ itself\")\n\t\t\t\t\texecuteOnce(then.bind(value))\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcallAsync(function() {\n\t\t\t\t\t\tif (!shouldAbsorb && list.length === 0) console.error(\"Possible unhandled promise rejection:\", value)\n\t\t\t\t\t\tfor (var i = 0; i < list.length; i++) list[i](value)\n\t\t\t\t\t\tresolvers.length = 0, rejectors.length = 0\n\t\t\t\t\t\tinstance.state = shouldAbsorb\n\t\t\t\t\t\tinstance.retry = function() {execute(value)}\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\trejectCurrent(e)\n\t\t\t}\n\t\t}\n\t}\n\tfunction executeOnce(then) {\n\t\tvar runs = 0\n\t\tfunction run(fn) {\n\t\t\treturn function(value) {\n\t\t\t\tif (runs++ > 0) return\n\t\t\t\tfn(value)\n\t\t\t}\n\t\t}\n\t\tvar onerror = run(rejectCurrent)\n\t\ttry {then(run(resolveCurrent), onerror)} catch (e) {onerror(e)}\n\t}\n\texecuteOnce(executor)\n}\nPromisePolyfill.prototype.then = function(onFulfilled, onRejection) {\n\tvar self = this, instance = self._instance\n\tfunction handle(callback, list, next, state) {\n\t\tlist.push(function(value) {\n\t\t\tif (typeof callback !== \"function\") next(value)\n\t\t\telse try {resolveNext(callback(value))} catch (e) {if (rejectNext) rejectNext(e)}\n\t\t})\n\t\tif (typeof instance.retry === \"function\" && state === instance.state) instance.retry()\n\t}\n\tvar resolveNext, rejectNext\n\tvar promise = new PromisePolyfill(function(resolve, reject) {resolveNext = resolve, rejectNext = reject})\n\thandle(onFulfilled, instance.resolvers, resolveNext, true), handle(onRejection, instance.rejectors, rejectNext, false)\n\treturn promise\n}\nPromisePolyfill.prototype.catch = function(onRejection) {\n\treturn this.then(null, onRejection)\n}\nPromisePolyfill.resolve = function(value) {\n\tif (value instanceof PromisePolyfill) return value\n\treturn new PromisePolyfill(function(resolve) {resolve(value)})\n}\nPromisePolyfill.reject = function(value) {\n\treturn new PromisePolyfill(function(resolve, reject) {reject(value)})\n}\nPromisePolyfill.all = function(list) {\n\treturn new PromisePolyfill(function(resolve, reject) {\n\t\tvar total = list.length, count = 0, values = []\n\t\tif (list.length === 0) resolve([])\n\t\telse for (var i = 0; i < list.length; i++) {\n\t\t\t(function(i) {\n\t\t\t\tfunction consume(value) {\n\t\t\t\t\tcount++\n\t\t\t\t\tvalues[i] = value\n\t\t\t\t\tif (count === total) resolve(values)\n\t\t\t\t}\n\t\t\t\tif (list[i] != null && (typeof list[i] === \"object\" || typeof list[i] === \"function\") && typeof list[i].then === \"function\") {\n\t\t\t\t\tlist[i].then(consume, reject)\n\t\t\t\t}\n\t\t\t\telse consume(list[i])\n\t\t\t})(i)\n\t\t}\n\t})\n}\nPromisePolyfill.race = function(list) {\n\treturn new PromisePolyfill(function(resolve, reject) {\n\t\tfor (var i = 0; i < list.length; i++) {\n\t\t\tlist[i].then(resolve, reject)\n\t\t}\n\t})\n}\nif (typeof window !== \"undefined\") {\n\tif (typeof window.Promise === \"undefined\") window.Promise = PromisePolyfill\n\tvar PromisePolyfill = window.Promise\n} else if (typeof global !== \"undefined\") {\n\tif (typeof global.Promise === \"undefined\") global.Promise = PromisePolyfill\n\tvar PromisePolyfill = global.Promise\n} else {\n}\nvar buildQueryString = function(object) {\n\tif (Object.prototype.toString.call(object) !== \"[object Object]\") return \"\"\n\tvar args = []\n\tfor (var key0 in object) {\n\t\tdestructure(key0, object[key0])\n\t}\n\treturn args.join(\"&\")\n\tfunction destructure(key0, value) {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (var i = 0; i < value.length; i++) {\n\t\t\t\tdestructure(key0 + \"[\" + i + \"]\", value[i])\n\t\t\t}\n\t\t}\n\t\telse if (Object.prototype.toString.call(value) === \"[object Object]\") {\n\t\t\tfor (var i in value) {\n\t\t\t\tdestructure(key0 + \"[\" + i + \"]\", value[i])\n\t\t\t}\n\t\t}\n\t\telse args.push(encodeURIComponent(key0) + (value != null && value !== \"\" ? \"=\" + encodeURIComponent(value) : \"\"))\n\t}\n}\nvar FILE_PROTOCOL_REGEX = new RegExp(\"^file://\", \"i\")\nvar _8 = function($window, Promise) {\n\tvar callbackCount = 0\n\tvar oncompletion\n\tfunction setCompletionCallback(callback) {oncompletion = callback}\n\tfunction finalizer() {\n\t\tvar count = 0\n\t\tfunction complete() {if (--count === 0 && typeof oncompletion === \"function\") oncompletion()}\n\t\treturn function finalize(promise0) {\n\t\t\tvar then0 = promise0.then\n\t\t\tpromise0.then = function() {\n\t\t\t\tcount++\n\t\t\t\tvar next = then0.apply(promise0, arguments)\n\t\t\t\tnext.then(complete, function(e) {\n\t\t\t\t\tcomplete()\n\t\t\t\t\tif (count === 0) throw e\n\t\t\t\t})\n\t\t\t\treturn finalize(next)\n\t\t\t}\n\t\t\treturn promise0\n\t\t}\n\t}\n\tfunction normalize(args, extra) {\n\t\tif (typeof args === \"string\") {\n\t\t\tvar url = args\n\t\t\targs = extra || {}\n\t\t\tif (args.url == null) args.url = url\n\t\t}\n\t\treturn args\n\t}\n\tfunction request(args, extra) {\n\t\tvar finalize = finalizer()\n\t\targs = normalize(args, extra)\n\t\tvar promise0 = new Promise(function(resolve, reject) {\n\t\t\tif (args.method == null) args.method = \"GET\"\n\t\t\targs.method = args.method.toUpperCase()\n\t\t\tvar useBody = (args.method === \"GET\" || args.method === \"TRACE\") ? false : (typeof args.useBody === \"boolean\" ? args.useBody : true)\n\t\t\tif (typeof args.serialize !== \"function\") args.serialize = typeof FormData !== \"undefined\" && args.data instanceof FormData ? function(value) {return value} : JSON.stringify\n\t\t\tif (typeof args.deserialize !== \"function\") args.deserialize = deserialize\n\t\t\tif (typeof args.extract !== \"function\") args.extract = extract\n\t\t\targs.url = interpolate(args.url, args.data)\n\t\t\tif (useBody) args.data = args.serialize(args.data)\n\t\t\telse args.url = assemble(args.url, args.data)\n\t\t\tvar xhr = new $window.XMLHttpRequest(),\n\t\t\t\taborted = false,\n\t\t\t\t_abort = xhr.abort\n\t\t\txhr.abort = function abort() {\n\t\t\t\taborted = true\n\t\t\t\t_abort.call(xhr)\n\t\t\t}\n\t\t\txhr.open(args.method, args.url, typeof args.async === \"boolean\" ? args.async : true, typeof args.user === \"string\" ? args.user : undefined, typeof args.password === \"string\" ? args.password : undefined)\n\t\t\tif (args.serialize === JSON.stringify && useBody && !(args.headers && args.headers.hasOwnProperty(\"Content-Type\"))) {\n\t\t\t\txhr.setRequestHeader(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\t\t}\n\t\t\tif (args.deserialize === deserialize && !(args.headers && args.headers.hasOwnProperty(\"Accept\"))) {\n\t\t\t\txhr.setRequestHeader(\"Accept\", \"application/json, text/*\")\n\t\t\t}\n\t\t\tif (args.withCredentials) xhr.withCredentials = args.withCredentials\n\t\t\tfor (var key in args.headers) if ({}.hasOwnProperty.call(args.headers, key)) {\n\t\t\t\txhr.setRequestHeader(key, args.headers[key])\n\t\t\t}\n\t\t\tif (typeof args.config === \"function\") xhr = args.config(xhr, args) || xhr\n\t\t\txhr.onreadystatechange = function() {\n\t\t\t\t// Don't throw errors on xhr.abort().\n\t\t\t\tif(aborted) return\n\t\t\t\tif (xhr.readyState === 4) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tvar response = (args.extract !== extract) ? args.extract(xhr, args) : args.deserialize(args.extract(xhr, args))\n\t\t\t\t\t\tif ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || FILE_PROTOCOL_REGEX.test(args.url)) {\n\t\t\t\t\t\t\tresolve(cast(args.type, response))\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tvar error = new Error(xhr.responseText)\n\t\t\t\t\t\t\tfor (var key in response) error[key] = response[key]\n\t\t\t\t\t\t\treject(error)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\treject(e)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (useBody && (args.data != null)) xhr.send(args.data)\n\t\t\telse xhr.send()\n\t\t})\n\t\treturn args.background === true ? promise0 : finalize(promise0)\n\t}\n\tfunction jsonp(args, extra) {\n\t\tvar finalize = finalizer()\n\t\targs = normalize(args, extra)\n\t\tvar promise0 = new Promise(function(resolve, reject) {\n\t\t\tvar callbackName = args.callbackName || \"_mithril_\" + Math.round(Math.random() * 1e16) + \"_\" + callbackCount++\n\t\t\tvar script = $window.document.createElement(\"script\")\n\t\t\t$window[callbackName] = function(data) {\n\t\t\t\tscript.parentNode.removeChild(script)\n\t\t\t\tresolve(cast(args.type, data))\n\t\t\t\tdelete $window[callbackName]\n\t\t\t}\n\t\t\tscript.onerror = function() {\n\t\t\t\tscript.parentNode.removeChild(script)\n\t\t\t\treject(new Error(\"JSONP request failed\"))\n\t\t\t\tdelete $window[callbackName]\n\t\t\t}\n\t\t\tif (args.data == null) args.data = {}\n\t\t\targs.url = interpolate(args.url, args.data)\n\t\t\targs.data[args.callbackKey || \"callback\"] = callbackName\n\t\t\tscript.src = assemble(args.url, args.data)\n\t\t\t$window.document.documentElement.appendChild(script)\n\t\t})\n\t\treturn args.background === true? promise0 : finalize(promise0)\n\t}\n\tfunction interpolate(url, data) {\n\t\tif (data == null) return url\n\t\tvar tokens = url.match(/:[^\\/]+/gi) || []\n\t\tfor (var i = 0; i < tokens.length; i++) {\n\t\t\tvar key = tokens[i].slice(1)\n\t\t\tif (data[key] != null) {\n\t\t\t\turl = url.replace(tokens[i], data[key])\n\t\t\t}\n\t\t}\n\t\treturn url\n\t}\n\tfunction assemble(url, data) {\n\t\tvar querystring = buildQueryString(data)\n\t\tif (querystring !== \"\") {\n\t\t\tvar prefix = url.indexOf(\"?\") < 0 ? \"?\" : \"&\"\n\t\t\turl += prefix + querystring\n\t\t}\n\t\treturn url\n\t}\n\tfunction deserialize(data) {\n\t\ttry {return data !== \"\" ? JSON.parse(data) : null}\n\t\tcatch (e) {throw new Error(data)}\n\t}\n\tfunction extract(xhr) {return xhr.responseText}\n\tfunction cast(type0, data) {\n\t\tif (typeof type0 === \"function\") {\n\t\t\tif (Array.isArray(data)) {\n\t\t\t\tfor (var i = 0; i < data.length; i++) {\n\t\t\t\t\tdata[i] = new type0(data[i])\n\t\t\t\t}\n\t\t\t}\n\t\t\telse return new type0(data)\n\t\t}\n\t\treturn data\n\t}\n\treturn {request: request, jsonp: jsonp, setCompletionCallback: setCompletionCallback}\n}\nvar requestService = _8(window, PromisePolyfill)\nvar coreRenderer = function($window) {\n\tvar $doc = $window.document\n\tvar $emptyFragment = $doc.createDocumentFragment()\n\tvar nameSpace = {\n\t\tsvg: \"http://www.w3.org/2000/svg\",\n\t\tmath: \"http://www.w3.org/1998/Math/MathML\"\n\t}\n\tvar onevent\n\tfunction setEventCallback(callback) {return onevent = callback}\n\tfunction getNameSpace(vnode) {\n\t\treturn vnode.attrs && vnode.attrs.xmlns || nameSpace[vnode.tag]\n\t}\n\t//create\n\tfunction createNodes(parent, vnodes, start, end, hooks, nextSibling, ns) {\n\t\tfor (var i = start; i < end; i++) {\n\t\t\tvar vnode = vnodes[i]\n\t\t\tif (vnode != null) {\n\t\t\t\tcreateNode(parent, vnode, hooks, ns, nextSibling)\n\t\t\t}\n\t\t}\n\t}\n\tfunction createNode(parent, vnode, hooks, ns, nextSibling) {\n\t\tvar tag = vnode.tag\n\t\tif (typeof tag === \"string\") {\n\t\t\tvnode.state = {}\n\t\t\tif (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)\n\t\t\tswitch (tag) {\n\t\t\t\tcase \"#\": return createText(parent, vnode, nextSibling)\n\t\t\t\tcase \"<\": return createHTML(parent, vnode, nextSibling)\n\t\t\t\tcase \"[\": return createFragment(parent, vnode, hooks, ns, nextSibling)\n\t\t\t\tdefault: return createElement(parent, vnode, hooks, ns, nextSibling)\n\t\t\t}\n\t\t}\n\t\telse return createComponent(parent, vnode, hooks, ns, nextSibling)\n\t}\n\tfunction createText(parent, vnode, nextSibling) {\n\t\tvnode.dom = $doc.createTextNode(vnode.children)\n\t\tinsertNode(parent, vnode.dom, nextSibling)\n\t\treturn vnode.dom\n\t}\n\tfunction createHTML(parent, vnode, nextSibling) {\n\t\tvar match1 = vnode.children.match(/^\\s*?<(\\w+)/im) || []\n\t\tvar parent1 = {caption: \"table\", thead: \"table\", tbody: \"table\", tfoot: \"table\", tr: \"tbody\", th: \"tr\", td: \"tr\", colgroup: \"table\", col: \"colgroup\"}[match1[1]] || \"div\"\n\t\tvar temp = $doc.createElement(parent1)\n\t\ttemp.innerHTML = vnode.children\n\t\tvnode.dom = temp.firstChild\n\t\tvnode.domSize = temp.childNodes.length\n\t\tvar fragment = $doc.createDocumentFragment()\n\t\tvar child\n\t\twhile (child = temp.firstChild) {\n\t\t\tfragment.appendChild(child)\n\t\t}\n\t\tinsertNode(parent, fragment, nextSibling)\n\t\treturn fragment\n\t}\n\tfunction createFragment(parent, vnode, hooks, ns, nextSibling) {\n\t\tvar fragment = $doc.createDocumentFragment()\n\t\tif (vnode.children != null) {\n\t\t\tvar children = vnode.children\n\t\t\tcreateNodes(fragment, children, 0, children.length, hooks, null, ns)\n\t\t}\n\t\tvnode.dom = fragment.firstChild\n\t\tvnode.domSize = fragment.childNodes.length\n\t\tinsertNode(parent, fragment, nextSibling)\n\t\treturn fragment\n\t}\n\tfunction createElement(parent, vnode, hooks, ns, nextSibling) {\n\t\tvar tag = vnode.tag\n\t\tvar attrs2 = vnode.attrs\n\t\tvar is = attrs2 && attrs2.is\n\t\tns = getNameSpace(vnode) || ns\n\t\tvar element = ns ?\n\t\t\tis ? $doc.createElementNS(ns, tag, {is: is}) : $doc.createElementNS(ns, tag) :\n\t\t\tis ? $doc.createElement(tag, {is: is}) : $doc.createElement(tag)\n\t\tvnode.dom = element\n\t\tif (attrs2 != null) {\n\t\t\tsetAttrs(vnode, attrs2, ns)\n\t\t}\n\t\tinsertNode(parent, element, nextSibling)\n\t\tif (vnode.attrs != null && vnode.attrs.contenteditable != null) {\n\t\t\tsetContentEditable(vnode)\n\t\t}\n\t\telse {\n\t\t\tif (vnode.text != null) {\n\t\t\t\tif (vnode.text !== \"\") element.textContent = vnode.text\n\t\t\t\telse vnode.children = [Vnode(\"#\", undefined, undefined, vnode.text, undefined, undefined)]\n\t\t\t}\n\t\t\tif (vnode.children != null) {\n\t\t\t\tvar children = vnode.children\n\t\t\t\tcreateNodes(element, children, 0, children.length, hooks, null, ns)\n\t\t\t\tsetLateAttrs(vnode)\n\t\t\t}\n\t\t}\n\t\treturn element\n\t}\n\tfunction initComponent(vnode, hooks) {\n\t\tvar sentinel\n\t\tif (typeof vnode.tag.view === \"function\") {\n\t\t\tvnode.state = Object.create(vnode.tag)\n\t\t\tsentinel = vnode.state.view\n\t\t\tif (sentinel.$$reentrantLock$$ != null) return $emptyFragment\n\t\t\tsentinel.$$reentrantLock$$ = true\n\t\t} else {\n\t\t\tvnode.state = void 0\n\t\t\tsentinel = vnode.tag\n\t\t\tif (sentinel.$$reentrantLock$$ != null) return $emptyFragment\n\t\t\tsentinel.$$reentrantLock$$ = true\n\t\t\tvnode.state = (vnode.tag.prototype != null && typeof vnode.tag.prototype.view === \"function\") ? new vnode.tag(vnode) : vnode.tag(vnode)\n\t\t}\n\t\tvnode._state = vnode.state\n\t\tif (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)\n\t\tinitLifecycle(vnode._state, vnode, hooks)\n\t\tvnode.instance = Vnode.normalize(vnode._state.view.call(vnode.state, vnode))\n\t\tif (vnode.instance === vnode) throw Error(\"A view cannot return the vnode it received as argument\")\n\t\tsentinel.$$reentrantLock$$ = null\n\t}\n\tfunction createComponent(parent, vnode, hooks, ns, nextSibling) {\n\t\tinitComponent(vnode, hooks)\n\t\tif (vnode.instance != null) {\n\t\t\tvar element = createNode(parent, vnode.instance, hooks, ns, nextSibling)\n\t\t\tvnode.dom = vnode.instance.dom\n\t\t\tvnode.domSize = vnode.dom != null ? vnode.instance.domSize : 0\n\t\t\tinsertNode(parent, element, nextSibling)\n\t\t\treturn element\n\t\t}\n\t\telse {\n\t\t\tvnode.domSize = 0\n\t\t\treturn $emptyFragment\n\t\t}\n\t}\n\t//update\n\tfunction updateNodes(parent, old, vnodes, recycling, hooks, nextSibling, ns) {\n\t\tif (old === vnodes || old == null && vnodes == null) return\n\t\telse if (old == null) createNodes(parent, vnodes, 0, vnodes.length, hooks, nextSibling, ns)\n\t\telse if (vnodes == null) removeNodes(old, 0, old.length, vnodes)\n\t\telse {\n\t\t\tif (old.length === vnodes.length) {\n\t\t\t\tvar isUnkeyed = false\n\t\t\t\tfor (var i = 0; i < vnodes.length; i++) {\n\t\t\t\t\tif (vnodes[i] != null && old[i] != null) {\n\t\t\t\t\t\tisUnkeyed = vnodes[i].key == null && old[i].key == null\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (isUnkeyed) {\n\t\t\t\t\tfor (var i = 0; i < old.length; i++) {\n\t\t\t\t\t\tif (old[i] === vnodes[i]) continue\n\t\t\t\t\t\telse if (old[i] == null && vnodes[i] != null) createNode(parent, vnodes[i], hooks, ns, getNextSibling(old, i + 1, nextSibling))\n\t\t\t\t\t\telse if (vnodes[i] == null) removeNodes(old, i, i + 1, vnodes)\n\t\t\t\t\t\telse updateNode(parent, old[i], vnodes[i], hooks, getNextSibling(old, i + 1, nextSibling), recycling, ns)\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\trecycling = recycling || isRecyclable(old, vnodes)\n\t\t\tif (recycling) {\n\t\t\t\tvar pool = old.pool\n\t\t\t\told = old.concat(old.pool)\n\t\t\t}\n\t\t\tvar oldStart = 0, start = 0, oldEnd = old.length - 1, end = vnodes.length - 1, map\n\t\t\twhile (oldEnd >= oldStart && end >= start) {\n\t\t\t\tvar o = old[oldStart], v = vnodes[start]\n\t\t\t\tif (o === v && !recycling) oldStart++, start++\n\t\t\t\telse if (o == null) oldStart++\n\t\t\t\telse if (v == null) start++\n\t\t\t\telse if (o.key === v.key) {\n\t\t\t\t\tvar shouldRecycle = (pool != null && oldStart >= old.length - pool.length) || ((pool == null) && recycling)\n\t\t\t\t\toldStart++, start++\n\t\t\t\t\tupdateNode(parent, o, v, hooks, getNextSibling(old, oldStart, nextSibling), shouldRecycle, ns)\n\t\t\t\t\tif (recycling && o.tag === v.tag) insertNode(parent, toFragment(o), nextSibling)\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tvar o = old[oldEnd]\n\t\t\t\t\tif (o === v && !recycling) oldEnd--, start++\n\t\t\t\t\telse if (o == null) oldEnd--\n\t\t\t\t\telse if (v == null) start++\n\t\t\t\t\telse if (o.key === v.key) {\n\t\t\t\t\t\tvar shouldRecycle = (pool != null && oldEnd >= old.length - pool.length) || ((pool == null) && recycling)\n\t\t\t\t\t\tupdateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), shouldRecycle, ns)\n\t\t\t\t\t\tif (recycling || start < end) insertNode(parent, toFragment(o), getNextSibling(old, oldStart, nextSibling))\n\t\t\t\t\t\toldEnd--, start++\n\t\t\t\t\t}\n\t\t\t\t\telse break\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile (oldEnd >= oldStart && end >= start) {\n\t\t\t\tvar o = old[oldEnd], v = vnodes[end]\n\t\t\t\tif (o === v && !recycling) oldEnd--, end--\n\t\t\t\telse if (o == null) oldEnd--\n\t\t\t\telse if (v == null) end--\n\t\t\t\telse if (o.key === v.key) {\n\t\t\t\t\tvar shouldRecycle = (pool != null && oldEnd >= old.length - pool.length) || ((pool == null) && recycling)\n\t\t\t\t\tupdateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), shouldRecycle, ns)\n\t\t\t\t\tif (recycling && o.tag === v.tag) insertNode(parent, toFragment(o), nextSibling)\n\t\t\t\t\tif (o.dom != null) nextSibling = o.dom\n\t\t\t\t\toldEnd--, end--\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!map) map = getKeyMap(old, oldEnd)\n\t\t\t\t\tif (v != null) {\n\t\t\t\t\t\tvar oldIndex = map[v.key]\n\t\t\t\t\t\tif (oldIndex != null) {\n\t\t\t\t\t\t\tvar movable = old[oldIndex]\n\t\t\t\t\t\t\tvar shouldRecycle = (pool != null && oldIndex >= old.length - pool.length) || ((pool == null) && recycling)\n\t\t\t\t\t\t\tupdateNode(parent, movable, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), recycling, ns)\n\t\t\t\t\t\t\tinsertNode(parent, toFragment(movable), nextSibling)\n\t\t\t\t\t\t\told[oldIndex].skip = true\n\t\t\t\t\t\t\tif (movable.dom != null) nextSibling = movable.dom\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tvar dom = createNode(parent, v, hooks, ns, nextSibling)\n\t\t\t\t\t\t\tnextSibling = dom\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tend--\n\t\t\t\t}\n\t\t\t\tif (end < start) break\n\t\t\t}\n\t\t\tcreateNodes(parent, vnodes, start, end + 1, hooks, nextSibling, ns)\n\t\t\tremoveNodes(old, oldStart, oldEnd + 1, vnodes)\n\t\t}\n\t}\n\tfunction updateNode(parent, old, vnode, hooks, nextSibling, recycling, ns) {\n\t\tvar oldTag = old.tag, tag = vnode.tag\n\t\tif (oldTag === tag) {\n\t\t\tvnode.state = old.state\n\t\t\tvnode._state = old._state\n\t\t\tvnode.events = old.events\n\t\t\tif (!recycling && shouldNotUpdate(vnode, old)) return\n\t\t\tif (typeof oldTag === \"string\") {\n\t\t\t\tif (vnode.attrs != null) {\n\t\t\t\t\tif (recycling) {\n\t\t\t\t\t\tvnode.state = {}\n\t\t\t\t\t\tinitLifecycle(vnode.attrs, vnode, hooks)\n\t\t\t\t\t}\n\t\t\t\t\telse updateLifecycle(vnode.attrs, vnode, hooks)\n\t\t\t\t}\n\t\t\t\tswitch (oldTag) {\n\t\t\t\t\tcase \"#\": updateText(old, vnode); break\n\t\t\t\t\tcase \"<\": updateHTML(parent, old, vnode, nextSibling); break\n\t\t\t\t\tcase \"[\": updateFragment(parent, old, vnode, recycling, hooks, nextSibling, ns); break\n\t\t\t\t\tdefault: updateElement(old, vnode, recycling, hooks, ns)\n\t\t\t\t}\n\t\t\t}\n\t\t\telse updateComponent(parent, old, vnode, hooks, nextSibling, recycling, ns)\n\t\t}\n\t\telse {\n\t\t\tremoveNode(old, null)\n\t\t\tcreateNode(parent, vnode, hooks, ns, nextSibling)\n\t\t}\n\t}\n\tfunction updateText(old, vnode) {\n\t\tif (old.children.toString() !== vnode.children.toString()) {\n\t\t\told.dom.nodeValue = vnode.children\n\t\t}\n\t\tvnode.dom = old.dom\n\t}\n\tfunction updateHTML(parent, old, vnode, nextSibling) {\n\t\tif (old.children !== vnode.children) {\n\t\t\ttoFragment(old)\n\t\t\tcreateHTML(parent, vnode, nextSibling)\n\t\t}\n\t\telse vnode.dom = old.dom, vnode.domSize = old.domSize\n\t}\n\tfunction updateFragment(parent, old, vnode, recycling, hooks, nextSibling, ns) {\n\t\tupdateNodes(parent, old.children, vnode.children, recycling, hooks, nextSibling, ns)\n\t\tvar domSize = 0, children = vnode.children\n\t\tvnode.dom = null\n\t\tif (children != null) {\n\t\t\tfor (var i = 0; i < children.length; i++) {\n\t\t\t\tvar child = children[i]\n\t\t\t\tif (child != null && child.dom != null) {\n\t\t\t\t\tif (vnode.dom == null) vnode.dom = child.dom\n\t\t\t\t\tdomSize += child.domSize || 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (domSize !== 1) vnode.domSize = domSize\n\t\t}\n\t}\n\tfunction updateElement(old, vnode, recycling, hooks, ns) {\n\t\tvar element = vnode.dom = old.dom\n\t\tns = getNameSpace(vnode) || ns\n\t\tif (vnode.tag === \"textarea\") {\n\t\t\tif (vnode.attrs == null) vnode.attrs = {}\n\t\t\tif (vnode.text != null) {\n\t\t\t\tvnode.attrs.value = vnode.text //FIXME handle0 multiple children\n\t\t\t\tvnode.text = undefined\n\t\t\t}\n\t\t}\n\t\tupdateAttrs(vnode, old.attrs, vnode.attrs, ns)\n\t\tif (vnode.attrs != null && vnode.attrs.contenteditable != null) {\n\t\t\tsetContentEditable(vnode)\n\t\t}\n\t\telse if (old.text != null && vnode.text != null && vnode.text !== \"\") {\n\t\t\tif (old.text.toString() !== vnode.text.toString()) old.dom.firstChild.nodeValue = vnode.text\n\t\t}\n\t\telse {\n\t\t\tif (old.text != null) old.children = [Vnode(\"#\", undefined, undefined, old.text, undefined, old.dom.firstChild)]\n\t\t\tif (vnode.text != null) vnode.children = [Vnode(\"#\", undefined, undefined, vnode.text, undefined, undefined)]\n\t\t\tupdateNodes(element, old.children, vnode.children, recycling, hooks, null, ns)\n\t\t}\n\t}\n\tfunction updateComponent(parent, old, vnode, hooks, nextSibling, recycling, ns) {\n\t\tif (recycling) {\n\t\t\tinitComponent(vnode, hooks)\n\t\t} else {\n\t\t\tvnode.instance = Vnode.normalize(vnode._state.view.call(vnode.state, vnode))\n\t\t\tif (vnode.instance === vnode) throw Error(\"A view cannot return the vnode it received as argument\")\n\t\t\tif (vnode.attrs != null) updateLifecycle(vnode.attrs, vnode, hooks)\n\t\t\tupdateLifecycle(vnode._state, vnode, hooks)\n\t\t}\n\t\tif (vnode.instance != null) {\n\t\t\tif (old.instance == null) createNode(parent, vnode.instance, hooks, ns, nextSibling)\n\t\t\telse updateNode(parent, old.instance, vnode.instance, hooks, nextSibling, recycling, ns)\n\t\t\tvnode.dom = vnode.instance.dom\n\t\t\tvnode.domSize = vnode.instance.domSize\n\t\t}\n\t\telse if (old.instance != null) {\n\t\t\tremoveNode(old.instance, null)\n\t\t\tvnode.dom = undefined\n\t\t\tvnode.domSize = 0\n\t\t}\n\t\telse {\n\t\t\tvnode.dom = old.dom\n\t\t\tvnode.domSize = old.domSize\n\t\t}\n\t}\n\tfunction isRecyclable(old, vnodes) {\n\t\tif (old.pool != null && Math.abs(old.pool.length - vnodes.length) <= Math.abs(old.length - vnodes.length)) {\n\t\t\tvar oldChildrenLength = old[0] && old[0].children && old[0].children.length || 0\n\t\t\tvar poolChildrenLength = old.pool[0] && old.pool[0].children && old.pool[0].children.length || 0\n\t\t\tvar vnodesChildrenLength = vnodes[0] && vnodes[0].children && vnodes[0].children.length || 0\n\t\t\tif (Math.abs(poolChildrenLength - vnodesChildrenLength) <= Math.abs(oldChildrenLength - vnodesChildrenLength)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfunction getKeyMap(vnodes, end) {\n\t\tvar map = {}, i = 0\n\t\tfor (var i = 0; i < end; i++) {\n\t\t\tvar vnode = vnodes[i]\n\t\t\tif (vnode != null) {\n\t\t\t\tvar key2 = vnode.key\n\t\t\t\tif (key2 != null) map[key2] = i\n\t\t\t}\n\t\t}\n\t\treturn map\n\t}\n\tfunction toFragment(vnode) {\n\t\tvar count0 = vnode.domSize\n\t\tif (count0 != null || vnode.dom == null) {\n\t\t\tvar fragment = $doc.createDocumentFragment()\n\t\t\tif (count0 > 0) {\n\t\t\t\tvar dom = vnode.dom\n\t\t\t\twhile (--count0) fragment.appendChild(dom.nextSibling)\n\t\t\t\tfragment.insertBefore(dom, fragment.firstChild)\n\t\t\t}\n\t\t\treturn fragment\n\t\t}\n\t\telse return vnode.dom\n\t}\n\tfunction getNextSibling(vnodes, i, nextSibling) {\n\t\tfor (; i < vnodes.length; i++) {\n\t\t\tif (vnodes[i] != null && vnodes[i].dom != null) return vnodes[i].dom\n\t\t}\n\t\treturn nextSibling\n\t}\n\tfunction insertNode(parent, dom, nextSibling) {\n\t\tif (nextSibling && nextSibling.parentNode) parent.insertBefore(dom, nextSibling)\n\t\telse parent.appendChild(dom)\n\t}\n\tfunction setContentEditable(vnode) {\n\t\tvar children = vnode.children\n\t\tif (children != null && children.length === 1 && children[0].tag === \"<\") {\n\t\t\tvar content = children[0].children\n\t\t\tif (vnode.dom.innerHTML !== content) vnode.dom.innerHTML = content\n\t\t}\n\t\telse if (vnode.text != null || children != null && children.length !== 0) throw new Error(\"Child node of a contenteditable must be trusted\")\n\t}\n\t//remove\n\tfunction removeNodes(vnodes, start, end, context) {\n\t\tfor (var i = start; i < end; i++) {\n\t\t\tvar vnode = vnodes[i]\n\t\t\tif (vnode != null) {\n\t\t\t\tif (vnode.skip) vnode.skip = false\n\t\t\t\telse removeNode(vnode, context)\n\t\t\t}\n\t\t}\n\t}\n\tfunction removeNode(vnode, context) {\n\t\tvar expected = 1, called = 0\n\t\tif (vnode.attrs && typeof vnode.attrs.onbeforeremove === \"function\") {\n\t\t\tvar result = vnode.attrs.onbeforeremove.call(vnode.state, vnode)\n\t\t\tif (result != null && typeof result.then === \"function\") {\n\t\t\t\texpected++\n\t\t\t\tresult.then(continuation, continuation)\n\t\t\t}\n\t\t}\n\t\tif (typeof vnode.tag !== \"string\" && typeof vnode._state.onbeforeremove === \"function\") {\n\t\t\tvar result = vnode._state.onbeforeremove.call(vnode.state, vnode)\n\t\t\tif (result != null && typeof result.then === \"function\") {\n\t\t\t\texpected++\n\t\t\t\tresult.then(continuation, continuation)\n\t\t\t}\n\t\t}\n\t\tcontinuation()\n\t\tfunction continuation() {\n\t\t\tif (++called === expected) {\n\t\t\t\tonremove(vnode)\n\t\t\t\tif (vnode.dom) {\n\t\t\t\t\tvar count0 = vnode.domSize || 1\n\t\t\t\t\tif (count0 > 1) {\n\t\t\t\t\t\tvar dom = vnode.dom\n\t\t\t\t\t\twhile (--count0) {\n\t\t\t\t\t\t\tremoveNodeFromDOM(dom.nextSibling)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tremoveNodeFromDOM(vnode.dom)\n\t\t\t\t\tif (context != null && vnode.domSize == null && !hasIntegrationMethods(vnode.attrs) && typeof vnode.tag === \"string\") { //TODO test custom elements\n\t\t\t\t\t\tif (!context.pool) context.pool = [vnode]\n\t\t\t\t\t\telse context.pool.push(vnode)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfunction removeNodeFromDOM(node) {\n\t\tvar parent = node.parentNode\n\t\tif (parent != null) parent.removeChild(node)\n\t}\n\tfunction onremove(vnode) {\n\t\tif (vnode.attrs && typeof vnode.attrs.onremove === \"function\") vnode.attrs.onremove.call(vnode.state, vnode)\n\t\tif (typeof vnode.tag !== \"string\") {\n\t\t\tif (typeof vnode._state.onremove === \"function\") vnode._state.onremove.call(vnode.state, vnode)\n\t\t\tif (vnode.instance != null) onremove(vnode.instance)\n\t\t} else {\n\t\t\tvar children = vnode.children\n\t\t\tif (Array.isArray(children)) {\n\t\t\t\tfor (var i = 0; i < children.length; i++) {\n\t\t\t\t\tvar child = children[i]\n\t\t\t\t\tif (child != null) onremove(child)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//attrs2\n\tfunction setAttrs(vnode, attrs2, ns) {\n\t\tfor (var key2 in attrs2) {\n\t\t\tsetAttr(vnode, key2, null, attrs2[key2], ns)\n\t\t}\n\t}\n\tfunction setAttr(vnode, key2, old, value, ns) {\n\t\tvar element = vnode.dom\n\t\tif (key2 === \"key\" || key2 === \"is\" || (old === value && !isFormAttribute(vnode, key2)) && typeof value !== \"object\" || typeof value === \"undefined\" || isLifecycleMethod(key2)) return\n\t\tvar nsLastIndex = key2.indexOf(\":\")\n\t\tif (nsLastIndex > -1 && key2.substr(0, nsLastIndex) === \"xlink\") {\n\t\t\telement.setAttributeNS(\"http://www.w3.org/1999/xlink\", key2.slice(nsLastIndex + 1), value)\n\t\t}\n\t\telse if (key2[0] === \"o\" && key2[1] === \"n\" && typeof value === \"function\") updateEvent(vnode, key2, value)\n\t\telse if (key2 === \"style\") updateStyle(element, old, value)\n\t\telse if (key2 in element && !isAttribute(key2) && ns === undefined && !isCustomElement(vnode)) {\n\t\t\tif (key2 === \"value\") {\n\t\t\t\tvar normalized0 = \"\" + value // eslint-disable-line no-implicit-coercion\n\t\t\t\t//setting input[value] to same value by typing on focused element moves cursor to end in Chrome\n\t\t\t\tif ((vnode.tag === \"input\" || vnode.tag === \"textarea\") && vnode.dom.value === normalized0 && vnode.dom === $doc.activeElement) return\n\t\t\t\t//setting select[value] to same value while having select open blinks select dropdown in Chrome\n\t\t\t\tif (vnode.tag === \"select\") {\n\t\t\t\t\tif (value === null) {\n\t\t\t\t\t\tif (vnode.dom.selectedIndex === -1 && vnode.dom === $doc.activeElement) return\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (old !== null && vnode.dom.value === normalized0 && vnode.dom === $doc.activeElement) return\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//setting option[value] to same value while having select open blinks select dropdown in Chrome\n\t\t\t\tif (vnode.tag === \"option\" && old != null && vnode.dom.value === normalized0) return\n\t\t\t}\n\t\t\t// If you assign an input type1 that is not supported by IE 11 with an assignment expression, an error0 will occur.\n\t\t\tif (vnode.tag === \"input\" && key2 === \"type\") {\n\t\t\t\telement.setAttribute(key2, value)\n\t\t\t\treturn\n\t\t\t}\n\t\t\telement[key2] = value\n\t\t}\n\t\telse {\n\t\t\tif (typeof value === \"boolean\") {\n\t\t\t\tif (value) element.setAttribute(key2, \"\")\n\t\t\t\telse element.removeAttribute(key2)\n\t\t\t}\n\t\t\telse element.setAttribute(key2 === \"className\" ? \"class\" : key2, value)\n\t\t}\n\t}\n\tfunction setLateAttrs(vnode) {\n\t\tvar attrs2 = vnode.attrs\n\t\tif (vnode.tag === \"select\" && attrs2 != null) {\n\t\t\tif (\"value\" in attrs2) setAttr(vnode, \"value\", null, attrs2.value, undefined)\n\t\t\tif (\"selectedIndex\" in attrs2) setAttr(vnode, \"selectedIndex\", null, attrs2.selectedIndex, undefined)\n\t\t}\n\t}\n\tfunction updateAttrs(vnode, old, attrs2, ns) {\n\t\tif (attrs2 != null) {\n\t\t\tfor (var key2 in attrs2) {\n\t\t\t\tsetAttr(vnode, key2, old && old[key2], attrs2[key2], ns)\n\t\t\t}\n\t\t}\n\t\tif (old != null) {\n\t\t\tfor (var key2 in old) {\n\t\t\t\tif (attrs2 == null || !(key2 in attrs2)) {\n\t\t\t\t\tif (key2 === \"className\") key2 = \"class\"\n\t\t\t\t\tif (key2[0] === \"o\" && key2[1] === \"n\" && !isLifecycleMethod(key2)) updateEvent(vnode, key2, undefined)\n\t\t\t\t\telse if (key2 !== \"key\") vnode.dom.removeAttribute(key2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfunction isFormAttribute(vnode, attr) {\n\t\treturn attr === \"value\" || attr === \"checked\" || attr === \"selectedIndex\" || attr === \"selected\" && vnode.dom === $doc.activeElement\n\t}\n\tfunction isLifecycleMethod(attr) {\n\t\treturn attr === \"oninit\" || attr === \"oncreate\" || attr === \"onupdate\" || attr === \"onremove\" || attr === \"onbeforeremove\" || attr === \"onbeforeupdate\"\n\t}\n\tfunction isAttribute(attr) {\n\t\treturn attr === \"href\" || attr === \"list\" || attr === \"form\" || attr === \"width\" || attr === \"height\"// || attr === \"type\"\n\t}\n\tfunction isCustomElement(vnode){\n\t\treturn vnode.attrs.is || vnode.tag.indexOf(\"-\") > -1\n\t}\n\tfunction hasIntegrationMethods(source) {\n\t\treturn source != null && (source.oncreate || source.onupdate || source.onbeforeremove || source.onremove)\n\t}\n\t//style\n\tfunction updateStyle(element, old, style) {\n\t\tif (old === style) element.style.cssText = \"\", old = null\n\t\tif (style == null) element.style.cssText = \"\"\n\t\telse if (typeof style === \"string\") element.style.cssText = style\n\t\telse {\n\t\t\tif (typeof old === \"string\") element.style.cssText = \"\"\n\t\t\tfor (var key2 in style) {\n\t\t\t\telement.style[key2] = style[key2]\n\t\t\t}\n\t\t\tif (old != null && typeof old !== \"string\") {\n\t\t\t\tfor (var key2 in old) {\n\t\t\t\t\tif (!(key2 in style)) element.style[key2] = \"\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//event\n\tfunction updateEvent(vnode, key2, value) {\n\t\tvar element = vnode.dom\n\t\tvar callback = typeof onevent !== \"function\" ? value : function(e) {\n\t\t\tvar result = value.call(element, e)\n\t\t\tonevent.call(element, e)\n\t\t\treturn result\n\t\t}\n\t\tif (key2 in element) element[key2] = typeof value === \"function\" ? callback : null\n\t\telse {\n\t\t\tvar eventName = key2.slice(2)\n\t\t\tif (vnode.events === undefined) vnode.events = {}\n\t\t\tif (vnode.events[key2] === callback) return\n\t\t\tif (vnode.events[key2] != null) element.removeEventListener(eventName, vnode.events[key2], false)\n\t\t\tif (typeof value === \"function\") {\n\t\t\t\tvnode.events[key2] = callback\n\t\t\t\telement.addEventListener(eventName, vnode.events[key2], false)\n\t\t\t}\n\t\t}\n\t}\n\t//lifecycle\n\tfunction initLifecycle(source, vnode, hooks) {\n\t\tif (typeof source.oninit === \"function\") source.oninit.call(vnode.state, vnode)\n\t\tif (typeof source.oncreate === \"function\") hooks.push(source.oncreate.bind(vnode.state, vnode))\n\t}\n\tfunction updateLifecycle(source, vnode, hooks) {\n\t\tif (typeof source.onupdate === \"function\") hooks.push(source.onupdate.bind(vnode.state, vnode))\n\t}\n\tfunction shouldNotUpdate(vnode, old) {\n\t\tvar forceVnodeUpdate, forceComponentUpdate\n\t\tif (vnode.attrs != null && typeof vnode.attrs.onbeforeupdate === \"function\") forceVnodeUpdate = vnode.attrs.onbeforeupdate.call(vnode.state, vnode, old)\n\t\tif (typeof vnode.tag !== \"string\" && typeof vnode._state.onbeforeupdate === \"function\") forceComponentUpdate = vnode._state.onbeforeupdate.call(vnode.state, vnode, old)\n\t\tif (!(forceVnodeUpdate === undefined && forceComponentUpdate === undefined) && !forceVnodeUpdate && !forceComponentUpdate) {\n\t\t\tvnode.dom = old.dom\n\t\t\tvnode.domSize = old.domSize\n\t\t\tvnode.instance = old.instance\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\tfunction render(dom, vnodes) {\n\t\tif (!dom) throw new Error(\"Ensure the DOM element being passed to m.route/m.mount/m.render is not undefined.\")\n\t\tvar hooks = []\n\t\tvar active = $doc.activeElement\n\t\tvar namespace = dom.namespaceURI\n\t\t// First time0 rendering into a node clears it out\n\t\tif (dom.vnodes == null) dom.textContent = \"\"\n\t\tif (!Array.isArray(vnodes)) vnodes = [vnodes]\n\t\tupdateNodes(dom, dom.vnodes, Vnode.normalizeChildren(vnodes), false, hooks, null, namespace === \"http://www.w3.org/1999/xhtml\" ? undefined : namespace)\n\t\tdom.vnodes = vnodes\n\t\t// document.activeElement can return null in IE https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement\n\t\tif (active != null && $doc.activeElement !== active) active.focus()\n\t\tfor (var i = 0; i < hooks.length; i++) hooks[i]()\n\t}\n\treturn {render: render, setEventCallback: setEventCallback}\n}\nfunction throttle(callback) {\n\t//60fps translates to 16.6ms, round it down since setTimeout requires int\n\tvar time = 16\n\tvar last = 0, pending = null\n\tvar timeout = typeof requestAnimationFrame === \"function\" ? requestAnimationFrame : setTimeout\n\treturn function() {\n\t\tvar now = Date.now()\n\t\tif (last === 0 || now - last >= time) {\n\t\t\tlast = now\n\t\t\tcallback()\n\t\t}\n\t\telse if (pending === null) {\n\t\t\tpending = timeout(function() {\n\t\t\t\tpending = null\n\t\t\t\tcallback()\n\t\t\t\tlast = Date.now()\n\t\t\t}, time - (now - last))\n\t\t}\n\t}\n}\nvar _11 = function($window) {\n\tvar renderService = coreRenderer($window)\n\trenderService.setEventCallback(function(e) {\n\t\tif (e.redraw === false) e.redraw = undefined\n\t\telse redraw()\n\t})\n\tvar callbacks = []\n\tfunction subscribe(key1, callback) {\n\t\tunsubscribe(key1)\n\t\tcallbacks.push(key1, throttle(callback))\n\t}\n\tfunction unsubscribe(key1) {\n\t\tvar index = callbacks.indexOf(key1)\n\t\tif (index > -1) callbacks.splice(index, 2)\n\t}\n\tfunction redraw() {\n\t\tfor (var i = 1; i < callbacks.length; i += 2) {\n\t\t\tcallbacks[i]()\n\t\t}\n\t}\n\treturn {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render}\n}\nvar redrawService = _11(window)\nrequestService.setCompletionCallback(redrawService.redraw)\nvar _16 = function(redrawService0) {\n\treturn function(root, component) {\n\t\tif (component === null) {\n\t\t\tredrawService0.render(root, [])\n\t\t\tredrawService0.unsubscribe(root)\n\t\t\treturn\n\t\t}\n\t\t\n\t\tif (component.view == null && typeof component !== \"function\") throw new Error(\"m.mount(element, component) expects a component, not a vnode\")\n\t\t\n\t\tvar run0 = function() {\n\t\t\tredrawService0.render(root, Vnode(component))\n\t\t}\n\t\tredrawService0.subscribe(root, run0)\n\t\tredrawService0.redraw()\n\t}\n}\nm.mount = _16(redrawService)\nvar Promise = PromisePolyfill\nvar parseQueryString = function(string) {\n\tif (string === \"\" || string == null) return {}\n\tif (string.charAt(0) === \"?\") string = string.slice(1)\n\tvar entries = string.split(\"&\"), data0 = {}, counters = {}\n\tfor (var i = 0; i < entries.length; i++) {\n\t\tvar entry = entries[i].split(\"=\")\n\t\tvar key5 = decodeURIComponent(entry[0])\n\t\tvar value = entry.length === 2 ? decodeURIComponent(entry[1]) : \"\"\n\t\tif (value === \"true\") value = true\n\t\telse if (value === \"false\") value = false\n\t\tvar levels = key5.split(/\\]\\[?|\\[/)\n\t\tvar cursor = data0\n\t\tif (key5.indexOf(\"[\") > -1) levels.pop()\n\t\tfor (var j = 0; j < levels.length; j++) {\n\t\t\tvar level = levels[j], nextLevel = levels[j + 1]\n\t\t\tvar isNumber = nextLevel == \"\" || !isNaN(parseInt(nextLevel, 10))\n\t\t\tvar isValue = j === levels.length - 1\n\t\t\tif (level === \"\") {\n\t\t\t\tvar key5 = levels.slice(0, j).join()\n\t\t\t\tif (counters[key5] == null) counters[key5] = 0\n\t\t\t\tlevel = counters[key5]++\n\t\t\t}\n\t\t\tif (cursor[level] == null) {\n\t\t\t\tcursor[level] = isValue ? value : isNumber ? [] : {}\n\t\t\t}\n\t\t\tcursor = cursor[level]\n\t\t}\n\t}\n\treturn data0\n}\nvar coreRouter = function($window) {\n\tvar supportsPushState = typeof $window.history.pushState === \"function\"\n\tvar callAsync0 = typeof setImmediate === \"function\" ? setImmediate : setTimeout\n\tfunction normalize1(fragment0) {\n\t\tvar data = $window.location[fragment0].replace(/(?:%[a-f89][a-f0-9])+/gim, decodeURIComponent)\n\t\tif (fragment0 === \"pathname\" && data[0] !== \"/\") data = \"/\" + data\n\t\treturn data\n\t}\n\tvar asyncId\n\tfunction debounceAsync(callback0) {\n\t\treturn function() {\n\t\t\tif (asyncId != null) return\n\t\t\tasyncId = callAsync0(function() {\n\t\t\t\tasyncId = null\n\t\t\t\tcallback0()\n\t\t\t})\n\t\t}\n\t}\n\tfunction parsePath(path, queryData, hashData) {\n\t\tvar queryIndex = path.indexOf(\"?\")\n\t\tvar hashIndex = path.indexOf(\"#\")\n\t\tvar pathEnd = queryIndex > -1 ? queryIndex : hashIndex > -1 ? hashIndex : path.length\n\t\tif (queryIndex > -1) {\n\t\t\tvar queryEnd = hashIndex > -1 ? hashIndex : path.length\n\t\t\tvar queryParams = parseQueryString(path.slice(queryIndex + 1, queryEnd))\n\t\t\tfor (var key4 in queryParams) queryData[key4] = queryParams[key4]\n\t\t}\n\t\tif (hashIndex > -1) {\n\t\t\tvar hashParams = parseQueryString(path.slice(hashIndex + 1))\n\t\t\tfor (var key4 in hashParams) hashData[key4] = hashParams[key4]\n\t\t}\n\t\treturn path.slice(0, pathEnd)\n\t}\n\tvar router = {prefix: \"#!\"}\n\trouter.getPath = function() {\n\t\tvar type2 = router.prefix.charAt(0)\n\t\tswitch (type2) {\n\t\t\tcase \"#\": return normalize1(\"hash\").slice(router.prefix.length)\n\t\t\tcase \"?\": return normalize1(\"search\").slice(router.prefix.length) + normalize1(\"hash\")\n\t\t\tdefault: return normalize1(\"pathname\").slice(router.prefix.length) + normalize1(\"search\") + normalize1(\"hash\")\n\t\t}\n\t}\n\trouter.setPath = function(path, data, options) {\n\t\tvar queryData = {}, hashData = {}\n\t\tpath = parsePath(path, queryData, hashData)\n\t\tif (data != null) {\n\t\t\tfor (var key4 in data) queryData[key4] = data[key4]\n\t\t\tpath = path.replace(/:([^\\/]+)/g, function(match2, token) {\n\t\t\t\tdelete queryData[token]\n\t\t\t\treturn data[token]\n\t\t\t})\n\t\t}\n\t\tvar query = buildQueryString(queryData)\n\t\tif (query) path += \"?\" + query\n\t\tvar hash = buildQueryString(hashData)\n\t\tif (hash) path += \"#\" + hash\n\t\tif (supportsPushState) {\n\t\t\tvar state = options ? options.state : null\n\t\t\tvar title = options ? options.title : null\n\t\t\t$window.onpopstate()\n\t\t\tif (options && options.replace) $window.history.replaceState(state, title, router.prefix + path)\n\t\t\telse $window.history.pushState(state, title, router.prefix + path)\n\t\t}\n\t\telse $window.location.href = router.prefix + path\n\t}\n\trouter.defineRoutes = function(routes, resolve, reject) {\n\t\tfunction resolveRoute() {\n\t\t\tvar path = router.getPath()\n\t\t\tvar params = {}\n\t\t\tvar pathname = parsePath(path, params, params)\n\t\t\tvar state = $window.history.state\n\t\t\tif (state != null) {\n\t\t\t\tfor (var k in state) params[k] = state[k]\n\t\t\t}\n\t\t\tfor (var route0 in routes) {\n\t\t\t\tvar matcher = new RegExp(\"^\" + route0.replace(/:[^\\/]+?\\.{3}/g, \"(.*?)\").replace(/:[^\\/]+/g, \"([^\\\\/]+)\") + \"\\/?$\")\n\t\t\t\tif (matcher.test(pathname)) {\n\t\t\t\t\tpathname.replace(matcher, function() {\n\t\t\t\t\t\tvar keys = route0.match(/:[^\\/]+/g) || []\n\t\t\t\t\t\tvar values = [].slice.call(arguments, 1, -2)\n\t\t\t\t\t\tfor (var i = 0; i < keys.length; i++) {\n\t\t\t\t\t\t\tparams[keys[i].replace(/:|\\./g, \"\")] = decodeURIComponent(values[i])\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve(routes[route0], params, path, route0)\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\treject(path, params)\n\t\t}\n\t\tif (supportsPushState) $window.onpopstate = debounceAsync(resolveRoute)\n\t\telse if (router.prefix.charAt(0) === \"#\") $window.onhashchange = resolveRoute\n\t\tresolveRoute()\n\t}\n\treturn router\n}\nvar _20 = function($window, redrawService0) {\n\tvar routeService = coreRouter($window)\n\tvar identity = function(v) {return v}\n\tvar render1, component, attrs3, currentPath, lastUpdate\n\tvar route = function(root, defaultRoute, routes) {\n\t\tif (root == null) throw new Error(\"Ensure the DOM element that was passed to `m.route` is not undefined\")\n\t\tvar run1 = function() {\n\t\t\tif (render1 != null) redrawService0.render(root, render1(Vnode(component, attrs3.key, attrs3)))\n\t\t}\n\t\tvar bail = function(path) {\n\t\t\tif (path !== defaultRoute) routeService.setPath(defaultRoute, null, {replace: true})\n\t\t\telse throw new Error(\"Could not resolve default route \" + defaultRoute)\n\t\t}\n\t\trouteService.defineRoutes(routes, function(payload, params, path) {\n\t\t\tvar update = lastUpdate = function(routeResolver, comp) {\n\t\t\t\tif (update !== lastUpdate) return\n\t\t\t\tcomponent = comp != null && (typeof comp.view === \"function\" || typeof comp === \"function\")? comp : \"div\"\n\t\t\t\tattrs3 = params, currentPath = path, lastUpdate = null\n\t\t\t\trender1 = (routeResolver.render || identity).bind(routeResolver)\n\t\t\t\trun1()\n\t\t\t}\n\t\t\tif (payload.view || typeof payload === \"function\") update({}, payload)\n\t\t\telse {\n\t\t\t\tif (payload.onmatch) {\n\t\t\t\t\tPromise.resolve(payload.onmatch(params, path)).then(function(resolved) {\n\t\t\t\t\t\tupdate(payload, resolved)\n\t\t\t\t\t}, bail)\n\t\t\t\t}\n\t\t\t\telse update(payload, \"div\")\n\t\t\t}\n\t\t}, bail)\n\t\tredrawService0.subscribe(root, run1)\n\t}\n\troute.set = function(path, data, options) {\n\t\tif (lastUpdate != null) {\n\t\t\toptions = options || {}\n\t\t\toptions.replace = true\n\t\t}\n\t\tlastUpdate = null\n\t\trouteService.setPath(path, data, options)\n\t}\n\troute.get = function() {return currentPath}\n\troute.prefix = function(prefix0) {routeService.prefix = prefix0}\n\troute.link = function(vnode1) {\n\t\tvnode1.dom.setAttribute(\"href\", routeService.prefix + vnode1.attrs.href)\n\t\tvnode1.dom.onclick = function(e) {\n\t\t\tif (e.ctrlKey || e.metaKey || e.shiftKey || e.which === 2) return\n\t\t\te.preventDefault()\n\t\t\te.redraw = false\n\t\t\tvar href = this.getAttribute(\"href\")\n\t\t\tif (href.indexOf(routeService.prefix) === 0) href = href.slice(routeService.prefix.length)\n\t\t\troute.set(href, undefined, undefined)\n\t\t}\n\t}\n\troute.param = function(key3) {\n\t\tif(typeof attrs3 !== \"undefined\" && typeof key3 !== \"undefined\") return attrs3[key3]\n\t\treturn attrs3\n\t}\n\treturn route\n}\nm.route = _20(window, redrawService)\nm.withAttr = function(attrName, callback1, context) {\n\treturn function(e) {\n\t\tcallback1.call(context || this, attrName in e.currentTarget ? e.currentTarget[attrName] : e.currentTarget.getAttribute(attrName))\n\t}\n}\nvar _28 = coreRenderer(window)\nm.render = _28.render\nm.redraw = redrawService.redraw\nm.request = requestService.request\nm.jsonp = requestService.jsonp\nm.parseQueryString = parseQueryString\nm.buildQueryString = buildQueryString\nm.version = \"1.1.6\"\nm.vnode = Vnode\nif (typeof module !== \"undefined\") module[\"exports\"] = m\nelse window.m = m\n}());\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {},require(\"timers\").setImmediate)\n},{\"timers\":9}],8:[function(require,module,exports){\n// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n},{}],9:[function(require,module,exports){\n(function (setImmediate,clearImmediate){\nvar nextTick = require('process/browser.js').nextTick;\nvar apply = Function.prototype.apply;\nvar slice = Array.prototype.slice;\nvar immediateIds = {};\nvar nextImmediateId = 0;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, window, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) { timeout.close(); };\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(window, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// That's not how node.js implements it but the exposed api is the same.\nexports.setImmediate = typeof setImmediate === \"function\" ? setImmediate : function(fn) {\n var id = nextImmediateId++;\n var args = arguments.length < 2 ? false : slice.call(arguments, 1);\n\n immediateIds[id] = true;\n\n nextTick(function onNextTick() {\n if (immediateIds[id]) {\n // fn.call() is faster so we optimize for the common use-case\n // @see http://jsperf.com/call-apply-segu\n if (args) {\n fn.apply(null, args);\n } else {\n fn.call(null);\n }\n // Prevent ids from leaking\n exports.clearImmediate(id);\n }\n });\n\n return id;\n};\n\nexports.clearImmediate = typeof clearImmediate === \"function\" ? clearImmediate : function(id) {\n delete immediateIds[id];\n};\n}).call(this,require(\"timers\").setImmediate,require(\"timers\").clearImmediate)\n},{\"process/browser.js\":8,\"timers\":9}],10:[function(require,module,exports){\nfunction tlite(getTooltipOpts) {\n document.addEventListener('mouseover', function (e) {\n var el = e.target;\n var opts = getTooltipOpts(el);\n\n if (!opts) {\n el = el.parentElement;\n opts = el && getTooltipOpts(el);\n }\n\n opts && tlite.show(el, opts, true);\n });\n}\n\ntlite.show = function (el, opts, isAuto) {\n var fallbackAttrib = 'data-tlite';\n opts = opts || {};\n\n (el.tooltip || Tooltip(el, opts)).show();\n\n function Tooltip(el, opts) {\n var tooltipEl;\n var showTimer;\n var text;\n\n el.addEventListener('mousedown', autoHide);\n el.addEventListener('mouseleave', autoHide);\n\n function show() {\n text = el.title || el.getAttribute(fallbackAttrib) || text;\n el.title = '';\n el.setAttribute(fallbackAttrib, '');\n text && !showTimer && (showTimer = setTimeout(fadeIn, isAuto ? 150 : 1))\n }\n\n function autoHide() {\n tlite.hide(el, true);\n }\n\n function hide(isAutoHiding) {\n if (isAuto === isAutoHiding) {\n showTimer = clearTimeout(showTimer);\n var parent = tooltipEl && tooltipEl.parentNode;\n parent && parent.removeChild(tooltipEl);\n tooltipEl = undefined;\n }\n }\n\n function fadeIn() {\n if (!tooltipEl) {\n tooltipEl = createTooltip(el, text, opts);\n }\n }\n\n return el.tooltip = {\n show: show,\n hide: hide\n };\n }\n\n function createTooltip(el, text, opts) {\n var tooltipEl = document.createElement('span');\n var grav = opts.grav || el.getAttribute('data-tlite') || 'n';\n\n tooltipEl.innerHTML = text;\n\n el.appendChild(tooltipEl);\n\n var vertGrav = grav[0] || '';\n var horzGrav = grav[1] || '';\n\n function positionTooltip() {\n tooltipEl.className = 'tlite ' + 'tlite-' + vertGrav + horzGrav;\n\n var arrowSize = 10;\n var top = el.offsetTop;\n var left = el.offsetLeft;\n\n if (tooltipEl.offsetParent === el) {\n top = left = 0;\n }\n\n var width = el.offsetWidth;\n var height = el.offsetHeight;\n var tooltipHeight = tooltipEl.offsetHeight;\n var tooltipWidth = tooltipEl.offsetWidth;\n var centerEl = left + (width / 2);\n\n tooltipEl.style.top = (\n vertGrav === 's' ? (top - tooltipHeight - arrowSize) :\n vertGrav === 'n' ? (top + height + arrowSize) :\n (top + (height / 2) - (tooltipHeight / 2))\n ) + 'px';\n\n tooltipEl.style.left = (\n horzGrav === 'w' ? left :\n horzGrav === 'e' ? left + width - tooltipWidth :\n vertGrav === 'w' ? (left + width + arrowSize) :\n vertGrav === 'e' ? (left - tooltipWidth - arrowSize) :\n (centerEl - tooltipWidth / 2)\n ) + 'px';\n }\n\n positionTooltip();\n\n var rect = tooltipEl.getBoundingClientRect();\n\n if (vertGrav === 's' && rect.top < 0) {\n vertGrav = 'n';\n positionTooltip();\n } else if (vertGrav === 'n' && rect.bottom > window.innerHeight) {\n vertGrav = 's';\n positionTooltip();\n } else if (vertGrav === 'e' && rect.left < 0) {\n vertGrav = 'w';\n positionTooltip();\n } else if (vertGrav === 'w' && rect.right > window.innerWidth) {\n vertGrav = 'e';\n positionTooltip();\n }\n\n tooltipEl.className += ' tlite-visible';\n\n return tooltipEl;\n }\n};\n\ntlite.hide = function (el, isAuto) {\n el.tooltip && el.tooltip.hide(isAuto);\n};\n\nif (typeof module !== 'undefined' && module.exports) {\n module.exports = tlite;\n}\n\n},{}],11:[function(require,module,exports){\n/*!\n * EventEmitter v5.2.5 - git.io/ee\n * Unlicense - http://unlicense.org/\n * Oliver Caldwell - http://oli.me.uk/\n * @preserve\n */\n\n;(function (exports) {\n 'use strict';\n\n /**\n * Class for managing events.\n * Can be extended to provide event functionality in other classes.\n *\n * @class EventEmitter Manages event registering and emitting.\n */\n function EventEmitter() {}\n\n // Shortcuts to improve speed and size\n var proto = EventEmitter.prototype;\n var originalGlobalValue = exports.EventEmitter;\n\n /**\n * Finds the index of the listener for the event in its storage array.\n *\n * @param {Function[]} listeners Array of listeners to search through.\n * @param {Function} listener Method to look for.\n * @return {Number} Index of the specified listener, -1 if not found\n * @api private\n */\n function indexOfListener(listeners, listener) {\n var i = listeners.length;\n while (i--) {\n if (listeners[i].listener === listener) {\n return i;\n }\n }\n\n return -1;\n }\n\n /**\n * Alias a method while keeping the context correct, to allow for overwriting of target method.\n *\n * @param {String} name The name of the target method.\n * @return {Function} The aliased method\n * @api private\n */\n function alias(name) {\n return function aliasClosure() {\n return this[name].apply(this, arguments);\n };\n }\n\n /**\n * Returns the listener array for the specified event.\n * Will initialise the event object and listener arrays if required.\n * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.\n * Each property in the object response is an array of listener functions.\n *\n * @param {String|RegExp} evt Name of the event to return the listeners from.\n * @return {Function[]|Object} All listener functions for the event.\n */\n proto.getListeners = function getListeners(evt) {\n var events = this._getEvents();\n var response;\n var key;\n\n // Return a concatenated array of all matching events if\n // the selector is a regular expression.\n if (evt instanceof RegExp) {\n response = {};\n for (key in events) {\n if (events.hasOwnProperty(key) && evt.test(key)) {\n response[key] = events[key];\n }\n }\n }\n else {\n response = events[evt] || (events[evt] = []);\n }\n\n return response;\n };\n\n /**\n * Takes a list of listener objects and flattens it into a list of listener functions.\n *\n * @param {Object[]} listeners Raw listener objects.\n * @return {Function[]} Just the listener functions.\n */\n proto.flattenListeners = function flattenListeners(listeners) {\n var flatListeners = [];\n var i;\n\n for (i = 0; i < listeners.length; i += 1) {\n flatListeners.push(listeners[i].listener);\n }\n\n return flatListeners;\n };\n\n /**\n * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.\n *\n * @param {String|RegExp} evt Name of the event to return the listeners from.\n * @return {Object} All listener functions for an event in an object.\n */\n proto.getListenersAsObject = function getListenersAsObject(evt) {\n var listeners = this.getListeners(evt);\n var response;\n\n if (listeners instanceof Array) {\n response = {};\n response[evt] = listeners;\n }\n\n return response || listeners;\n };\n\n function isValidListener (listener) {\n if (typeof listener === 'function' || listener instanceof RegExp) {\n return true\n } else if (listener && typeof listener === 'object') {\n return isValidListener(listener.listener)\n } else {\n return false\n }\n }\n\n /**\n * Adds a listener function to the specified event.\n * The listener will not be added if it is a duplicate.\n * If the listener returns true then it will be removed after it is called.\n * If you pass a regular expression as the event name then the listener will be added to all events that match it.\n *\n * @param {String|RegExp} evt Name of the event to attach the listener to.\n * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.addListener = function addListener(evt, listener) {\n if (!isValidListener(listener)) {\n throw new TypeError('listener must be a function');\n }\n\n var listeners = this.getListenersAsObject(evt);\n var listenerIsWrapped = typeof listener === 'object';\n var key;\n\n for (key in listeners) {\n if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {\n listeners[key].push(listenerIsWrapped ? listener : {\n listener: listener,\n once: false\n });\n }\n }\n\n return this;\n };\n\n /**\n * Alias of addListener\n */\n proto.on = alias('addListener');\n\n /**\n * Semi-alias of addListener. It will add a listener that will be\n * automatically removed after its first execution.\n *\n * @param {String|RegExp} evt Name of the event to attach the listener to.\n * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.addOnceListener = function addOnceListener(evt, listener) {\n return this.addListener(evt, {\n listener: listener,\n once: true\n });\n };\n\n /**\n * Alias of addOnceListener.\n */\n proto.once = alias('addOnceListener');\n\n /**\n * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.\n * You need to tell it what event names should be matched by a regex.\n *\n * @param {String} evt Name of the event to create.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.defineEvent = function defineEvent(evt) {\n this.getListeners(evt);\n return this;\n };\n\n /**\n * Uses defineEvent to define multiple events.\n *\n * @param {String[]} evts An array of event names to define.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.defineEvents = function defineEvents(evts) {\n for (var i = 0; i < evts.length; i += 1) {\n this.defineEvent(evts[i]);\n }\n return this;\n };\n\n /**\n * Removes a listener function from the specified event.\n * When passed a regular expression as the event name, it will remove the listener from all events that match it.\n *\n * @param {String|RegExp} evt Name of the event to remove the listener from.\n * @param {Function} listener Method to remove from the event.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.removeListener = function removeListener(evt, listener) {\n var listeners = this.getListenersAsObject(evt);\n var index;\n var key;\n\n for (key in listeners) {\n if (listeners.hasOwnProperty(key)) {\n index = indexOfListener(listeners[key], listener);\n\n if (index !== -1) {\n listeners[key].splice(index, 1);\n }\n }\n }\n\n return this;\n };\n\n /**\n * Alias of removeListener\n */\n proto.off = alias('removeListener');\n\n /**\n * Adds listeners in bulk using the manipulateListeners method.\n * If you pass an object as the first argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.\n * You can also pass it a regular expression to add the array of listeners to all events that match it.\n * Yeah, this function does quite a bit. That's probably a bad thing.\n *\n * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.\n * @param {Function[]} [listeners] An optional array of listener functions to add.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.addListeners = function addListeners(evt, listeners) {\n // Pass through to manipulateListeners\n return this.manipulateListeners(false, evt, listeners);\n };\n\n /**\n * Removes listeners in bulk using the manipulateListeners method.\n * If you pass an object as the first argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.\n * You can also pass it an event name and an array of listeners to be removed.\n * You can also pass it a regular expression to remove the listeners from all events that match it.\n *\n * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.\n * @param {Function[]} [listeners] An optional array of listener functions to remove.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.removeListeners = function removeListeners(evt, listeners) {\n // Pass through to manipulateListeners\n return this.manipulateListeners(true, evt, listeners);\n };\n\n /**\n * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.\n * The first argument will determine if the listeners are removed (true) or added (false).\n * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.\n * You can also pass it an event name and an array of listeners to be added/removed.\n * You can also pass it a regular expression to manipulate the listeners of all events that match it.\n *\n * @param {Boolean} remove True if you want to remove listeners, false if you want to add.\n * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.\n * @param {Function[]} [listeners] An optional array of listener functions to add/remove.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {\n var i;\n var value;\n var single = remove ? this.removeListener : this.addListener;\n var multiple = remove ? this.removeListeners : this.addListeners;\n\n // If evt is an object then pass each of its properties to this method\n if (typeof evt === 'object' && !(evt instanceof RegExp)) {\n for (i in evt) {\n if (evt.hasOwnProperty(i) && (value = evt[i])) {\n // Pass the single listener straight through to the singular method\n if (typeof value === 'function') {\n single.call(this, i, value);\n }\n else {\n // Otherwise pass back to the multiple function\n multiple.call(this, i, value);\n }\n }\n }\n }\n else {\n // So evt must be a string\n // And listeners must be an array of listeners\n // Loop over it and pass each one to the multiple method\n i = listeners.length;\n while (i--) {\n single.call(this, evt, listeners[i]);\n }\n }\n\n return this;\n };\n\n /**\n * Removes all listeners from a specified event.\n * If you do not specify an event then all listeners will be removed.\n * That means every event will be emptied.\n * You can also pass a regex to remove all events that match it.\n *\n * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.removeEvent = function removeEvent(evt) {\n var type = typeof evt;\n var events = this._getEvents();\n var key;\n\n // Remove different things depending on the state of evt\n if (type === 'string') {\n // Remove all listeners for the specified event\n delete events[evt];\n }\n else if (evt instanceof RegExp) {\n // Remove all events matching the regex.\n for (key in events) {\n if (events.hasOwnProperty(key) && evt.test(key)) {\n delete events[key];\n }\n }\n }\n else {\n // Remove all listeners in all events\n delete this._events;\n }\n\n return this;\n };\n\n /**\n * Alias of removeEvent.\n *\n * Added to mirror the node API.\n */\n proto.removeAllListeners = alias('removeEvent');\n\n /**\n * Emits an event of your choice.\n * When emitted, every listener attached to that event will be executed.\n * If you pass the optional argument array then those arguments will be passed to every listener upon execution.\n * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.\n * So they will not arrive within the array on the other side, they will be separate.\n * You can also pass a regular expression to emit to all events that match it.\n *\n * @param {String|RegExp} evt Name of the event to emit and execute listeners for.\n * @param {Array} [args] Optional array of arguments to be passed to each listener.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.emitEvent = function emitEvent(evt, args) {\n var listenersMap = this.getListenersAsObject(evt);\n var listeners;\n var listener;\n var i;\n var key;\n var response;\n\n for (key in listenersMap) {\n if (listenersMap.hasOwnProperty(key)) {\n listeners = listenersMap[key].slice(0);\n\n for (i = 0; i < listeners.length; i++) {\n // If the listener returns true then it shall be removed from the event\n // The function is executed either with a basic call or an apply if there is an args array\n listener = listeners[i];\n\n if (listener.once === true) {\n this.removeListener(evt, listener.listener);\n }\n\n response = listener.listener.apply(this, args || []);\n\n if (response === this._getOnceReturnValue()) {\n this.removeListener(evt, listener.listener);\n }\n }\n }\n }\n\n return this;\n };\n\n /**\n * Alias of emitEvent\n */\n proto.trigger = alias('emitEvent');\n\n /**\n * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.\n * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.\n *\n * @param {String|RegExp} evt Name of the event to emit and execute listeners for.\n * @param {...*} Optional additional arguments to be passed to each listener.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.emit = function emit(evt) {\n var args = Array.prototype.slice.call(arguments, 1);\n return this.emitEvent(evt, args);\n };\n\n /**\n * Sets the current value to check against when executing listeners. If a\n * listeners return value matches the one set here then it will be removed\n * after execution. This value defaults to true.\n *\n * @param {*} value The new value to check for when executing listeners.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.setOnceReturnValue = function setOnceReturnValue(value) {\n this._onceReturnValue = value;\n return this;\n };\n\n /**\n * Fetches the current value to check against when executing listeners. If\n * the listeners return value matches this one then it should be removed\n * automatically. It will return true by default.\n *\n * @return {*|Boolean} The current value to check for or the default, true.\n * @api private\n */\n proto._getOnceReturnValue = function _getOnceReturnValue() {\n if (this.hasOwnProperty('_onceReturnValue')) {\n return this._onceReturnValue;\n }\n else {\n return true;\n }\n };\n\n /**\n * Fetches the events object and creates one if required.\n *\n * @return {Object} The events storage object.\n * @api private\n */\n proto._getEvents = function _getEvents() {\n return this._events || (this._events = {});\n };\n\n /**\n * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.\n *\n * @return {Function} Non conflicting EventEmitter class.\n */\n EventEmitter.noConflict = function noConflict() {\n exports.EventEmitter = originalGlobalValue;\n return EventEmitter;\n };\n\n // Expose the class either via AMD, CommonJS or the global object\n if (typeof define === 'function' && define.amd) {\n define(function () {\n return EventEmitter;\n });\n }\n else if (typeof module === 'object' && module.exports){\n module.exports = EventEmitter;\n }\n else {\n exports.EventEmitter = EventEmitter;\n }\n}(typeof window !== 'undefined' ? window : this || {}));\n\n},{}]},{},[1]);\n })();"]} \ No newline at end of file +{"version":3,"sources":["admin.js"],"names":["define","undefined","r","e","n","t","o","i","f","c","u","a","Error","code","p","exports","call","length","1","require","module","obj","_tlite","__esModule","default","m","window","EventEmitter","context","document","getElementById","events","tabs","helpers","settings","el","className","indexOf","ListFetcher","mount","nl4wp","deps","mithril","./admin/fields/newsletter-api-key.js","./admin/helpers.js","./admin/list-fetcher.js","./admin/settings.js","./admin/tabs.js","tlite","wolfy87-eventemitter","2","field","validate","evt","node","createElement","innerText","nl4wp_vars","i18n","invalid_api_key","nextElementSibling","parentElement","removeChild","value","match","insertBefore","addEventListener","3","showIfElements","toggleElement","selector","elements","querySelectorAll","show","clientHeight","style","display","bindEventToElement","element","event","handler","attachEvent","bindEventToElements","Array","prototype","forEach","debounce","func","wait","immediate","timeout","this","args","arguments","callNow","clearTimeout","setTimeout","apply","config","JSON","parse","getAttribute","parentElements","inputs","hide","checked","conditionMet","visibility","opacity","inputElement","removeAttribute","setAttribute","4","$","jQuery","working","done","newsletter","api_connected","lists","fetch","preventDefault","post","ajaxurl","action","data","success","location","reload","bind","fail","always","redraw","view","method","onsubmit","type","fetching_newsletter_lists","renew_newsletter_lists","disabled","trust","fetching_newsletter_lists_can_take_a_while","fetching_newsletter_lists_done","fetching_newsletter_lists_error","5","_typeof","Symbol","iterator","constructor","querySelector","listInputs","selectedLists","updateSelectedLists","input","push","trigger","on","rows","searchKey","searchValue","listId","filter","replace","getSelectedLists","6","URL","$context","$tabs","find","$tabNavs","refererField","get","id","_open","tab","updateState","removeClass","css","nav","blur","url","setParameter","href","history","pushState","title","tb_remove","forms","editor","refresh","split","switchTab","tabId","urlParams","returnValue","each","substring","first","text","open","click","body","activeTab","replaceState","state","init","./url.js","7","query","hasOwnProperty","b","decodeURIComponent","build","ret","d","encodeURIComponent","join","key","8","global","setImmediate","Vnode","tag","attrs0","children","dom","attrs","domSize","_state","instance","skip","normalize","isArray","normalizeChildren","selectorParser","selectorCache","hasOwn","isEmpty","object","hyperscript","start","cached","classes","exec","attrValue","compileSelector","normalized","childList","hasAttrs","class","newAttrs","execSelector","html","fragment","attrs1","PromisePolyfill","executor","TypeError","self","resolvers","rejectors","resolveCurrent","rejectCurrent","_instance","callAsync","list","shouldAbsorb","execute","then","console","error","retry","executeOnce","runs","run","fn","onerror","onFulfilled","onRejection","resolveNext","rejectNext","handle","callback","next","promise","resolve","reject","catch","all","total","count","values","consume","race","Promise","buildQueryString","Object","toString","key0","destructure","FILE_PROTOCOL_REGEX","RegExp","requestService","$window","oncompletion","callbackCount","finalizer","complete","finalize","promise0","then0","extra","interpolate","tokens","slice","assemble","querystring","prefix","deserialize","extract","xhr","responseText","cast","type0","request","toUpperCase","useBody","serialize","FormData","stringify","XMLHttpRequest","aborted","_abort","abort","async","user","password","headers","setRequestHeader","withCredentials","onreadystatechange","readyState","response","status","test","send","background","jsonp","callbackName","Math","round","random","script","parentNode","callbackKey","src","documentElement","appendChild","setCompletionCallback","_8","coreRenderer","onevent","$doc","$emptyFragment","createDocumentFragment","nameSpace","svg","math","getNameSpace","vnode","xmlns","createNodes","parent","vnodes","end","hooks","nextSibling","ns","createNode","initComponent","insertNode","createComponent","initLifecycle","createTextNode","createHTML","firstChild","childNodes","createFragment","attrs2","is","createElementNS","key2","setAttr","setAttrs","contenteditable","setContentEditable","textContent","selectedIndex","parent1","caption","thead","tbody","tfoot","tr","th","td","colgroup","col","temp","innerHTML","child","sentinel","create","$$reentrantLock$$","updateNodes","old","recycling","removeNodes","isUnkeyed","getNextSibling","updateNode","pool","abs","oldChildrenLength","poolChildrenLength","vnodesChildrenLength","isRecyclable","concat","map","oldStart","oldEnd","v","shouldRecycle","toFragment","getKeyMap","oldIndex","movable","oldTag","forceVnodeUpdate","forceComponentUpdate","onbeforeupdate","shouldNotUpdate","updateLifecycle","nodeValue","updateText","updateFragment","isLifecycleMethod","updateEvent","updateAttrs","updateElement","removeNode","updateComponent","count0","content","result","expected","called","onbeforeremove","continuation","onremove","removeNodeFromDOM","source","oncreate","onupdate","attr","activeElement","nsLastIndex","substr","setAttributeNS","cssText","updateStyle","normalized0","eventName","removeEventListener","oninit","render","active","namespace","namespaceURI","focus","setEventCallback","redrawService","renderService","callbacks","unsubscribe","key1","index","splice","subscribe","last","pending","requestAnimationFrame","now","Date","_11","redrawService0","root","component","render1","attrs3","currentPath","lastUpdate","routeService","route","parseQueryString","string","charAt","entries","data0","counters","entry","key5","levels","cursor","pop","j","level","nextLevel","isNumber","isNaN","parseInt","isValue","coreRouter","asyncId","supportsPushState","callAsync0","normalize1","fragment0","parsePath","path","queryData","hashData","queryIndex","hashIndex","pathEnd","queryEnd","queryParams","key4","hashParams","router","getPath","setPath","options","match2","token","hash","onpopstate","defineRoutes","routes","resolveRoute","params","pathname","k","route0","matcher","keys","callback0","onhashchange","defaultRoute","run1","bail","payload","update","routeResolver","comp","onmatch","resolved","set","prefix0","link","vnode1","onclick","ctrlKey","metaKey","shiftKey","which","param","key3","withAttr","attrName","callback1","currentTarget","_28","version","timers","9","cachedSetTimeout","cachedClearTimeout","process","defaultSetTimout","defaultClearTimeout","runTimeout","fun","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","len","marker","runClearTimeout","Item","array","noop","nextTick","browser","env","argv","versions","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","name","binding","cwd","chdir","dir","umask","10","clearImmediate","Function","immediateIds","nextImmediateId","Timeout","clearFn","_id","_clearFn","setInterval","clearInterval","close","unref","ref","enroll","item","msecs","_idleTimeoutId","_idleTimeout","unenroll","_unrefActive","_onTimeout","process/browser.js","11","getTooltipOpts","target","opts","isAuto","fallbackAttrib","tooltip","tooltipEl","showTimer","autoHide","fadeIn","grav","vertGrav","horzGrav","positionTooltip","top","offsetTop","left","offsetLeft","offsetParent","width","offsetWidth","height","offsetHeight","tooltipHeight","tooltipWidth","centerEl","rect","getBoundingClientRect","bottom","innerHeight","right","innerWidth","createTooltip","isAutoHiding","Tooltip","12","proto","originalGlobalValue","indexOfListener","listener","alias","getListeners","_getEvents","flattenListeners","flatListeners","getListenersAsObject","isValidListener","listenerIsWrapped","addOnceListener","defineEvent","defineEvents","evts","addListeners","manipulateListeners","removeListeners","remove","single","multiple","removeEvent","_events","emitEvent","listenersMap","_getOnceReturnValue","setOnceReturnValue","_onceReturnValue","noConflict","amd"],"mappings":"CAAA,WAAe,IAA6BA,OAASC,GAAuB,SAASC,EAAEC,EAAEC,EAAEC,GAAG,SAASC,EAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,IAAIE,GAAE,EAAoC,IAAID,GAAGC,EAAE,OAAOA,EAAEF,GAAE,GAAI,GAAGG,EAAE,OAAOA,EAAEH,GAAE,GAAI,IAAII,EAAE,IAAIC,MAAM,uBAAuBL,EAAE,KAAK,MAAMI,EAAEE,KAAK,mBAAmBF,EAAE,IAAIG,EAAEV,EAAEG,GAAG,CAACQ,QAAQ,IAAIZ,EAAEI,GAAG,GAAGS,KAAKF,EAAEC,QAAQ,SAASb,GAAoB,OAAOI,EAAlBH,EAAEI,GAAG,GAAGL,IAAeA,IAAIY,EAAEA,EAAEC,QAAQb,EAAEC,EAAEC,EAAEC,GAAG,OAAOD,EAAEG,GAAGQ,QAAQ,IAAI,IAAIL,GAAE,EAAoCH,EAAE,EAAEA,EAAEF,EAAEY,OAAOV,IAAID,EAAED,EAAEE,IAAI,OAAOD,EAA7b,CAA4c,CAACY,EAAE,CAAC,SAASC,EAAQC,EAAOL,GACxiB,aAEA,IAEgCM,EAF5BC,GAE4BD,EAFIF,EAAQ,WAESE,EAAIE,WAAaF,EAAM,CAAEG,QAASH,GAEvF,IAAII,EAAIC,OAAOD,EAAIN,EAAQ,WAE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,EAAGA,EAAImmB,EAAUzlB,OAAQV,KAKR,KAFtByqB,EAAWtE,EAAUnmB,IAER4lB,MACTxgB,KAAK0gB,eAAehjB,EAAK2nB,EAASA,UAG3BA,EAASA,SAAS/kB,MAAMN,KAAMC,GAAQ,MAEhCD,KAAK4mB,uBAClB5mB,KAAK0gB,eAAehjB,EAAK2nB,EAASA,UAMlD,OAAOrlB,MAMXklB,EAAMlhB,QAAUshB,EAAM,aAUtBJ,EAAMtE,KAAO,SAAcljB,GACvB,IAAIuC,EAAOT,MAAMC,UAAUsO,MAAM1S,KAAK6E,UAAW,GACjD,OAAOF,KAAK0mB,UAAUhpB,EAAKuC,IAW/BilB,EAAM2B,mBAAqB,SAA4BzoB,GAEnD,OADA4B,KAAK8mB,iBAAmB1oB,EACjB4B,MAWXklB,EAAM0B,oBAAsB,WACxB,OAAI5mB,KAAKsH,eAAe,qBACbtH,KAAK8mB,kBAapB5B,EAAMM,WAAa,WACf,OAAOxlB,KAAKymB,UAAYzmB,KAAKymB,QAAU,KAQ3CzqB,EAAa+qB,WAAa,WAEtB,OADA3rB,EAAQY,aAAempB,EAChBnpB,GAIW,mBAAX3B,GAAyBA,EAAO2sB,IACvC3sB,EAAO,WACH,OAAO2B,IAGY,iBAAXP,GAAuBA,EAAOL,QAC1CK,EAAOL,QAAUY,EAGjBZ,EAAQY,aAAeA,EA5d9B,CA8dmB,oBAAXD,OAAyBA,OAASiE,MAAQ,KAEjD,KAAK,GAAG,CAAC,IAjlFX","file":"admin.min.js","sourcesContent":["(function () { var require = undefined; var define = undefined; (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i -1;\n}); // list fetcher\n\nvar ListFetcher = require('./admin/list-fetcher.js');\n\nvar mount = document.getElementById('nl4wp-list-fetcher');\n\nif (mount) {\n m.mount(mount, new ListFetcher());\n}\n\nrequire('./admin/fields/newsletter-api-key.js'); // expose some things\n\n\nwindow.nl4wp = window.nl4wp || {};\nwindow.nl4wp.deps = window.nl4wp.deps || {};\nwindow.nl4wp.deps.mithril = m;\nwindow.nl4wp.helpers = helpers;\nwindow.nl4wp.events = events;\nwindow.nl4wp.settings = settings;\nwindow.nl4wp.tabs = tabs;\n\n},{\"./admin/fields/newsletter-api-key.js\":2,\"./admin/helpers.js\":3,\"./admin/list-fetcher.js\":4,\"./admin/settings.js\":5,\"./admin/tabs.js\":6,\"mithril\":8,\"tlite\":11,\"wolfy87-eventemitter\":12}],2:[function(require,module,exports){\n'use strict';\n\nvar field;\n\nfunction validate(evt) {\n var node = document.createElement('p');\n node.className = 'help red';\n node.innerText = window.nl4wp_vars.i18n.invalid_api_key;\n\n if (field.nextElementSibling.innerText === node.innerText) {\n field.nextElementSibling.parentElement.removeChild(field.nextElementSibling);\n }\n\n if (!field.value.match(/^[0-9a-z]+-[0-9a-z]+-[0-9a-z]+$/)) {\n field.parentElement.insertBefore(node, field.nextElementSibling);\n }\n}\n\n(function () {\n field = document.getElementById('newsletter_api_key');\n\n if (!field) {\n return;\n }\n\n field.addEventListener('change', validate);\n})();\n\n},{}],3:[function(require,module,exports){\n'use strict';\n\nvar helpers = {};\n\nhelpers.toggleElement = function (selector) {\n var elements = document.querySelectorAll(selector);\n\n for (var i = 0; i < elements.length; i++) {\n var show = elements[i].clientHeight <= 0;\n elements[i].style.display = show ? '' : 'none';\n }\n};\n\nhelpers.bindEventToElement = function (element, event, handler) {\n if (element.addEventListener) {\n element.addEventListener(event, handler);\n } else if (element.attachEvent) {\n element.attachEvent('on' + event, handler);\n }\n};\n\nhelpers.bindEventToElements = function (elements, event, handler) {\n Array.prototype.forEach.call(elements, function (element) {\n helpers.bindEventToElement(element, event, handler);\n });\n}; // polling\n\n\nhelpers.debounce = function (func, wait, immediate) {\n var timeout;\n return function () {\n var context = this,\n args = arguments;\n\n var later = function later() {\n timeout = null;\n if (!immediate) func.apply(context, args);\n };\n\n var callNow = immediate && !timeout;\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n if (callNow) func.apply(context, args);\n };\n};\n/**\n * Showif.js\n */\n\n\n(function () {\n var showIfElements = document.querySelectorAll('[data-showif]'); // dependent elements\n\n Array.prototype.forEach.call(showIfElements, function (element) {\n var config = JSON.parse(element.getAttribute('data-showif'));\n var parentElements = document.querySelectorAll('[name=\"' + config.element + '\"]');\n var inputs = element.querySelectorAll('input,select,textarea:not([readonly])');\n var hide = config.hide === undefined || config.hide;\n\n function toggleElement() {\n // do nothing with unchecked radio inputs\n if (this.getAttribute('type') === \"radio\" && !this.checked) {\n return;\n }\n\n var value = this.getAttribute(\"type\") === \"checkbox\" ? this.checked : this.value;\n var conditionMet = value == config.value;\n\n if (hide) {\n element.style.display = conditionMet ? '' : 'none';\n element.style.visibility = conditionMet ? '' : 'hidden';\n } else {\n element.style.opacity = conditionMet ? '' : '0.4';\n } // disable input fields to stop sending their values to server\n\n\n Array.prototype.forEach.call(inputs, function (inputElement) {\n conditionMet ? inputElement.removeAttribute('readonly') : inputElement.setAttribute('readonly', 'readonly');\n });\n } // find checked element and call toggleElement function\n\n\n Array.prototype.forEach.call(parentElements, function (parentElement) {\n toggleElement.call(parentElement);\n }); // bind on all changes\n\n helpers.bindEventToElements(parentElements, 'change', toggleElement);\n });\n})();\n\nmodule.exports = helpers;\n\n},{}],4:[function(require,module,exports){\n'use strict';\n\nvar $ = window.jQuery;\nvar config = nl4wp_vars;\nvar i18n = config.i18n;\n\nfunction ListFetcher() {\n this.working = false;\n this.done = false; // start fetching right away when no lists but api key given\n\n if (config.newsletter.api_connected && config.newsletter.lists.length === 0) {\n this.fetch();\n }\n}\n\nListFetcher.prototype.fetch = function (e) {\n e && e.preventDefault();\n this.working = true;\n this.done = false;\n $.post(ajaxurl, {\n action: \"nl4wp_renew_newsletter_lists\",\n timeout: 600000 // 10 minutes, matching max_execution_time\n\n }).done(function (data) {\n this.success = true;\n\n if (data) {\n window.setTimeout(function () {\n window.location.reload();\n }, 3000);\n }\n }.bind(this)).fail(function (data) {\n this.success = false;\n }.bind(this)).always(function (data) {\n this.working = false;\n this.done = true;\n m.redraw();\n }.bind(this));\n};\n\nListFetcher.prototype.view = function () {\n return m('form', {\n method: \"POST\",\n onsubmit: this.fetch.bind(this)\n }, [m('p', [m('input', {\n type: \"submit\",\n value: this.working ? i18n.fetching_newsletter_lists : i18n.renew_newsletter_lists,\n className: \"button\",\n disabled: !!this.working\n }), m.trust('   '), this.working ? [m('span.nl4wp-loader', \"Loading...\"), m.trust('   '), m('em.help', i18n.fetching_newsletter_lists_can_take_a_while)] : '', this.done ? [this.success ? m('em.help.green', i18n.fetching_newsletter_lists_done) : m('em.help.red', i18n.fetching_newsletter_lists_error)] : ''])]);\n};\n\nmodule.exports = ListFetcher;\n\n},{}],5:[function(require,module,exports){\n\"use strict\";\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar Settings = function Settings(context, helpers, events) {\n 'use strict'; // vars\n\n var form = context.querySelector('form');\n var listInputs = context.querySelectorAll('.nl4wp-list-input');\n var lists = nl4wp_vars.newsletter.lists;\n var selectedLists = []; // functions\n\n function getSelectedListsWhere(searchKey, searchValue) {\n return selectedLists.filter(function (el) {\n return el[searchKey] === searchValue;\n });\n }\n\n function getSelectedLists() {\n return selectedLists;\n }\n\n function updateSelectedLists() {\n selectedLists = [];\n Array.prototype.forEach.call(listInputs, function (input) {\n // skip unchecked checkboxes\n if (typeof input.checked === \"boolean\" && !input.checked) {\n return;\n }\n\n if (_typeof(lists[input.value]) === \"object\") {\n selectedLists.push(lists[input.value]);\n }\n });\n events.trigger('selectedLists.change', [selectedLists]);\n return selectedLists;\n }\n\n function toggleVisibleLists() {\n var rows = document.querySelectorAll('.lists--only-selected > *');\n Array.prototype.forEach.call(rows, function (el) {\n var listId = el.getAttribute('data-list-id');\n var isSelected = getSelectedListsWhere('id', listId).length > 0;\n\n if (isSelected) {\n el.setAttribute('class', el.getAttribute('class').replace('hidden', ''));\n } else {\n el.setAttribute('class', el.getAttribute('class') + \" hidden\");\n }\n });\n }\n\n events.on('selectedLists.change', toggleVisibleLists);\n helpers.bindEventToElements(listInputs, 'change', updateSelectedLists);\n updateSelectedLists();\n return {\n getSelectedLists: getSelectedLists\n };\n};\n\nmodule.exports = Settings;\n\n},{}],6:[function(require,module,exports){\n'use strict';\n\nvar URL = require('./url.js'); // Tabs\n\n\nvar Tabs = function Tabs(context) {\n // TODO: last piece of jQuery... can we get rid of it?\n var $ = window.jQuery;\n var $context = $(context);\n var $tabs = $context.find('.tab');\n var $tabNavs = $context.find('.nav-tab');\n var refererField = context.querySelector('input[name=\"_wp_http_referer\"]');\n var tabs = [];\n $.each($tabs, function (i, t) {\n var id = t.id.substring(4);\n var title = $(t).find('h2').first().text();\n tabs.push({\n id: id,\n title: title,\n element: t,\n nav: context.querySelectorAll('.nav-tab-' + id),\n open: function open() {\n return _open(id);\n }\n });\n });\n\n function get(id) {\n for (var i = 0; i < tabs.length; i++) {\n if (tabs[i].id === id) {\n return tabs[i];\n }\n }\n\n return undefined;\n }\n\n function _open(tab, updateState) {\n // make sure we have a tab object\n if (typeof tab === \"string\") {\n tab = get(tab);\n }\n\n if (!tab) {\n return false;\n } // should we update state?\n\n\n if (updateState == undefined) {\n updateState = true;\n } // hide all tabs & remove active class\n\n\n $tabs.removeClass('tab-active').css('display', 'none');\n $tabNavs.removeClass('nav-tab-active'); // add `nav-tab-active` to this tab\n\n Array.prototype.forEach.call(tab.nav, function (nav) {\n nav.className += \" nav-tab-active\";\n nav.blur();\n }); // show target tab\n\n tab.element.style.display = 'block';\n tab.element.className += \" tab-active\"; // create new URL\n\n var url = URL.setParameter(window.location.href, \"tab\", tab.id); // update hash\n\n if (history.pushState && updateState) {\n history.pushState(tab.id, '', url);\n } // update document title\n\n\n title(tab); // update referer field\n\n refererField.value = url; // if thickbox is open, close it.\n\n if (typeof tb_remove === \"function\") {\n tb_remove();\n } // refresh editor after switching tabs\n // TODO: decouple this! law of demeter etc.\n\n\n if (tab.id === 'fields' && window.nl4wp && window.nl4wp.forms && window.nl4wp.forms.editor) {\n nl4wp.forms.editor.refresh();\n }\n\n return true;\n }\n\n function title(tab) {\n var title = document.title.split('-');\n document.title = document.title.replace(title[0], tab.title + \" \");\n }\n\n function switchTab(e) {\n e = e || window.event; // get from data attribute\n\n var tabId = this.getAttribute('data-tab'); // get from classname\n\n if (!tabId) {\n var match = this.className.match(/nav-tab-(\\w+)?/);\n\n if (match) {\n tabId = match[1];\n }\n } // get from href\n\n\n if (!tabId) {\n var urlParams = URL.parse(this.href);\n\n if (!urlParams.tab) {\n return;\n }\n\n tabId = urlParams.tab;\n }\n\n var opened = _open(tabId);\n\n if (opened) {\n e.preventDefault();\n e.returnValue = false;\n return false;\n }\n\n return true;\n }\n\n function init() {\n // check for current tab\n if (!history.pushState) {\n return;\n }\n\n var activeTab = $tabs.filter(':visible').get(0);\n\n if (!activeTab) {\n return;\n }\n\n var tab = get(activeTab.id.substring(4));\n if (!tab) return; // check if tab is in html5 history\n\n if (history.replaceState && history.state === null) {\n history.replaceState(tab.id, '');\n } // update document title\n\n\n title(tab);\n }\n\n $tabNavs.click(switchTab);\n $(document.body).on('click', '.tab-link', switchTab);\n init();\n\n if (window.addEventListener && history.pushState) {\n window.addEventListener('popstate', function (e) {\n if (!e.state) return true;\n var tabId = e.state;\n return _open(tabId, false);\n });\n }\n\n return {\n open: _open,\n get: get\n };\n};\n\nmodule.exports = Tabs;\n\n},{\"./url.js\":7}],7:[function(require,module,exports){\n'use strict';\n\nvar URL = {\n parse: function parse(url) {\n var query = {};\n var a = url.split('&');\n\n for (var i in a) {\n if (!a.hasOwnProperty(i)) {\n continue;\n }\n\n var b = a[i].split('=');\n query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]);\n }\n\n return query;\n },\n build: function build(data) {\n var ret = [];\n\n for (var d in data) {\n ret.push(d + \"=\" + encodeURIComponent(data[d]));\n }\n\n return ret.join(\"&\");\n },\n setParameter: function setParameter(url, key, value) {\n var data = URL.parse(url);\n data[key] = value;\n return URL.build(data);\n }\n};\nmodule.exports = URL;\n\n},{}],8:[function(require,module,exports){\n(function (global,setImmediate){\n;(function() {\n\"use strict\"\nfunction Vnode(tag, key, attrs0, children, text, dom) {\n\treturn {tag: tag, key: key, attrs: attrs0, children: children, text: text, dom: dom, domSize: undefined, state: undefined, _state: undefined, events: undefined, instance: undefined, skip: false}\n}\nVnode.normalize = function(node) {\n\tif (Array.isArray(node)) return Vnode(\"[\", undefined, undefined, Vnode.normalizeChildren(node), undefined, undefined)\n\tif (node != null && typeof node !== \"object\") return Vnode(\"#\", undefined, undefined, node === false ? \"\" : node, undefined, undefined)\n\treturn node\n}\nVnode.normalizeChildren = function normalizeChildren(children) {\n\tfor (var i = 0; i < children.length; i++) {\n\t\tchildren[i] = Vnode.normalize(children[i])\n\t}\n\treturn children\n}\nvar selectorParser = /(?:(^|#|\\.)([^#\\.\\[\\]]+))|(\\[(.+?)(?:\\s*=\\s*(\"|'|)((?:\\\\[\"'\\]]|.)*?)\\5)?\\])/g\nvar selectorCache = {}\nvar hasOwn = {}.hasOwnProperty\nfunction isEmpty(object) {\n\tfor (var key in object) if (hasOwn.call(object, key)) return false\n\treturn true\n}\nfunction compileSelector(selector) {\n\tvar match, tag = \"div\", classes = [], attrs = {}\n\twhile (match = selectorParser.exec(selector)) {\n\t\tvar type = match[1], value = match[2]\n\t\tif (type === \"\" && value !== \"\") tag = value\n\t\telse if (type === \"#\") attrs.id = value\n\t\telse if (type === \".\") classes.push(value)\n\t\telse if (match[3][0] === \"[\") {\n\t\t\tvar attrValue = match[6]\n\t\t\tif (attrValue) attrValue = attrValue.replace(/\\\\([\"'])/g, \"$1\").replace(/\\\\\\\\/g, \"\\\\\")\n\t\t\tif (match[4] === \"class\") classes.push(attrValue)\n\t\t\telse attrs[match[4]] = attrValue === \"\" ? attrValue : attrValue || true\n\t\t}\n\t}\n\tif (classes.length > 0) attrs.className = classes.join(\" \")\n\treturn selectorCache[selector] = {tag: tag, attrs: attrs}\n}\nfunction execSelector(state, attrs, children) {\n\tvar hasAttrs = false, childList, text\n\tvar className = attrs.className || attrs.class\n\tif (!isEmpty(state.attrs) && !isEmpty(attrs)) {\n\t\tvar newAttrs = {}\n\t\tfor(var key in attrs) {\n\t\t\tif (hasOwn.call(attrs, key)) {\n\t\t\t\tnewAttrs[key] = attrs[key]\n\t\t\t}\n\t\t}\n\t\tattrs = newAttrs\n\t}\n\tfor (var key in state.attrs) {\n\t\tif (hasOwn.call(state.attrs, key)) {\n\t\t\tattrs[key] = state.attrs[key]\n\t\t}\n\t}\n\tif (className !== undefined) {\n\t\tif (attrs.class !== undefined) {\n\t\t\tattrs.class = undefined\n\t\t\tattrs.className = className\n\t\t}\n\t\tif (state.attrs.className != null) {\n\t\t\tattrs.className = state.attrs.className + \" \" + className\n\t\t}\n\t}\n\tfor (var key in attrs) {\n\t\tif (hasOwn.call(attrs, key) && key !== \"key\") {\n\t\t\thasAttrs = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif (Array.isArray(children) && children.length === 1 && children[0] != null && children[0].tag === \"#\") {\n\t\ttext = children[0].children\n\t} else {\n\t\tchildList = children\n\t}\n\treturn Vnode(state.tag, attrs.key, hasAttrs ? attrs : undefined, childList, text)\n}\nfunction hyperscript(selector) {\n\t// Because sloppy mode sucks\n\tvar attrs = arguments[1], start = 2, children\n\tif (selector == null || typeof selector !== \"string\" && typeof selector !== \"function\" && typeof selector.view !== \"function\") {\n\t\tthrow Error(\"The selector must be either a string or a component.\");\n\t}\n\tif (typeof selector === \"string\") {\n\t\tvar cached = selectorCache[selector] || compileSelector(selector)\n\t}\n\tif (attrs == null) {\n\t\tattrs = {}\n\t} else if (typeof attrs !== \"object\" || attrs.tag != null || Array.isArray(attrs)) {\n\t\tattrs = {}\n\t\tstart = 1\n\t}\n\tif (arguments.length === start + 1) {\n\t\tchildren = arguments[start]\n\t\tif (!Array.isArray(children)) children = [children]\n\t} else {\n\t\tchildren = []\n\t\twhile (start < arguments.length) children.push(arguments[start++])\n\t}\n\tvar normalized = Vnode.normalizeChildren(children)\n\tif (typeof selector === \"string\") {\n\t\treturn execSelector(cached, attrs, normalized)\n\t} else {\n\t\treturn Vnode(selector, attrs.key, attrs, normalized)\n\t}\n}\nhyperscript.trust = function(html) {\n\tif (html == null) html = \"\"\n\treturn Vnode(\"<\", undefined, undefined, html, undefined, undefined)\n}\nhyperscript.fragment = function(attrs1, children) {\n\treturn Vnode(\"[\", attrs1.key, attrs1, Vnode.normalizeChildren(children), undefined, undefined)\n}\nvar m = hyperscript\n/** @constructor */\nvar PromisePolyfill = function(executor) {\n\tif (!(this instanceof PromisePolyfill)) throw new Error(\"Promise must be called with `new`\")\n\tif (typeof executor !== \"function\") throw new TypeError(\"executor must be a function\")\n\tvar self = this, resolvers = [], rejectors = [], resolveCurrent = handler(resolvers, true), rejectCurrent = handler(rejectors, false)\n\tvar instance = self._instance = {resolvers: resolvers, rejectors: rejectors}\n\tvar callAsync = typeof setImmediate === \"function\" ? setImmediate : setTimeout\n\tfunction handler(list, shouldAbsorb) {\n\t\treturn function execute(value) {\n\t\t\tvar then\n\t\t\ttry {\n\t\t\t\tif (shouldAbsorb && value != null && (typeof value === \"object\" || typeof value === \"function\") && typeof (then = value.then) === \"function\") {\n\t\t\t\t\tif (value === self) throw new TypeError(\"Promise can't be resolved w/ itself\")\n\t\t\t\t\texecuteOnce(then.bind(value))\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcallAsync(function() {\n\t\t\t\t\t\tif (!shouldAbsorb && list.length === 0) console.error(\"Possible unhandled promise rejection:\", value)\n\t\t\t\t\t\tfor (var i = 0; i < list.length; i++) list[i](value)\n\t\t\t\t\t\tresolvers.length = 0, rejectors.length = 0\n\t\t\t\t\t\tinstance.state = shouldAbsorb\n\t\t\t\t\t\tinstance.retry = function() {execute(value)}\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\trejectCurrent(e)\n\t\t\t}\n\t\t}\n\t}\n\tfunction executeOnce(then) {\n\t\tvar runs = 0\n\t\tfunction run(fn) {\n\t\t\treturn function(value) {\n\t\t\t\tif (runs++ > 0) return\n\t\t\t\tfn(value)\n\t\t\t}\n\t\t}\n\t\tvar onerror = run(rejectCurrent)\n\t\ttry {then(run(resolveCurrent), onerror)} catch (e) {onerror(e)}\n\t}\n\texecuteOnce(executor)\n}\nPromisePolyfill.prototype.then = function(onFulfilled, onRejection) {\n\tvar self = this, instance = self._instance\n\tfunction handle(callback, list, next, state) {\n\t\tlist.push(function(value) {\n\t\t\tif (typeof callback !== \"function\") next(value)\n\t\t\telse try {resolveNext(callback(value))} catch (e) {if (rejectNext) rejectNext(e)}\n\t\t})\n\t\tif (typeof instance.retry === \"function\" && state === instance.state) instance.retry()\n\t}\n\tvar resolveNext, rejectNext\n\tvar promise = new PromisePolyfill(function(resolve, reject) {resolveNext = resolve, rejectNext = reject})\n\thandle(onFulfilled, instance.resolvers, resolveNext, true), handle(onRejection, instance.rejectors, rejectNext, false)\n\treturn promise\n}\nPromisePolyfill.prototype.catch = function(onRejection) {\n\treturn this.then(null, onRejection)\n}\nPromisePolyfill.resolve = function(value) {\n\tif (value instanceof PromisePolyfill) return value\n\treturn new PromisePolyfill(function(resolve) {resolve(value)})\n}\nPromisePolyfill.reject = function(value) {\n\treturn new PromisePolyfill(function(resolve, reject) {reject(value)})\n}\nPromisePolyfill.all = function(list) {\n\treturn new PromisePolyfill(function(resolve, reject) {\n\t\tvar total = list.length, count = 0, values = []\n\t\tif (list.length === 0) resolve([])\n\t\telse for (var i = 0; i < list.length; i++) {\n\t\t\t(function(i) {\n\t\t\t\tfunction consume(value) {\n\t\t\t\t\tcount++\n\t\t\t\t\tvalues[i] = value\n\t\t\t\t\tif (count === total) resolve(values)\n\t\t\t\t}\n\t\t\t\tif (list[i] != null && (typeof list[i] === \"object\" || typeof list[i] === \"function\") && typeof list[i].then === \"function\") {\n\t\t\t\t\tlist[i].then(consume, reject)\n\t\t\t\t}\n\t\t\t\telse consume(list[i])\n\t\t\t})(i)\n\t\t}\n\t})\n}\nPromisePolyfill.race = function(list) {\n\treturn new PromisePolyfill(function(resolve, reject) {\n\t\tfor (var i = 0; i < list.length; i++) {\n\t\t\tlist[i].then(resolve, reject)\n\t\t}\n\t})\n}\nif (typeof window !== \"undefined\") {\n\tif (typeof window.Promise === \"undefined\") window.Promise = PromisePolyfill\n\tvar PromisePolyfill = window.Promise\n} else if (typeof global !== \"undefined\") {\n\tif (typeof global.Promise === \"undefined\") global.Promise = PromisePolyfill\n\tvar PromisePolyfill = global.Promise\n} else {\n}\nvar buildQueryString = function(object) {\n\tif (Object.prototype.toString.call(object) !== \"[object Object]\") return \"\"\n\tvar args = []\n\tfor (var key0 in object) {\n\t\tdestructure(key0, object[key0])\n\t}\n\treturn args.join(\"&\")\n\tfunction destructure(key0, value) {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (var i = 0; i < value.length; i++) {\n\t\t\t\tdestructure(key0 + \"[\" + i + \"]\", value[i])\n\t\t\t}\n\t\t}\n\t\telse if (Object.prototype.toString.call(value) === \"[object Object]\") {\n\t\t\tfor (var i in value) {\n\t\t\t\tdestructure(key0 + \"[\" + i + \"]\", value[i])\n\t\t\t}\n\t\t}\n\t\telse args.push(encodeURIComponent(key0) + (value != null && value !== \"\" ? \"=\" + encodeURIComponent(value) : \"\"))\n\t}\n}\nvar FILE_PROTOCOL_REGEX = new RegExp(\"^file://\", \"i\")\nvar _8 = function($window, Promise) {\n\tvar callbackCount = 0\n\tvar oncompletion\n\tfunction setCompletionCallback(callback) {oncompletion = callback}\n\tfunction finalizer() {\n\t\tvar count = 0\n\t\tfunction complete() {if (--count === 0 && typeof oncompletion === \"function\") oncompletion()}\n\t\treturn function finalize(promise0) {\n\t\t\tvar then0 = promise0.then\n\t\t\tpromise0.then = function() {\n\t\t\t\tcount++\n\t\t\t\tvar next = then0.apply(promise0, arguments)\n\t\t\t\tnext.then(complete, function(e) {\n\t\t\t\t\tcomplete()\n\t\t\t\t\tif (count === 0) throw e\n\t\t\t\t})\n\t\t\t\treturn finalize(next)\n\t\t\t}\n\t\t\treturn promise0\n\t\t}\n\t}\n\tfunction normalize(args, extra) {\n\t\tif (typeof args === \"string\") {\n\t\t\tvar url = args\n\t\t\targs = extra || {}\n\t\t\tif (args.url == null) args.url = url\n\t\t}\n\t\treturn args\n\t}\n\tfunction request(args, extra) {\n\t\tvar finalize = finalizer()\n\t\targs = normalize(args, extra)\n\t\tvar promise0 = new Promise(function(resolve, reject) {\n\t\t\tif (args.method == null) args.method = \"GET\"\n\t\t\targs.method = args.method.toUpperCase()\n\t\t\tvar useBody = (args.method === \"GET\" || args.method === \"TRACE\") ? false : (typeof args.useBody === \"boolean\" ? args.useBody : true)\n\t\t\tif (typeof args.serialize !== \"function\") args.serialize = typeof FormData !== \"undefined\" && args.data instanceof FormData ? function(value) {return value} : JSON.stringify\n\t\t\tif (typeof args.deserialize !== \"function\") args.deserialize = deserialize\n\t\t\tif (typeof args.extract !== \"function\") args.extract = extract\n\t\t\targs.url = interpolate(args.url, args.data)\n\t\t\tif (useBody) args.data = args.serialize(args.data)\n\t\t\telse args.url = assemble(args.url, args.data)\n\t\t\tvar xhr = new $window.XMLHttpRequest(),\n\t\t\t\taborted = false,\n\t\t\t\t_abort = xhr.abort\n\t\t\txhr.abort = function abort() {\n\t\t\t\taborted = true\n\t\t\t\t_abort.call(xhr)\n\t\t\t}\n\t\t\txhr.open(args.method, args.url, typeof args.async === \"boolean\" ? args.async : true, typeof args.user === \"string\" ? args.user : undefined, typeof args.password === \"string\" ? args.password : undefined)\n\t\t\tif (args.serialize === JSON.stringify && useBody && !(args.headers && args.headers.hasOwnProperty(\"Content-Type\"))) {\n\t\t\t\txhr.setRequestHeader(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\t\t}\n\t\t\tif (args.deserialize === deserialize && !(args.headers && args.headers.hasOwnProperty(\"Accept\"))) {\n\t\t\t\txhr.setRequestHeader(\"Accept\", \"application/json, text/*\")\n\t\t\t}\n\t\t\tif (args.withCredentials) xhr.withCredentials = args.withCredentials\n\t\t\tfor (var key in args.headers) if ({}.hasOwnProperty.call(args.headers, key)) {\n\t\t\t\txhr.setRequestHeader(key, args.headers[key])\n\t\t\t}\n\t\t\tif (typeof args.config === \"function\") xhr = args.config(xhr, args) || xhr\n\t\t\txhr.onreadystatechange = function() {\n\t\t\t\t// Don't throw errors on xhr.abort().\n\t\t\t\tif(aborted) return\n\t\t\t\tif (xhr.readyState === 4) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tvar response = (args.extract !== extract) ? args.extract(xhr, args) : args.deserialize(args.extract(xhr, args))\n\t\t\t\t\t\tif ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || FILE_PROTOCOL_REGEX.test(args.url)) {\n\t\t\t\t\t\t\tresolve(cast(args.type, response))\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tvar error = new Error(xhr.responseText)\n\t\t\t\t\t\t\tfor (var key in response) error[key] = response[key]\n\t\t\t\t\t\t\treject(error)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\treject(e)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (useBody && (args.data != null)) xhr.send(args.data)\n\t\t\telse xhr.send()\n\t\t})\n\t\treturn args.background === true ? promise0 : finalize(promise0)\n\t}\n\tfunction jsonp(args, extra) {\n\t\tvar finalize = finalizer()\n\t\targs = normalize(args, extra)\n\t\tvar promise0 = new Promise(function(resolve, reject) {\n\t\t\tvar callbackName = args.callbackName || \"_mithril_\" + Math.round(Math.random() * 1e16) + \"_\" + callbackCount++\n\t\t\tvar script = $window.document.createElement(\"script\")\n\t\t\t$window[callbackName] = function(data) {\n\t\t\t\tscript.parentNode.removeChild(script)\n\t\t\t\tresolve(cast(args.type, data))\n\t\t\t\tdelete $window[callbackName]\n\t\t\t}\n\t\t\tscript.onerror = function() {\n\t\t\t\tscript.parentNode.removeChild(script)\n\t\t\t\treject(new Error(\"JSONP request failed\"))\n\t\t\t\tdelete $window[callbackName]\n\t\t\t}\n\t\t\tif (args.data == null) args.data = {}\n\t\t\targs.url = interpolate(args.url, args.data)\n\t\t\targs.data[args.callbackKey || \"callback\"] = callbackName\n\t\t\tscript.src = assemble(args.url, args.data)\n\t\t\t$window.document.documentElement.appendChild(script)\n\t\t})\n\t\treturn args.background === true? promise0 : finalize(promise0)\n\t}\n\tfunction interpolate(url, data) {\n\t\tif (data == null) return url\n\t\tvar tokens = url.match(/:[^\\/]+/gi) || []\n\t\tfor (var i = 0; i < tokens.length; i++) {\n\t\t\tvar key = tokens[i].slice(1)\n\t\t\tif (data[key] != null) {\n\t\t\t\turl = url.replace(tokens[i], data[key])\n\t\t\t}\n\t\t}\n\t\treturn url\n\t}\n\tfunction assemble(url, data) {\n\t\tvar querystring = buildQueryString(data)\n\t\tif (querystring !== \"\") {\n\t\t\tvar prefix = url.indexOf(\"?\") < 0 ? \"?\" : \"&\"\n\t\t\turl += prefix + querystring\n\t\t}\n\t\treturn url\n\t}\n\tfunction deserialize(data) {\n\t\ttry {return data !== \"\" ? JSON.parse(data) : null}\n\t\tcatch (e) {throw new Error(data)}\n\t}\n\tfunction extract(xhr) {return xhr.responseText}\n\tfunction cast(type0, data) {\n\t\tif (typeof type0 === \"function\") {\n\t\t\tif (Array.isArray(data)) {\n\t\t\t\tfor (var i = 0; i < data.length; i++) {\n\t\t\t\t\tdata[i] = new type0(data[i])\n\t\t\t\t}\n\t\t\t}\n\t\t\telse return new type0(data)\n\t\t}\n\t\treturn data\n\t}\n\treturn {request: request, jsonp: jsonp, setCompletionCallback: setCompletionCallback}\n}\nvar requestService = _8(window, PromisePolyfill)\nvar coreRenderer = function($window) {\n\tvar $doc = $window.document\n\tvar $emptyFragment = $doc.createDocumentFragment()\n\tvar nameSpace = {\n\t\tsvg: \"http://www.w3.org/2000/svg\",\n\t\tmath: \"http://www.w3.org/1998/Math/MathML\"\n\t}\n\tvar onevent\n\tfunction setEventCallback(callback) {return onevent = callback}\n\tfunction getNameSpace(vnode) {\n\t\treturn vnode.attrs && vnode.attrs.xmlns || nameSpace[vnode.tag]\n\t}\n\t//create\n\tfunction createNodes(parent, vnodes, start, end, hooks, nextSibling, ns) {\n\t\tfor (var i = start; i < end; i++) {\n\t\t\tvar vnode = vnodes[i]\n\t\t\tif (vnode != null) {\n\t\t\t\tcreateNode(parent, vnode, hooks, ns, nextSibling)\n\t\t\t}\n\t\t}\n\t}\n\tfunction createNode(parent, vnode, hooks, ns, nextSibling) {\n\t\tvar tag = vnode.tag\n\t\tif (typeof tag === \"string\") {\n\t\t\tvnode.state = {}\n\t\t\tif (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)\n\t\t\tswitch (tag) {\n\t\t\t\tcase \"#\": return createText(parent, vnode, nextSibling)\n\t\t\t\tcase \"<\": return createHTML(parent, vnode, nextSibling)\n\t\t\t\tcase \"[\": return createFragment(parent, vnode, hooks, ns, nextSibling)\n\t\t\t\tdefault: return createElement(parent, vnode, hooks, ns, nextSibling)\n\t\t\t}\n\t\t}\n\t\telse return createComponent(parent, vnode, hooks, ns, nextSibling)\n\t}\n\tfunction createText(parent, vnode, nextSibling) {\n\t\tvnode.dom = $doc.createTextNode(vnode.children)\n\t\tinsertNode(parent, vnode.dom, nextSibling)\n\t\treturn vnode.dom\n\t}\n\tfunction createHTML(parent, vnode, nextSibling) {\n\t\tvar match1 = vnode.children.match(/^\\s*?<(\\w+)/im) || []\n\t\tvar parent1 = {caption: \"table\", thead: \"table\", tbody: \"table\", tfoot: \"table\", tr: \"tbody\", th: \"tr\", td: \"tr\", colgroup: \"table\", col: \"colgroup\"}[match1[1]] || \"div\"\n\t\tvar temp = $doc.createElement(parent1)\n\t\ttemp.innerHTML = vnode.children\n\t\tvnode.dom = temp.firstChild\n\t\tvnode.domSize = temp.childNodes.length\n\t\tvar fragment = $doc.createDocumentFragment()\n\t\tvar child\n\t\twhile (child = temp.firstChild) {\n\t\t\tfragment.appendChild(child)\n\t\t}\n\t\tinsertNode(parent, fragment, nextSibling)\n\t\treturn fragment\n\t}\n\tfunction createFragment(parent, vnode, hooks, ns, nextSibling) {\n\t\tvar fragment = $doc.createDocumentFragment()\n\t\tif (vnode.children != null) {\n\t\t\tvar children = vnode.children\n\t\t\tcreateNodes(fragment, children, 0, children.length, hooks, null, ns)\n\t\t}\n\t\tvnode.dom = fragment.firstChild\n\t\tvnode.domSize = fragment.childNodes.length\n\t\tinsertNode(parent, fragment, nextSibling)\n\t\treturn fragment\n\t}\n\tfunction createElement(parent, vnode, hooks, ns, nextSibling) {\n\t\tvar tag = vnode.tag\n\t\tvar attrs2 = vnode.attrs\n\t\tvar is = attrs2 && attrs2.is\n\t\tns = getNameSpace(vnode) || ns\n\t\tvar element = ns ?\n\t\t\tis ? $doc.createElementNS(ns, tag, {is: is}) : $doc.createElementNS(ns, tag) :\n\t\t\tis ? $doc.createElement(tag, {is: is}) : $doc.createElement(tag)\n\t\tvnode.dom = element\n\t\tif (attrs2 != null) {\n\t\t\tsetAttrs(vnode, attrs2, ns)\n\t\t}\n\t\tinsertNode(parent, element, nextSibling)\n\t\tif (vnode.attrs != null && vnode.attrs.contenteditable != null) {\n\t\t\tsetContentEditable(vnode)\n\t\t}\n\t\telse {\n\t\t\tif (vnode.text != null) {\n\t\t\t\tif (vnode.text !== \"\") element.textContent = vnode.text\n\t\t\t\telse vnode.children = [Vnode(\"#\", undefined, undefined, vnode.text, undefined, undefined)]\n\t\t\t}\n\t\t\tif (vnode.children != null) {\n\t\t\t\tvar children = vnode.children\n\t\t\t\tcreateNodes(element, children, 0, children.length, hooks, null, ns)\n\t\t\t\tsetLateAttrs(vnode)\n\t\t\t}\n\t\t}\n\t\treturn element\n\t}\n\tfunction initComponent(vnode, hooks) {\n\t\tvar sentinel\n\t\tif (typeof vnode.tag.view === \"function\") {\n\t\t\tvnode.state = Object.create(vnode.tag)\n\t\t\tsentinel = vnode.state.view\n\t\t\tif (sentinel.$$reentrantLock$$ != null) return $emptyFragment\n\t\t\tsentinel.$$reentrantLock$$ = true\n\t\t} else {\n\t\t\tvnode.state = void 0\n\t\t\tsentinel = vnode.tag\n\t\t\tif (sentinel.$$reentrantLock$$ != null) return $emptyFragment\n\t\t\tsentinel.$$reentrantLock$$ = true\n\t\t\tvnode.state = (vnode.tag.prototype != null && typeof vnode.tag.prototype.view === \"function\") ? new vnode.tag(vnode) : vnode.tag(vnode)\n\t\t}\n\t\tvnode._state = vnode.state\n\t\tif (vnode.attrs != null) initLifecycle(vnode.attrs, vnode, hooks)\n\t\tinitLifecycle(vnode._state, vnode, hooks)\n\t\tvnode.instance = Vnode.normalize(vnode._state.view.call(vnode.state, vnode))\n\t\tif (vnode.instance === vnode) throw Error(\"A view cannot return the vnode it received as argument\")\n\t\tsentinel.$$reentrantLock$$ = null\n\t}\n\tfunction createComponent(parent, vnode, hooks, ns, nextSibling) {\n\t\tinitComponent(vnode, hooks)\n\t\tif (vnode.instance != null) {\n\t\t\tvar element = createNode(parent, vnode.instance, hooks, ns, nextSibling)\n\t\t\tvnode.dom = vnode.instance.dom\n\t\t\tvnode.domSize = vnode.dom != null ? vnode.instance.domSize : 0\n\t\t\tinsertNode(parent, element, nextSibling)\n\t\t\treturn element\n\t\t}\n\t\telse {\n\t\t\tvnode.domSize = 0\n\t\t\treturn $emptyFragment\n\t\t}\n\t}\n\t//update\n\tfunction updateNodes(parent, old, vnodes, recycling, hooks, nextSibling, ns) {\n\t\tif (old === vnodes || old == null && vnodes == null) return\n\t\telse if (old == null) createNodes(parent, vnodes, 0, vnodes.length, hooks, nextSibling, ns)\n\t\telse if (vnodes == null) removeNodes(old, 0, old.length, vnodes)\n\t\telse {\n\t\t\tif (old.length === vnodes.length) {\n\t\t\t\tvar isUnkeyed = false\n\t\t\t\tfor (var i = 0; i < vnodes.length; i++) {\n\t\t\t\t\tif (vnodes[i] != null && old[i] != null) {\n\t\t\t\t\t\tisUnkeyed = vnodes[i].key == null && old[i].key == null\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (isUnkeyed) {\n\t\t\t\t\tfor (var i = 0; i < old.length; i++) {\n\t\t\t\t\t\tif (old[i] === vnodes[i]) continue\n\t\t\t\t\t\telse if (old[i] == null && vnodes[i] != null) createNode(parent, vnodes[i], hooks, ns, getNextSibling(old, i + 1, nextSibling))\n\t\t\t\t\t\telse if (vnodes[i] == null) removeNodes(old, i, i + 1, vnodes)\n\t\t\t\t\t\telse updateNode(parent, old[i], vnodes[i], hooks, getNextSibling(old, i + 1, nextSibling), recycling, ns)\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\trecycling = recycling || isRecyclable(old, vnodes)\n\t\t\tif (recycling) {\n\t\t\t\tvar pool = old.pool\n\t\t\t\told = old.concat(old.pool)\n\t\t\t}\n\t\t\tvar oldStart = 0, start = 0, oldEnd = old.length - 1, end = vnodes.length - 1, map\n\t\t\twhile (oldEnd >= oldStart && end >= start) {\n\t\t\t\tvar o = old[oldStart], v = vnodes[start]\n\t\t\t\tif (o === v && !recycling) oldStart++, start++\n\t\t\t\telse if (o == null) oldStart++\n\t\t\t\telse if (v == null) start++\n\t\t\t\telse if (o.key === v.key) {\n\t\t\t\t\tvar shouldRecycle = (pool != null && oldStart >= old.length - pool.length) || ((pool == null) && recycling)\n\t\t\t\t\toldStart++, start++\n\t\t\t\t\tupdateNode(parent, o, v, hooks, getNextSibling(old, oldStart, nextSibling), shouldRecycle, ns)\n\t\t\t\t\tif (recycling && o.tag === v.tag) insertNode(parent, toFragment(o), nextSibling)\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tvar o = old[oldEnd]\n\t\t\t\t\tif (o === v && !recycling) oldEnd--, start++\n\t\t\t\t\telse if (o == null) oldEnd--\n\t\t\t\t\telse if (v == null) start++\n\t\t\t\t\telse if (o.key === v.key) {\n\t\t\t\t\t\tvar shouldRecycle = (pool != null && oldEnd >= old.length - pool.length) || ((pool == null) && recycling)\n\t\t\t\t\t\tupdateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), shouldRecycle, ns)\n\t\t\t\t\t\tif (recycling || start < end) insertNode(parent, toFragment(o), getNextSibling(old, oldStart, nextSibling))\n\t\t\t\t\t\toldEnd--, start++\n\t\t\t\t\t}\n\t\t\t\t\telse break\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile (oldEnd >= oldStart && end >= start) {\n\t\t\t\tvar o = old[oldEnd], v = vnodes[end]\n\t\t\t\tif (o === v && !recycling) oldEnd--, end--\n\t\t\t\telse if (o == null) oldEnd--\n\t\t\t\telse if (v == null) end--\n\t\t\t\telse if (o.key === v.key) {\n\t\t\t\t\tvar shouldRecycle = (pool != null && oldEnd >= old.length - pool.length) || ((pool == null) && recycling)\n\t\t\t\t\tupdateNode(parent, o, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), shouldRecycle, ns)\n\t\t\t\t\tif (recycling && o.tag === v.tag) insertNode(parent, toFragment(o), nextSibling)\n\t\t\t\t\tif (o.dom != null) nextSibling = o.dom\n\t\t\t\t\toldEnd--, end--\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!map) map = getKeyMap(old, oldEnd)\n\t\t\t\t\tif (v != null) {\n\t\t\t\t\t\tvar oldIndex = map[v.key]\n\t\t\t\t\t\tif (oldIndex != null) {\n\t\t\t\t\t\t\tvar movable = old[oldIndex]\n\t\t\t\t\t\t\tvar shouldRecycle = (pool != null && oldIndex >= old.length - pool.length) || ((pool == null) && recycling)\n\t\t\t\t\t\t\tupdateNode(parent, movable, v, hooks, getNextSibling(old, oldEnd + 1, nextSibling), recycling, ns)\n\t\t\t\t\t\t\tinsertNode(parent, toFragment(movable), nextSibling)\n\t\t\t\t\t\t\told[oldIndex].skip = true\n\t\t\t\t\t\t\tif (movable.dom != null) nextSibling = movable.dom\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tvar dom = createNode(parent, v, hooks, ns, nextSibling)\n\t\t\t\t\t\t\tnextSibling = dom\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tend--\n\t\t\t\t}\n\t\t\t\tif (end < start) break\n\t\t\t}\n\t\t\tcreateNodes(parent, vnodes, start, end + 1, hooks, nextSibling, ns)\n\t\t\tremoveNodes(old, oldStart, oldEnd + 1, vnodes)\n\t\t}\n\t}\n\tfunction updateNode(parent, old, vnode, hooks, nextSibling, recycling, ns) {\n\t\tvar oldTag = old.tag, tag = vnode.tag\n\t\tif (oldTag === tag) {\n\t\t\tvnode.state = old.state\n\t\t\tvnode._state = old._state\n\t\t\tvnode.events = old.events\n\t\t\tif (!recycling && shouldNotUpdate(vnode, old)) return\n\t\t\tif (typeof oldTag === \"string\") {\n\t\t\t\tif (vnode.attrs != null) {\n\t\t\t\t\tif (recycling) {\n\t\t\t\t\t\tvnode.state = {}\n\t\t\t\t\t\tinitLifecycle(vnode.attrs, vnode, hooks)\n\t\t\t\t\t}\n\t\t\t\t\telse updateLifecycle(vnode.attrs, vnode, hooks)\n\t\t\t\t}\n\t\t\t\tswitch (oldTag) {\n\t\t\t\t\tcase \"#\": updateText(old, vnode); break\n\t\t\t\t\tcase \"<\": updateHTML(parent, old, vnode, nextSibling); break\n\t\t\t\t\tcase \"[\": updateFragment(parent, old, vnode, recycling, hooks, nextSibling, ns); break\n\t\t\t\t\tdefault: updateElement(old, vnode, recycling, hooks, ns)\n\t\t\t\t}\n\t\t\t}\n\t\t\telse updateComponent(parent, old, vnode, hooks, nextSibling, recycling, ns)\n\t\t}\n\t\telse {\n\t\t\tremoveNode(old, null)\n\t\t\tcreateNode(parent, vnode, hooks, ns, nextSibling)\n\t\t}\n\t}\n\tfunction updateText(old, vnode) {\n\t\tif (old.children.toString() !== vnode.children.toString()) {\n\t\t\told.dom.nodeValue = vnode.children\n\t\t}\n\t\tvnode.dom = old.dom\n\t}\n\tfunction updateHTML(parent, old, vnode, nextSibling) {\n\t\tif (old.children !== vnode.children) {\n\t\t\ttoFragment(old)\n\t\t\tcreateHTML(parent, vnode, nextSibling)\n\t\t}\n\t\telse vnode.dom = old.dom, vnode.domSize = old.domSize\n\t}\n\tfunction updateFragment(parent, old, vnode, recycling, hooks, nextSibling, ns) {\n\t\tupdateNodes(parent, old.children, vnode.children, recycling, hooks, nextSibling, ns)\n\t\tvar domSize = 0, children = vnode.children\n\t\tvnode.dom = null\n\t\tif (children != null) {\n\t\t\tfor (var i = 0; i < children.length; i++) {\n\t\t\t\tvar child = children[i]\n\t\t\t\tif (child != null && child.dom != null) {\n\t\t\t\t\tif (vnode.dom == null) vnode.dom = child.dom\n\t\t\t\t\tdomSize += child.domSize || 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (domSize !== 1) vnode.domSize = domSize\n\t\t}\n\t}\n\tfunction updateElement(old, vnode, recycling, hooks, ns) {\n\t\tvar element = vnode.dom = old.dom\n\t\tns = getNameSpace(vnode) || ns\n\t\tif (vnode.tag === \"textarea\") {\n\t\t\tif (vnode.attrs == null) vnode.attrs = {}\n\t\t\tif (vnode.text != null) {\n\t\t\t\tvnode.attrs.value = vnode.text //FIXME handle0 multiple children\n\t\t\t\tvnode.text = undefined\n\t\t\t}\n\t\t}\n\t\tupdateAttrs(vnode, old.attrs, vnode.attrs, ns)\n\t\tif (vnode.attrs != null && vnode.attrs.contenteditable != null) {\n\t\t\tsetContentEditable(vnode)\n\t\t}\n\t\telse if (old.text != null && vnode.text != null && vnode.text !== \"\") {\n\t\t\tif (old.text.toString() !== vnode.text.toString()) old.dom.firstChild.nodeValue = vnode.text\n\t\t}\n\t\telse {\n\t\t\tif (old.text != null) old.children = [Vnode(\"#\", undefined, undefined, old.text, undefined, old.dom.firstChild)]\n\t\t\tif (vnode.text != null) vnode.children = [Vnode(\"#\", undefined, undefined, vnode.text, undefined, undefined)]\n\t\t\tupdateNodes(element, old.children, vnode.children, recycling, hooks, null, ns)\n\t\t}\n\t}\n\tfunction updateComponent(parent, old, vnode, hooks, nextSibling, recycling, ns) {\n\t\tif (recycling) {\n\t\t\tinitComponent(vnode, hooks)\n\t\t} else {\n\t\t\tvnode.instance = Vnode.normalize(vnode._state.view.call(vnode.state, vnode))\n\t\t\tif (vnode.instance === vnode) throw Error(\"A view cannot return the vnode it received as argument\")\n\t\t\tif (vnode.attrs != null) updateLifecycle(vnode.attrs, vnode, hooks)\n\t\t\tupdateLifecycle(vnode._state, vnode, hooks)\n\t\t}\n\t\tif (vnode.instance != null) {\n\t\t\tif (old.instance == null) createNode(parent, vnode.instance, hooks, ns, nextSibling)\n\t\t\telse updateNode(parent, old.instance, vnode.instance, hooks, nextSibling, recycling, ns)\n\t\t\tvnode.dom = vnode.instance.dom\n\t\t\tvnode.domSize = vnode.instance.domSize\n\t\t}\n\t\telse if (old.instance != null) {\n\t\t\tremoveNode(old.instance, null)\n\t\t\tvnode.dom = undefined\n\t\t\tvnode.domSize = 0\n\t\t}\n\t\telse {\n\t\t\tvnode.dom = old.dom\n\t\t\tvnode.domSize = old.domSize\n\t\t}\n\t}\n\tfunction isRecyclable(old, vnodes) {\n\t\tif (old.pool != null && Math.abs(old.pool.length - vnodes.length) <= Math.abs(old.length - vnodes.length)) {\n\t\t\tvar oldChildrenLength = old[0] && old[0].children && old[0].children.length || 0\n\t\t\tvar poolChildrenLength = old.pool[0] && old.pool[0].children && old.pool[0].children.length || 0\n\t\t\tvar vnodesChildrenLength = vnodes[0] && vnodes[0].children && vnodes[0].children.length || 0\n\t\t\tif (Math.abs(poolChildrenLength - vnodesChildrenLength) <= Math.abs(oldChildrenLength - vnodesChildrenLength)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfunction getKeyMap(vnodes, end) {\n\t\tvar map = {}, i = 0\n\t\tfor (var i = 0; i < end; i++) {\n\t\t\tvar vnode = vnodes[i]\n\t\t\tif (vnode != null) {\n\t\t\t\tvar key2 = vnode.key\n\t\t\t\tif (key2 != null) map[key2] = i\n\t\t\t}\n\t\t}\n\t\treturn map\n\t}\n\tfunction toFragment(vnode) {\n\t\tvar count0 = vnode.domSize\n\t\tif (count0 != null || vnode.dom == null) {\n\t\t\tvar fragment = $doc.createDocumentFragment()\n\t\t\tif (count0 > 0) {\n\t\t\t\tvar dom = vnode.dom\n\t\t\t\twhile (--count0) fragment.appendChild(dom.nextSibling)\n\t\t\t\tfragment.insertBefore(dom, fragment.firstChild)\n\t\t\t}\n\t\t\treturn fragment\n\t\t}\n\t\telse return vnode.dom\n\t}\n\tfunction getNextSibling(vnodes, i, nextSibling) {\n\t\tfor (; i < vnodes.length; i++) {\n\t\t\tif (vnodes[i] != null && vnodes[i].dom != null) return vnodes[i].dom\n\t\t}\n\t\treturn nextSibling\n\t}\n\tfunction insertNode(parent, dom, nextSibling) {\n\t\tif (nextSibling && nextSibling.parentNode) parent.insertBefore(dom, nextSibling)\n\t\telse parent.appendChild(dom)\n\t}\n\tfunction setContentEditable(vnode) {\n\t\tvar children = vnode.children\n\t\tif (children != null && children.length === 1 && children[0].tag === \"<\") {\n\t\t\tvar content = children[0].children\n\t\t\tif (vnode.dom.innerHTML !== content) vnode.dom.innerHTML = content\n\t\t}\n\t\telse if (vnode.text != null || children != null && children.length !== 0) throw new Error(\"Child node of a contenteditable must be trusted\")\n\t}\n\t//remove\n\tfunction removeNodes(vnodes, start, end, context) {\n\t\tfor (var i = start; i < end; i++) {\n\t\t\tvar vnode = vnodes[i]\n\t\t\tif (vnode != null) {\n\t\t\t\tif (vnode.skip) vnode.skip = false\n\t\t\t\telse removeNode(vnode, context)\n\t\t\t}\n\t\t}\n\t}\n\tfunction removeNode(vnode, context) {\n\t\tvar expected = 1, called = 0\n\t\tif (vnode.attrs && typeof vnode.attrs.onbeforeremove === \"function\") {\n\t\t\tvar result = vnode.attrs.onbeforeremove.call(vnode.state, vnode)\n\t\t\tif (result != null && typeof result.then === \"function\") {\n\t\t\t\texpected++\n\t\t\t\tresult.then(continuation, continuation)\n\t\t\t}\n\t\t}\n\t\tif (typeof vnode.tag !== \"string\" && typeof vnode._state.onbeforeremove === \"function\") {\n\t\t\tvar result = vnode._state.onbeforeremove.call(vnode.state, vnode)\n\t\t\tif (result != null && typeof result.then === \"function\") {\n\t\t\t\texpected++\n\t\t\t\tresult.then(continuation, continuation)\n\t\t\t}\n\t\t}\n\t\tcontinuation()\n\t\tfunction continuation() {\n\t\t\tif (++called === expected) {\n\t\t\t\tonremove(vnode)\n\t\t\t\tif (vnode.dom) {\n\t\t\t\t\tvar count0 = vnode.domSize || 1\n\t\t\t\t\tif (count0 > 1) {\n\t\t\t\t\t\tvar dom = vnode.dom\n\t\t\t\t\t\twhile (--count0) {\n\t\t\t\t\t\t\tremoveNodeFromDOM(dom.nextSibling)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tremoveNodeFromDOM(vnode.dom)\n\t\t\t\t\tif (context != null && vnode.domSize == null && !hasIntegrationMethods(vnode.attrs) && typeof vnode.tag === \"string\") { //TODO test custom elements\n\t\t\t\t\t\tif (!context.pool) context.pool = [vnode]\n\t\t\t\t\t\telse context.pool.push(vnode)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfunction removeNodeFromDOM(node) {\n\t\tvar parent = node.parentNode\n\t\tif (parent != null) parent.removeChild(node)\n\t}\n\tfunction onremove(vnode) {\n\t\tif (vnode.attrs && typeof vnode.attrs.onremove === \"function\") vnode.attrs.onremove.call(vnode.state, vnode)\n\t\tif (typeof vnode.tag !== \"string\") {\n\t\t\tif (typeof vnode._state.onremove === \"function\") vnode._state.onremove.call(vnode.state, vnode)\n\t\t\tif (vnode.instance != null) onremove(vnode.instance)\n\t\t} else {\n\t\t\tvar children = vnode.children\n\t\t\tif (Array.isArray(children)) {\n\t\t\t\tfor (var i = 0; i < children.length; i++) {\n\t\t\t\t\tvar child = children[i]\n\t\t\t\t\tif (child != null) onremove(child)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//attrs2\n\tfunction setAttrs(vnode, attrs2, ns) {\n\t\tfor (var key2 in attrs2) {\n\t\t\tsetAttr(vnode, key2, null, attrs2[key2], ns)\n\t\t}\n\t}\n\tfunction setAttr(vnode, key2, old, value, ns) {\n\t\tvar element = vnode.dom\n\t\tif (key2 === \"key\" || key2 === \"is\" || (old === value && !isFormAttribute(vnode, key2)) && typeof value !== \"object\" || typeof value === \"undefined\" || isLifecycleMethod(key2)) return\n\t\tvar nsLastIndex = key2.indexOf(\":\")\n\t\tif (nsLastIndex > -1 && key2.substr(0, nsLastIndex) === \"xlink\") {\n\t\t\telement.setAttributeNS(\"http://www.w3.org/1999/xlink\", key2.slice(nsLastIndex + 1), value)\n\t\t}\n\t\telse if (key2[0] === \"o\" && key2[1] === \"n\" && typeof value === \"function\") updateEvent(vnode, key2, value)\n\t\telse if (key2 === \"style\") updateStyle(element, old, value)\n\t\telse if (key2 in element && !isAttribute(key2) && ns === undefined && !isCustomElement(vnode)) {\n\t\t\tif (key2 === \"value\") {\n\t\t\t\tvar normalized0 = \"\" + value // eslint-disable-line no-implicit-coercion\n\t\t\t\t//setting input[value] to same value by typing on focused element moves cursor to end in Chrome\n\t\t\t\tif ((vnode.tag === \"input\" || vnode.tag === \"textarea\") && vnode.dom.value === normalized0 && vnode.dom === $doc.activeElement) return\n\t\t\t\t//setting select[value] to same value while having select open blinks select dropdown in Chrome\n\t\t\t\tif (vnode.tag === \"select\") {\n\t\t\t\t\tif (value === null) {\n\t\t\t\t\t\tif (vnode.dom.selectedIndex === -1 && vnode.dom === $doc.activeElement) return\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (old !== null && vnode.dom.value === normalized0 && vnode.dom === $doc.activeElement) return\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//setting option[value] to same value while having select open blinks select dropdown in Chrome\n\t\t\t\tif (vnode.tag === \"option\" && old != null && vnode.dom.value === normalized0) return\n\t\t\t}\n\t\t\t// If you assign an input type1 that is not supported by IE 11 with an assignment expression, an error0 will occur.\n\t\t\tif (vnode.tag === \"input\" && key2 === \"type\") {\n\t\t\t\telement.setAttribute(key2, value)\n\t\t\t\treturn\n\t\t\t}\n\t\t\telement[key2] = value\n\t\t}\n\t\telse {\n\t\t\tif (typeof value === \"boolean\") {\n\t\t\t\tif (value) element.setAttribute(key2, \"\")\n\t\t\t\telse element.removeAttribute(key2)\n\t\t\t}\n\t\t\telse element.setAttribute(key2 === \"className\" ? \"class\" : key2, value)\n\t\t}\n\t}\n\tfunction setLateAttrs(vnode) {\n\t\tvar attrs2 = vnode.attrs\n\t\tif (vnode.tag === \"select\" && attrs2 != null) {\n\t\t\tif (\"value\" in attrs2) setAttr(vnode, \"value\", null, attrs2.value, undefined)\n\t\t\tif (\"selectedIndex\" in attrs2) setAttr(vnode, \"selectedIndex\", null, attrs2.selectedIndex, undefined)\n\t\t}\n\t}\n\tfunction updateAttrs(vnode, old, attrs2, ns) {\n\t\tif (attrs2 != null) {\n\t\t\tfor (var key2 in attrs2) {\n\t\t\t\tsetAttr(vnode, key2, old && old[key2], attrs2[key2], ns)\n\t\t\t}\n\t\t}\n\t\tif (old != null) {\n\t\t\tfor (var key2 in old) {\n\t\t\t\tif (attrs2 == null || !(key2 in attrs2)) {\n\t\t\t\t\tif (key2 === \"className\") key2 = \"class\"\n\t\t\t\t\tif (key2[0] === \"o\" && key2[1] === \"n\" && !isLifecycleMethod(key2)) updateEvent(vnode, key2, undefined)\n\t\t\t\t\telse if (key2 !== \"key\") vnode.dom.removeAttribute(key2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfunction isFormAttribute(vnode, attr) {\n\t\treturn attr === \"value\" || attr === \"checked\" || attr === \"selectedIndex\" || attr === \"selected\" && vnode.dom === $doc.activeElement\n\t}\n\tfunction isLifecycleMethod(attr) {\n\t\treturn attr === \"oninit\" || attr === \"oncreate\" || attr === \"onupdate\" || attr === \"onremove\" || attr === \"onbeforeremove\" || attr === \"onbeforeupdate\"\n\t}\n\tfunction isAttribute(attr) {\n\t\treturn attr === \"href\" || attr === \"list\" || attr === \"form\" || attr === \"width\" || attr === \"height\"// || attr === \"type\"\n\t}\n\tfunction isCustomElement(vnode){\n\t\treturn vnode.attrs.is || vnode.tag.indexOf(\"-\") > -1\n\t}\n\tfunction hasIntegrationMethods(source) {\n\t\treturn source != null && (source.oncreate || source.onupdate || source.onbeforeremove || source.onremove)\n\t}\n\t//style\n\tfunction updateStyle(element, old, style) {\n\t\tif (old === style) element.style.cssText = \"\", old = null\n\t\tif (style == null) element.style.cssText = \"\"\n\t\telse if (typeof style === \"string\") element.style.cssText = style\n\t\telse {\n\t\t\tif (typeof old === \"string\") element.style.cssText = \"\"\n\t\t\tfor (var key2 in style) {\n\t\t\t\telement.style[key2] = style[key2]\n\t\t\t}\n\t\t\tif (old != null && typeof old !== \"string\") {\n\t\t\t\tfor (var key2 in old) {\n\t\t\t\t\tif (!(key2 in style)) element.style[key2] = \"\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//event\n\tfunction updateEvent(vnode, key2, value) {\n\t\tvar element = vnode.dom\n\t\tvar callback = typeof onevent !== \"function\" ? value : function(e) {\n\t\t\tvar result = value.call(element, e)\n\t\t\tonevent.call(element, e)\n\t\t\treturn result\n\t\t}\n\t\tif (key2 in element) element[key2] = typeof value === \"function\" ? callback : null\n\t\telse {\n\t\t\tvar eventName = key2.slice(2)\n\t\t\tif (vnode.events === undefined) vnode.events = {}\n\t\t\tif (vnode.events[key2] === callback) return\n\t\t\tif (vnode.events[key2] != null) element.removeEventListener(eventName, vnode.events[key2], false)\n\t\t\tif (typeof value === \"function\") {\n\t\t\t\tvnode.events[key2] = callback\n\t\t\t\telement.addEventListener(eventName, vnode.events[key2], false)\n\t\t\t}\n\t\t}\n\t}\n\t//lifecycle\n\tfunction initLifecycle(source, vnode, hooks) {\n\t\tif (typeof source.oninit === \"function\") source.oninit.call(vnode.state, vnode)\n\t\tif (typeof source.oncreate === \"function\") hooks.push(source.oncreate.bind(vnode.state, vnode))\n\t}\n\tfunction updateLifecycle(source, vnode, hooks) {\n\t\tif (typeof source.onupdate === \"function\") hooks.push(source.onupdate.bind(vnode.state, vnode))\n\t}\n\tfunction shouldNotUpdate(vnode, old) {\n\t\tvar forceVnodeUpdate, forceComponentUpdate\n\t\tif (vnode.attrs != null && typeof vnode.attrs.onbeforeupdate === \"function\") forceVnodeUpdate = vnode.attrs.onbeforeupdate.call(vnode.state, vnode, old)\n\t\tif (typeof vnode.tag !== \"string\" && typeof vnode._state.onbeforeupdate === \"function\") forceComponentUpdate = vnode._state.onbeforeupdate.call(vnode.state, vnode, old)\n\t\tif (!(forceVnodeUpdate === undefined && forceComponentUpdate === undefined) && !forceVnodeUpdate && !forceComponentUpdate) {\n\t\t\tvnode.dom = old.dom\n\t\t\tvnode.domSize = old.domSize\n\t\t\tvnode.instance = old.instance\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\tfunction render(dom, vnodes) {\n\t\tif (!dom) throw new Error(\"Ensure the DOM element being passed to m.route/m.mount/m.render is not undefined.\")\n\t\tvar hooks = []\n\t\tvar active = $doc.activeElement\n\t\tvar namespace = dom.namespaceURI\n\t\t// First time0 rendering into a node clears it out\n\t\tif (dom.vnodes == null) dom.textContent = \"\"\n\t\tif (!Array.isArray(vnodes)) vnodes = [vnodes]\n\t\tupdateNodes(dom, dom.vnodes, Vnode.normalizeChildren(vnodes), false, hooks, null, namespace === \"http://www.w3.org/1999/xhtml\" ? undefined : namespace)\n\t\tdom.vnodes = vnodes\n\t\t// document.activeElement can return null in IE https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement\n\t\tif (active != null && $doc.activeElement !== active) active.focus()\n\t\tfor (var i = 0; i < hooks.length; i++) hooks[i]()\n\t}\n\treturn {render: render, setEventCallback: setEventCallback}\n}\nfunction throttle(callback) {\n\t//60fps translates to 16.6ms, round it down since setTimeout requires int\n\tvar time = 16\n\tvar last = 0, pending = null\n\tvar timeout = typeof requestAnimationFrame === \"function\" ? requestAnimationFrame : setTimeout\n\treturn function() {\n\t\tvar now = Date.now()\n\t\tif (last === 0 || now - last >= time) {\n\t\t\tlast = now\n\t\t\tcallback()\n\t\t}\n\t\telse if (pending === null) {\n\t\t\tpending = timeout(function() {\n\t\t\t\tpending = null\n\t\t\t\tcallback()\n\t\t\t\tlast = Date.now()\n\t\t\t}, time - (now - last))\n\t\t}\n\t}\n}\nvar _11 = function($window) {\n\tvar renderService = coreRenderer($window)\n\trenderService.setEventCallback(function(e) {\n\t\tif (e.redraw === false) e.redraw = undefined\n\t\telse redraw()\n\t})\n\tvar callbacks = []\n\tfunction subscribe(key1, callback) {\n\t\tunsubscribe(key1)\n\t\tcallbacks.push(key1, throttle(callback))\n\t}\n\tfunction unsubscribe(key1) {\n\t\tvar index = callbacks.indexOf(key1)\n\t\tif (index > -1) callbacks.splice(index, 2)\n\t}\n\tfunction redraw() {\n\t\tfor (var i = 1; i < callbacks.length; i += 2) {\n\t\t\tcallbacks[i]()\n\t\t}\n\t}\n\treturn {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render}\n}\nvar redrawService = _11(window)\nrequestService.setCompletionCallback(redrawService.redraw)\nvar _16 = function(redrawService0) {\n\treturn function(root, component) {\n\t\tif (component === null) {\n\t\t\tredrawService0.render(root, [])\n\t\t\tredrawService0.unsubscribe(root)\n\t\t\treturn\n\t\t}\n\t\t\n\t\tif (component.view == null && typeof component !== \"function\") throw new Error(\"m.mount(element, component) expects a component, not a vnode\")\n\t\t\n\t\tvar run0 = function() {\n\t\t\tredrawService0.render(root, Vnode(component))\n\t\t}\n\t\tredrawService0.subscribe(root, run0)\n\t\tredrawService0.redraw()\n\t}\n}\nm.mount = _16(redrawService)\nvar Promise = PromisePolyfill\nvar parseQueryString = function(string) {\n\tif (string === \"\" || string == null) return {}\n\tif (string.charAt(0) === \"?\") string = string.slice(1)\n\tvar entries = string.split(\"&\"), data0 = {}, counters = {}\n\tfor (var i = 0; i < entries.length; i++) {\n\t\tvar entry = entries[i].split(\"=\")\n\t\tvar key5 = decodeURIComponent(entry[0])\n\t\tvar value = entry.length === 2 ? decodeURIComponent(entry[1]) : \"\"\n\t\tif (value === \"true\") value = true\n\t\telse if (value === \"false\") value = false\n\t\tvar levels = key5.split(/\\]\\[?|\\[/)\n\t\tvar cursor = data0\n\t\tif (key5.indexOf(\"[\") > -1) levels.pop()\n\t\tfor (var j = 0; j < levels.length; j++) {\n\t\t\tvar level = levels[j], nextLevel = levels[j + 1]\n\t\t\tvar isNumber = nextLevel == \"\" || !isNaN(parseInt(nextLevel, 10))\n\t\t\tvar isValue = j === levels.length - 1\n\t\t\tif (level === \"\") {\n\t\t\t\tvar key5 = levels.slice(0, j).join()\n\t\t\t\tif (counters[key5] == null) counters[key5] = 0\n\t\t\t\tlevel = counters[key5]++\n\t\t\t}\n\t\t\tif (cursor[level] == null) {\n\t\t\t\tcursor[level] = isValue ? value : isNumber ? [] : {}\n\t\t\t}\n\t\t\tcursor = cursor[level]\n\t\t}\n\t}\n\treturn data0\n}\nvar coreRouter = function($window) {\n\tvar supportsPushState = typeof $window.history.pushState === \"function\"\n\tvar callAsync0 = typeof setImmediate === \"function\" ? setImmediate : setTimeout\n\tfunction normalize1(fragment0) {\n\t\tvar data = $window.location[fragment0].replace(/(?:%[a-f89][a-f0-9])+/gim, decodeURIComponent)\n\t\tif (fragment0 === \"pathname\" && data[0] !== \"/\") data = \"/\" + data\n\t\treturn data\n\t}\n\tvar asyncId\n\tfunction debounceAsync(callback0) {\n\t\treturn function() {\n\t\t\tif (asyncId != null) return\n\t\t\tasyncId = callAsync0(function() {\n\t\t\t\tasyncId = null\n\t\t\t\tcallback0()\n\t\t\t})\n\t\t}\n\t}\n\tfunction parsePath(path, queryData, hashData) {\n\t\tvar queryIndex = path.indexOf(\"?\")\n\t\tvar hashIndex = path.indexOf(\"#\")\n\t\tvar pathEnd = queryIndex > -1 ? queryIndex : hashIndex > -1 ? hashIndex : path.length\n\t\tif (queryIndex > -1) {\n\t\t\tvar queryEnd = hashIndex > -1 ? hashIndex : path.length\n\t\t\tvar queryParams = parseQueryString(path.slice(queryIndex + 1, queryEnd))\n\t\t\tfor (var key4 in queryParams) queryData[key4] = queryParams[key4]\n\t\t}\n\t\tif (hashIndex > -1) {\n\t\t\tvar hashParams = parseQueryString(path.slice(hashIndex + 1))\n\t\t\tfor (var key4 in hashParams) hashData[key4] = hashParams[key4]\n\t\t}\n\t\treturn path.slice(0, pathEnd)\n\t}\n\tvar router = {prefix: \"#!\"}\n\trouter.getPath = function() {\n\t\tvar type2 = router.prefix.charAt(0)\n\t\tswitch (type2) {\n\t\t\tcase \"#\": return normalize1(\"hash\").slice(router.prefix.length)\n\t\t\tcase \"?\": return normalize1(\"search\").slice(router.prefix.length) + normalize1(\"hash\")\n\t\t\tdefault: return normalize1(\"pathname\").slice(router.prefix.length) + normalize1(\"search\") + normalize1(\"hash\")\n\t\t}\n\t}\n\trouter.setPath = function(path, data, options) {\n\t\tvar queryData = {}, hashData = {}\n\t\tpath = parsePath(path, queryData, hashData)\n\t\tif (data != null) {\n\t\t\tfor (var key4 in data) queryData[key4] = data[key4]\n\t\t\tpath = path.replace(/:([^\\/]+)/g, function(match2, token) {\n\t\t\t\tdelete queryData[token]\n\t\t\t\treturn data[token]\n\t\t\t})\n\t\t}\n\t\tvar query = buildQueryString(queryData)\n\t\tif (query) path += \"?\" + query\n\t\tvar hash = buildQueryString(hashData)\n\t\tif (hash) path += \"#\" + hash\n\t\tif (supportsPushState) {\n\t\t\tvar state = options ? options.state : null\n\t\t\tvar title = options ? options.title : null\n\t\t\t$window.onpopstate()\n\t\t\tif (options && options.replace) $window.history.replaceState(state, title, router.prefix + path)\n\t\t\telse $window.history.pushState(state, title, router.prefix + path)\n\t\t}\n\t\telse $window.location.href = router.prefix + path\n\t}\n\trouter.defineRoutes = function(routes, resolve, reject) {\n\t\tfunction resolveRoute() {\n\t\t\tvar path = router.getPath()\n\t\t\tvar params = {}\n\t\t\tvar pathname = parsePath(path, params, params)\n\t\t\tvar state = $window.history.state\n\t\t\tif (state != null) {\n\t\t\t\tfor (var k in state) params[k] = state[k]\n\t\t\t}\n\t\t\tfor (var route0 in routes) {\n\t\t\t\tvar matcher = new RegExp(\"^\" + route0.replace(/:[^\\/]+?\\.{3}/g, \"(.*?)\").replace(/:[^\\/]+/g, \"([^\\\\/]+)\") + \"\\/?$\")\n\t\t\t\tif (matcher.test(pathname)) {\n\t\t\t\t\tpathname.replace(matcher, function() {\n\t\t\t\t\t\tvar keys = route0.match(/:[^\\/]+/g) || []\n\t\t\t\t\t\tvar values = [].slice.call(arguments, 1, -2)\n\t\t\t\t\t\tfor (var i = 0; i < keys.length; i++) {\n\t\t\t\t\t\t\tparams[keys[i].replace(/:|\\./g, \"\")] = decodeURIComponent(values[i])\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve(routes[route0], params, path, route0)\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\treject(path, params)\n\t\t}\n\t\tif (supportsPushState) $window.onpopstate = debounceAsync(resolveRoute)\n\t\telse if (router.prefix.charAt(0) === \"#\") $window.onhashchange = resolveRoute\n\t\tresolveRoute()\n\t}\n\treturn router\n}\nvar _20 = function($window, redrawService0) {\n\tvar routeService = coreRouter($window)\n\tvar identity = function(v) {return v}\n\tvar render1, component, attrs3, currentPath, lastUpdate\n\tvar route = function(root, defaultRoute, routes) {\n\t\tif (root == null) throw new Error(\"Ensure the DOM element that was passed to `m.route` is not undefined\")\n\t\tvar run1 = function() {\n\t\t\tif (render1 != null) redrawService0.render(root, render1(Vnode(component, attrs3.key, attrs3)))\n\t\t}\n\t\tvar bail = function(path) {\n\t\t\tif (path !== defaultRoute) routeService.setPath(defaultRoute, null, {replace: true})\n\t\t\telse throw new Error(\"Could not resolve default route \" + defaultRoute)\n\t\t}\n\t\trouteService.defineRoutes(routes, function(payload, params, path) {\n\t\t\tvar update = lastUpdate = function(routeResolver, comp) {\n\t\t\t\tif (update !== lastUpdate) return\n\t\t\t\tcomponent = comp != null && (typeof comp.view === \"function\" || typeof comp === \"function\")? comp : \"div\"\n\t\t\t\tattrs3 = params, currentPath = path, lastUpdate = null\n\t\t\t\trender1 = (routeResolver.render || identity).bind(routeResolver)\n\t\t\t\trun1()\n\t\t\t}\n\t\t\tif (payload.view || typeof payload === \"function\") update({}, payload)\n\t\t\telse {\n\t\t\t\tif (payload.onmatch) {\n\t\t\t\t\tPromise.resolve(payload.onmatch(params, path)).then(function(resolved) {\n\t\t\t\t\t\tupdate(payload, resolved)\n\t\t\t\t\t}, bail)\n\t\t\t\t}\n\t\t\t\telse update(payload, \"div\")\n\t\t\t}\n\t\t}, bail)\n\t\tredrawService0.subscribe(root, run1)\n\t}\n\troute.set = function(path, data, options) {\n\t\tif (lastUpdate != null) {\n\t\t\toptions = options || {}\n\t\t\toptions.replace = true\n\t\t}\n\t\tlastUpdate = null\n\t\trouteService.setPath(path, data, options)\n\t}\n\troute.get = function() {return currentPath}\n\troute.prefix = function(prefix0) {routeService.prefix = prefix0}\n\troute.link = function(vnode1) {\n\t\tvnode1.dom.setAttribute(\"href\", routeService.prefix + vnode1.attrs.href)\n\t\tvnode1.dom.onclick = function(e) {\n\t\t\tif (e.ctrlKey || e.metaKey || e.shiftKey || e.which === 2) return\n\t\t\te.preventDefault()\n\t\t\te.redraw = false\n\t\t\tvar href = this.getAttribute(\"href\")\n\t\t\tif (href.indexOf(routeService.prefix) === 0) href = href.slice(routeService.prefix.length)\n\t\t\troute.set(href, undefined, undefined)\n\t\t}\n\t}\n\troute.param = function(key3) {\n\t\tif(typeof attrs3 !== \"undefined\" && typeof key3 !== \"undefined\") return attrs3[key3]\n\t\treturn attrs3\n\t}\n\treturn route\n}\nm.route = _20(window, redrawService)\nm.withAttr = function(attrName, callback1, context) {\n\treturn function(e) {\n\t\tcallback1.call(context || this, attrName in e.currentTarget ? e.currentTarget[attrName] : e.currentTarget.getAttribute(attrName))\n\t}\n}\nvar _28 = coreRenderer(window)\nm.render = _28.render\nm.redraw = redrawService.redraw\nm.request = requestService.request\nm.jsonp = requestService.jsonp\nm.parseQueryString = parseQueryString\nm.buildQueryString = buildQueryString\nm.version = \"1.1.6\"\nm.vnode = Vnode\nif (typeof module !== \"undefined\") module[\"exports\"] = m\nelse window.m = m\n}());\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {},require(\"timers\").setImmediate)\n},{\"timers\":10}],9:[function(require,module,exports){\n// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n},{}],10:[function(require,module,exports){\n(function (setImmediate,clearImmediate){\nvar nextTick = require('process/browser.js').nextTick;\nvar apply = Function.prototype.apply;\nvar slice = Array.prototype.slice;\nvar immediateIds = {};\nvar nextImmediateId = 0;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, window, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) { timeout.close(); };\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(window, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// That's not how node.js implements it but the exposed api is the same.\nexports.setImmediate = typeof setImmediate === \"function\" ? setImmediate : function(fn) {\n var id = nextImmediateId++;\n var args = arguments.length < 2 ? false : slice.call(arguments, 1);\n\n immediateIds[id] = true;\n\n nextTick(function onNextTick() {\n if (immediateIds[id]) {\n // fn.call() is faster so we optimize for the common use-case\n // @see http://jsperf.com/call-apply-segu\n if (args) {\n fn.apply(null, args);\n } else {\n fn.call(null);\n }\n // Prevent ids from leaking\n exports.clearImmediate(id);\n }\n });\n\n return id;\n};\n\nexports.clearImmediate = typeof clearImmediate === \"function\" ? clearImmediate : function(id) {\n delete immediateIds[id];\n};\n}).call(this,require(\"timers\").setImmediate,require(\"timers\").clearImmediate)\n},{\"process/browser.js\":9,\"timers\":10}],11:[function(require,module,exports){\nfunction tlite(getTooltipOpts) {\n document.addEventListener('mouseover', function (e) {\n var el = e.target;\n var opts = getTooltipOpts(el);\n\n if (!opts) {\n el = el.parentElement;\n opts = el && getTooltipOpts(el);\n }\n\n opts && tlite.show(el, opts, true);\n });\n}\n\ntlite.show = function (el, opts, isAuto) {\n var fallbackAttrib = 'data-tlite';\n opts = opts || {};\n\n (el.tooltip || Tooltip(el, opts)).show();\n\n function Tooltip(el, opts) {\n var tooltipEl;\n var showTimer;\n var text;\n\n el.addEventListener('mousedown', autoHide);\n el.addEventListener('mouseleave', autoHide);\n\n function show() {\n text = el.title || el.getAttribute(fallbackAttrib) || text;\n el.title = '';\n el.setAttribute(fallbackAttrib, '');\n text && !showTimer && (showTimer = setTimeout(fadeIn, isAuto ? 150 : 1))\n }\n\n function autoHide() {\n tlite.hide(el, true);\n }\n\n function hide(isAutoHiding) {\n if (isAuto === isAutoHiding) {\n showTimer = clearTimeout(showTimer);\n var parent = tooltipEl && tooltipEl.parentNode;\n parent && parent.removeChild(tooltipEl);\n tooltipEl = undefined;\n }\n }\n\n function fadeIn() {\n if (!tooltipEl) {\n tooltipEl = createTooltip(el, text, opts);\n }\n }\n\n return el.tooltip = {\n show: show,\n hide: hide\n };\n }\n\n function createTooltip(el, text, opts) {\n var tooltipEl = document.createElement('span');\n var grav = opts.grav || el.getAttribute('data-tlite') || 'n';\n\n tooltipEl.innerHTML = text;\n\n el.appendChild(tooltipEl);\n\n var vertGrav = grav[0] || '';\n var horzGrav = grav[1] || '';\n\n function positionTooltip() {\n tooltipEl.className = 'tlite ' + 'tlite-' + vertGrav + horzGrav;\n\n var arrowSize = 10;\n var top = el.offsetTop;\n var left = el.offsetLeft;\n\n if (tooltipEl.offsetParent === el) {\n top = left = 0;\n }\n\n var width = el.offsetWidth;\n var height = el.offsetHeight;\n var tooltipHeight = tooltipEl.offsetHeight;\n var tooltipWidth = tooltipEl.offsetWidth;\n var centerEl = left + (width / 2);\n\n tooltipEl.style.top = (\n vertGrav === 's' ? (top - tooltipHeight - arrowSize) :\n vertGrav === 'n' ? (top + height + arrowSize) :\n (top + (height / 2) - (tooltipHeight / 2))\n ) + 'px';\n\n tooltipEl.style.left = (\n horzGrav === 'w' ? left :\n horzGrav === 'e' ? left + width - tooltipWidth :\n vertGrav === 'w' ? (left + width + arrowSize) :\n vertGrav === 'e' ? (left - tooltipWidth - arrowSize) :\n (centerEl - tooltipWidth / 2)\n ) + 'px';\n }\n\n positionTooltip();\n\n var rect = tooltipEl.getBoundingClientRect();\n\n if (vertGrav === 's' && rect.top < 0) {\n vertGrav = 'n';\n positionTooltip();\n } else if (vertGrav === 'n' && rect.bottom > window.innerHeight) {\n vertGrav = 's';\n positionTooltip();\n } else if (vertGrav === 'e' && rect.left < 0) {\n vertGrav = 'w';\n positionTooltip();\n } else if (vertGrav === 'w' && rect.right > window.innerWidth) {\n vertGrav = 'e';\n positionTooltip();\n }\n\n tooltipEl.className += ' tlite-visible';\n\n return tooltipEl;\n }\n};\n\ntlite.hide = function (el, isAuto) {\n el.tooltip && el.tooltip.hide(isAuto);\n};\n\nif (typeof module !== 'undefined' && module.exports) {\n module.exports = tlite;\n}\n\n},{}],12:[function(require,module,exports){\n/*!\n * EventEmitter v5.2.5 - git.io/ee\n * Unlicense - http://unlicense.org/\n * Oliver Caldwell - http://oli.me.uk/\n * @preserve\n */\n\n;(function (exports) {\n 'use strict';\n\n /**\n * Class for managing events.\n * Can be extended to provide event functionality in other classes.\n *\n * @class EventEmitter Manages event registering and emitting.\n */\n function EventEmitter() {}\n\n // Shortcuts to improve speed and size\n var proto = EventEmitter.prototype;\n var originalGlobalValue = exports.EventEmitter;\n\n /**\n * Finds the index of the listener for the event in its storage array.\n *\n * @param {Function[]} listeners Array of listeners to search through.\n * @param {Function} listener Method to look for.\n * @return {Number} Index of the specified listener, -1 if not found\n * @api private\n */\n function indexOfListener(listeners, listener) {\n var i = listeners.length;\n while (i--) {\n if (listeners[i].listener === listener) {\n return i;\n }\n }\n\n return -1;\n }\n\n /**\n * Alias a method while keeping the context correct, to allow for overwriting of target method.\n *\n * @param {String} name The name of the target method.\n * @return {Function} The aliased method\n * @api private\n */\n function alias(name) {\n return function aliasClosure() {\n return this[name].apply(this, arguments);\n };\n }\n\n /**\n * Returns the listener array for the specified event.\n * Will initialise the event object and listener arrays if required.\n * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.\n * Each property in the object response is an array of listener functions.\n *\n * @param {String|RegExp} evt Name of the event to return the listeners from.\n * @return {Function[]|Object} All listener functions for the event.\n */\n proto.getListeners = function getListeners(evt) {\n var events = this._getEvents();\n var response;\n var key;\n\n // Return a concatenated array of all matching events if\n // the selector is a regular expression.\n if (evt instanceof RegExp) {\n response = {};\n for (key in events) {\n if (events.hasOwnProperty(key) && evt.test(key)) {\n response[key] = events[key];\n }\n }\n }\n else {\n response = events[evt] || (events[evt] = []);\n }\n\n return response;\n };\n\n /**\n * Takes a list of listener objects and flattens it into a list of listener functions.\n *\n * @param {Object[]} listeners Raw listener objects.\n * @return {Function[]} Just the listener functions.\n */\n proto.flattenListeners = function flattenListeners(listeners) {\n var flatListeners = [];\n var i;\n\n for (i = 0; i < listeners.length; i += 1) {\n flatListeners.push(listeners[i].listener);\n }\n\n return flatListeners;\n };\n\n /**\n * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.\n *\n * @param {String|RegExp} evt Name of the event to return the listeners from.\n * @return {Object} All listener functions for an event in an object.\n */\n proto.getListenersAsObject = function getListenersAsObject(evt) {\n var listeners = this.getListeners(evt);\n var response;\n\n if (listeners instanceof Array) {\n response = {};\n response[evt] = listeners;\n }\n\n return response || listeners;\n };\n\n function isValidListener (listener) {\n if (typeof listener === 'function' || listener instanceof RegExp) {\n return true\n } else if (listener && typeof listener === 'object') {\n return isValidListener(listener.listener)\n } else {\n return false\n }\n }\n\n /**\n * Adds a listener function to the specified event.\n * The listener will not be added if it is a duplicate.\n * If the listener returns true then it will be removed after it is called.\n * If you pass a regular expression as the event name then the listener will be added to all events that match it.\n *\n * @param {String|RegExp} evt Name of the event to attach the listener to.\n * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.addListener = function addListener(evt, listener) {\n if (!isValidListener(listener)) {\n throw new TypeError('listener must be a function');\n }\n\n var listeners = this.getListenersAsObject(evt);\n var listenerIsWrapped = typeof listener === 'object';\n var key;\n\n for (key in listeners) {\n if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {\n listeners[key].push(listenerIsWrapped ? listener : {\n listener: listener,\n once: false\n });\n }\n }\n\n return this;\n };\n\n /**\n * Alias of addListener\n */\n proto.on = alias('addListener');\n\n /**\n * Semi-alias of addListener. It will add a listener that will be\n * automatically removed after its first execution.\n *\n * @param {String|RegExp} evt Name of the event to attach the listener to.\n * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.addOnceListener = function addOnceListener(evt, listener) {\n return this.addListener(evt, {\n listener: listener,\n once: true\n });\n };\n\n /**\n * Alias of addOnceListener.\n */\n proto.once = alias('addOnceListener');\n\n /**\n * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.\n * You need to tell it what event names should be matched by a regex.\n *\n * @param {String} evt Name of the event to create.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.defineEvent = function defineEvent(evt) {\n this.getListeners(evt);\n return this;\n };\n\n /**\n * Uses defineEvent to define multiple events.\n *\n * @param {String[]} evts An array of event names to define.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.defineEvents = function defineEvents(evts) {\n for (var i = 0; i < evts.length; i += 1) {\n this.defineEvent(evts[i]);\n }\n return this;\n };\n\n /**\n * Removes a listener function from the specified event.\n * When passed a regular expression as the event name, it will remove the listener from all events that match it.\n *\n * @param {String|RegExp} evt Name of the event to remove the listener from.\n * @param {Function} listener Method to remove from the event.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.removeListener = function removeListener(evt, listener) {\n var listeners = this.getListenersAsObject(evt);\n var index;\n var key;\n\n for (key in listeners) {\n if (listeners.hasOwnProperty(key)) {\n index = indexOfListener(listeners[key], listener);\n\n if (index !== -1) {\n listeners[key].splice(index, 1);\n }\n }\n }\n\n return this;\n };\n\n /**\n * Alias of removeListener\n */\n proto.off = alias('removeListener');\n\n /**\n * Adds listeners in bulk using the manipulateListeners method.\n * If you pass an object as the first argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.\n * You can also pass it a regular expression to add the array of listeners to all events that match it.\n * Yeah, this function does quite a bit. That's probably a bad thing.\n *\n * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.\n * @param {Function[]} [listeners] An optional array of listener functions to add.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.addListeners = function addListeners(evt, listeners) {\n // Pass through to manipulateListeners\n return this.manipulateListeners(false, evt, listeners);\n };\n\n /**\n * Removes listeners in bulk using the manipulateListeners method.\n * If you pass an object as the first argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.\n * You can also pass it an event name and an array of listeners to be removed.\n * You can also pass it a regular expression to remove the listeners from all events that match it.\n *\n * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.\n * @param {Function[]} [listeners] An optional array of listener functions to remove.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.removeListeners = function removeListeners(evt, listeners) {\n // Pass through to manipulateListeners\n return this.manipulateListeners(true, evt, listeners);\n };\n\n /**\n * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.\n * The first argument will determine if the listeners are removed (true) or added (false).\n * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.\n * You can also pass it an event name and an array of listeners to be added/removed.\n * You can also pass it a regular expression to manipulate the listeners of all events that match it.\n *\n * @param {Boolean} remove True if you want to remove listeners, false if you want to add.\n * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.\n * @param {Function[]} [listeners] An optional array of listener functions to add/remove.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {\n var i;\n var value;\n var single = remove ? this.removeListener : this.addListener;\n var multiple = remove ? this.removeListeners : this.addListeners;\n\n // If evt is an object then pass each of its properties to this method\n if (typeof evt === 'object' && !(evt instanceof RegExp)) {\n for (i in evt) {\n if (evt.hasOwnProperty(i) && (value = evt[i])) {\n // Pass the single listener straight through to the singular method\n if (typeof value === 'function') {\n single.call(this, i, value);\n }\n else {\n // Otherwise pass back to the multiple function\n multiple.call(this, i, value);\n }\n }\n }\n }\n else {\n // So evt must be a string\n // And listeners must be an array of listeners\n // Loop over it and pass each one to the multiple method\n i = listeners.length;\n while (i--) {\n single.call(this, evt, listeners[i]);\n }\n }\n\n return this;\n };\n\n /**\n * Removes all listeners from a specified event.\n * If you do not specify an event then all listeners will be removed.\n * That means every event will be emptied.\n * You can also pass a regex to remove all events that match it.\n *\n * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.removeEvent = function removeEvent(evt) {\n var type = typeof evt;\n var events = this._getEvents();\n var key;\n\n // Remove different things depending on the state of evt\n if (type === 'string') {\n // Remove all listeners for the specified event\n delete events[evt];\n }\n else if (evt instanceof RegExp) {\n // Remove all events matching the regex.\n for (key in events) {\n if (events.hasOwnProperty(key) && evt.test(key)) {\n delete events[key];\n }\n }\n }\n else {\n // Remove all listeners in all events\n delete this._events;\n }\n\n return this;\n };\n\n /**\n * Alias of removeEvent.\n *\n * Added to mirror the node API.\n */\n proto.removeAllListeners = alias('removeEvent');\n\n /**\n * Emits an event of your choice.\n * When emitted, every listener attached to that event will be executed.\n * If you pass the optional argument array then those arguments will be passed to every listener upon execution.\n * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.\n * So they will not arrive within the array on the other side, they will be separate.\n * You can also pass a regular expression to emit to all events that match it.\n *\n * @param {String|RegExp} evt Name of the event to emit and execute listeners for.\n * @param {Array} [args] Optional array of arguments to be passed to each listener.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.emitEvent = function emitEvent(evt, args) {\n var listenersMap = this.getListenersAsObject(evt);\n var listeners;\n var listener;\n var i;\n var key;\n var response;\n\n for (key in listenersMap) {\n if (listenersMap.hasOwnProperty(key)) {\n listeners = listenersMap[key].slice(0);\n\n for (i = 0; i < listeners.length; i++) {\n // If the listener returns true then it shall be removed from the event\n // The function is executed either with a basic call or an apply if there is an args array\n listener = listeners[i];\n\n if (listener.once === true) {\n this.removeListener(evt, listener.listener);\n }\n\n response = listener.listener.apply(this, args || []);\n\n if (response === this._getOnceReturnValue()) {\n this.removeListener(evt, listener.listener);\n }\n }\n }\n }\n\n return this;\n };\n\n /**\n * Alias of emitEvent\n */\n proto.trigger = alias('emitEvent');\n\n /**\n * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.\n * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.\n *\n * @param {String|RegExp} evt Name of the event to emit and execute listeners for.\n * @param {...*} Optional additional arguments to be passed to each listener.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.emit = function emit(evt) {\n var args = Array.prototype.slice.call(arguments, 1);\n return this.emitEvent(evt, args);\n };\n\n /**\n * Sets the current value to check against when executing listeners. If a\n * listeners return value matches the one set here then it will be removed\n * after execution. This value defaults to true.\n *\n * @param {*} value The new value to check for when executing listeners.\n * @return {Object} Current instance of EventEmitter for chaining.\n */\n proto.setOnceReturnValue = function setOnceReturnValue(value) {\n this._onceReturnValue = value;\n return this;\n };\n\n /**\n * Fetches the current value to check against when executing listeners. If\n * the listeners return value matches this one then it should be removed\n * automatically. It will return true by default.\n *\n * @return {*|Boolean} The current value to check for or the default, true.\n * @api private\n */\n proto._getOnceReturnValue = function _getOnceReturnValue() {\n if (this.hasOwnProperty('_onceReturnValue')) {\n return this._onceReturnValue;\n }\n else {\n return true;\n }\n };\n\n /**\n * Fetches the events object and creates one if required.\n *\n * @return {Object} The events storage object.\n * @api private\n */\n proto._getEvents = function _getEvents() {\n return this._events || (this._events = {});\n };\n\n /**\n * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.\n *\n * @return {Function} Non conflicting EventEmitter class.\n */\n EventEmitter.noConflict = function noConflict() {\n exports.EventEmitter = originalGlobalValue;\n return EventEmitter;\n };\n\n // Expose the class either via AMD, CommonJS or the global object\n if (typeof define === 'function' && define.amd) {\n define(function () {\n return EventEmitter;\n });\n }\n else if (typeof module === 'object' && module.exports){\n module.exports = EventEmitter;\n }\n else {\n exports.EventEmitter = EventEmitter;\n }\n}(typeof window !== 'undefined' ? window : this || {}));\n\n},{}]},{},[1]);\n })();"]} \ No newline at end of file diff --git a/assets/js/forms-admin.js b/assets/js/forms-admin.js index 9fa0908..606182c 100755 --- a/assets/js/forms-admin.js +++ b/assets/js/forms-admin.js @@ -397,7 +397,7 @@ var FieldHelper = function FieldHelper(m, tabs, editor, fields, events, i18n) { var generate = require('./field-generator.js')(m); - var overlay = require('./overlay.js')(m, i18n); + var overlay = require('../overlay.js')(m, i18n); var forms = require('./field-forms.js')(m, i18n); @@ -518,7 +518,7 @@ var FieldHelper = function FieldHelper(m, tabs, editor, fields, events, i18n) { module.exports = FieldHelper; -},{"./field-forms.js":2,"./field-generator.js":3,"./overlay.js":10}],5:[function(require,module,exports){ +},{"../overlay.js":10,"./field-forms.js":2,"./field-generator.js":3}],5:[function(require,module,exports){ "use strict"; var FieldFactory = function FieldFactory(fields, i18n) { @@ -1347,15 +1347,15 @@ var settings = nl4wp.settings; var helpers = nl4wp.helpers; var tabs = nl4wp.tabs; -var FormWatcher = require('./admin/form-watcher.js'); +var FormWatcher = require('./admin/form-editor/form-watcher.js'); -var FormEditor = require('./admin/form-editor.js'); +var FormEditor = require('./admin/form-editor/form-editor.js'); -var FieldHelper = require('./admin/field-helper.js'); +var FieldHelper = require('./admin/form-editor/field-helper.js'); -var FieldsFactory = require('./admin/fields-factory.js'); +var FieldsFactory = require('./admin/form-editor/fields-factory.js'); -var fields = require('./admin/fields.js')(m, events); // vars +var fields = require('./admin/form-editor/fields.js')(m, events); // vars var editor = window.formEditor = FormEditor; @@ -1382,7 +1382,7 @@ window.nl4wp.forms = window.nl4wp.forms || {}; window.nl4wp.forms.editor = editor; window.nl4wp.forms.fields = fields; -},{"./admin/field-helper.js":4,"./admin/fields-factory.js":5,"./admin/fields.js":6,"./admin/form-editor.js":7,"./admin/form-watcher.js":8,"./admin/notices":9}],12:[function(require,module,exports){ +},{"./admin/form-editor/field-helper.js":4,"./admin/form-editor/fields-factory.js":5,"./admin/form-editor/fields.js":6,"./admin/form-editor/form-editor.js":7,"./admin/form-editor/form-watcher.js":8,"./admin/notices":9}],12:[function(require,module,exports){ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE diff --git a/assets/js/forms-admin.min.js b/assets/js/forms-admin.min.js index 46450d2..502e073 100755 --- a/assets/js/forms-admin.min.js +++ b/assets/js/forms-admin.min.js @@ -1,2 +1,2 @@ -!function(){var o=void 0;!function o(a,l,s){function c(t,e){if(!l[t]){if(!a[t]){var r=!1;if(!e&&r)return r(t,!0);if(u)return u(t,!0);var n=new Error("Cannot find module '"+t+"'");throw n.code="MODULE_NOT_FOUND",n}var i=l[t]={exports:{}};a[t][0].call(i.exports,function(e){return c(a[t][1][e]||e)},i,i.exports,o,a,l,s)}return l[t].exports}for(var u=!1,e=0;e";var r=document.querySelector(".nl4wp-notices");if(!r){(r=document.createElement("div")).className="nl4wp-notices";var n=document.querySelector("h1, h2");n.parentNode.insertBefore(r,n.nextSibling)}r.innerHTML=e}t.exports={init:function(r,n){var e=function(){-1GROUPINGS fields.

Please remove these fields from your form and then re-add them through the available field buttons to make sure your data is getting through to Newsletter correctly."):a("deprecated_groupings")},t=function(){var e=n.getAllWhere("forceRequired",!0).filter(function(e){return!r.containsField(e.name().toUpperCase())}),t="Heads up! Your form is missing list fields that are required in Newsletter. Either add these fields to your form or mark them as optional in Newsletter.";t+='
  • '+e.map(function(e){return e.title()}).join("
  • ")+"
",0'"]=function(e){return function(e){if(e.getOption("disableInput"))return y.Pass;for(var t=e.listSelections(),r=[],n=e.getOption("autoCloseTags"),i=0;io.ch&&(f=f.slice(0,f.length-a.end+o.ch));var h=f.toLowerCase();if(!f||"string"==a.type&&(a.end!=o.ch||!/[\"\']/.test(a.string.charAt(a.string.length-1))||1==a.string.length)||"tag"==a.type&&"closeTag"==s.type||a.string.indexOf("/")==a.string.length-1||u&&-1"+(p?"\n\n":"")+"",newPos:p?y.Pos(o.line+1,0):y.Pos(o.line,o.ch+1)}}for(var m="object"==typeof n&&n.dontIndentOnAutoClose,i=t.length-1;0<=i;i--){var g=r[i];e.replaceRange(g.text,t[i].head,t[i].anchor,"+insert");var v=e.listSelections().slice(0);v[i]={head:g.newPos,anchor:g.newPos},e.setSelections(v),!m&&g.indent&&(e.indentLine(g.newPos.line,null,!0),e.indentLine(g.newPos.line+1,null,!0))}}(e)}),e.addKeyMap(n)}});var b=["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],w=["applet","blockquote","body","button","div","dl","fieldset","form","frameset","h1","h2","h3","h4","h5","h6","head","html","iframe","layer","legend","object","ol","p","select","table","ul"];function i(e,t){for(var r=e.listSelections(),n=[],i=t?"/":""!=e.getLine(c.line).charAt(u.end)&&(s+=">"),n[l]=s}if(e.replaceSelections(n),r=e.listSelections(),!a)for(l=0;l",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"};function d(e,t,r){var n=e.getLineHandle(t.line),i=t.ch-1,o=r&&r.afterCursor;null==o&&(o=/(^| )cm-fat-cursor($| )/.test(e.getWrapperElement().className));var a=!o&&0<=i&&g[n.text.charAt(i)]||g[n.text.charAt(++i)];if(!a)return null;var l=">"==a.charAt(1)?1:-1;if(r&&r.strict&&0o))for(u==t.line&&(f=t.ch-(r<0?1:0));f!=h;f+=r){var p=d.charAt(f);if(s.test(p)&&(void 0===n||e.getTokenTypeAt(m(u,f+1))==n))if(">"==g[p].charAt(1)==0=e.max))return e.ch=0,e.text=e.cm.getLine(++e.line),!0}function a(e){if(!(e.line<=e.min))return e.text=e.cm.getLine(--e.line),e.ch=e.text.length,!0}function d(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(o(e))continue;return}if(i(e,t+1)){var r=e.text.lastIndexOf("/",t),n=-1",e.ch-1):-1;if(-1==t){if(a(e))continue;return}if(i(e,t+1)){var r=e.text.lastIndexOf("/",t),n=-1")||-1!=n.text.indexOf("<")){var i=d(n),o=i&&s(n.line,n.ch),a=i&&f(n);if(i&&a&&!(0=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var r=e;!r.lines;)for(var n=0;;++n){var i=r.children[n],o=i.chunkSize();if(t=e.first&&to?ge(o,se(e,o).text.length):(n=se(e,(r=t).line).text.length,null==(i=r.ch)||n=t:o.to>t);(n||(n=[])).push(new Me(a,o.from,l?null:o.to))}}return n}(r,i,a),s=function(e,t,r){var n;if(e)for(var i=0;i=t:o.to>t)||o.from==t&&"bookmark"==a.type&&(!r||o.marker.insertLeft)){var l=null==o.from||(a.inclusiveLeft?o.from<=t:o.fromt)&&(!r||ze(r,o.marker)<0)&&(r=o.marker)}return r}function je(e,t,r,n,i){var o=se(e,t),a=Le&&o.markedSpans;if(a)for(var l=0;le.lastLine())return t;var r,n=se(e,t);if(!Ke(e,n))return t;for(;r=Ie(n);)n=r.find(1,!0).line;return fe(n)+1}function Ke(e,t){var r=Le&&t.markedSpans;if(r)for(var n=void 0,i=0;ir.maxLineLength&&(r.maxLineLength=t,r.maxLine=e)})}var Xe=null;function Ze(e,t,r){var n;Xe=null;for(var i=0;it)return i;o.to==t&&(o.from!=o.to&&"before"==r?n=i:Xe=i),o.from==t&&(o.from!=o.to&&"before"!=r?n=i:Xe=i)}return null!=n?n:Xe}var Je=function(){var P="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",H="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";var I=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,R=/[stwN]/,j=/[LRr]/,B=/[Lb1n]/,q=/[1n]/;function U(e,t,r){this.level=e,this.from=t,this.to=r}return function(e,t){var r="ltr"==t?"L":"R";if(0==e.length||"ltr"==t&&!I.test(e))return!1;for(var n,i=e.length,o=[],a=0;a=this.string.length},Ft.prototype.sol=function(){return this.pos==this.lineStart},Ft.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Ft.prototype.next=function(){if(this.post},Ft.prototype.eatSpace=function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},Ft.prototype.skipToEnd=function(){this.pos=this.string.length},Ft.prototype.skipTo=function(e){var t=this.string.indexOf(e,this.pos);if(-1e.options.maxHighlightLength&&_t(e.doc.mode,n.state),o=Pt(e,t,n);i&&(n.state=i),t.stateAfter=n.save(!i),t.styles=o.styles,o.classes?t.styleClasses=o.classes:t.styleClasses&&(t.styleClasses=null),r===e.doc.highlightFrontier&&(e.doc.modeFrontier=Math.max(e.doc.modeFrontier,++e.doc.highlightFrontier))}return t.styles}function It(r,n,e){var t=r.doc,i=r.display;if(!t.mode.startState)return new zt(t,!0,n);var o=function(e,t,r){for(var n,i,o=e.doc,a=r?-1:t-(e.doc.mode.innerMode?1e3:100),l=t;at.first&&se(t,o-1).stateAfter,l=a?zt.fromSaved(t,a,o):new zt(t,Dt(t.mode),o);return t.iter(o,n,function(e){Rt(r,e.text,l);var t=l.line;e.stateAfter=t==n-1||t%5==0||t>=i.viewFrom&&tt.start)return o}throw new Error("Mode "+e.name+" failed to advance stream.")}zt.prototype.lookAhead=function(e){var t=this.doc.getLine(this.line+e);return null!=t&&e>this.maxLookAhead&&(this.maxLookAhead=e),t},zt.prototype.baseToken=function(e){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=e;)this.baseTokenPos+=2;var t=this.baseTokens[this.baseTokenPos+1];return{type:t&&t.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-e}},zt.prototype.nextLine=function(){this.line++,0e.options.maxHighlightLength?(l=!1,a&&Rt(e,t,n,d.pos),d.pos=t.length,null):Kt(Bt(r,d,n.state,f),o),f){var h=f[0].name;h&&(s="m-"+(s?h+" "+s:h))}if(!l||u!=s){for(;cl&&c.from<=l);u++);if(c.to>=s)return d(e,t,r,n,i,o,a);d(e,t.slice(0,c.to-l),r,n,null,o,a),n=null,t=t.slice(c.to-l),l=c.to}}}function tr(e,t,r,n){var i=!n&&r.widgetNode;i&&e.map.push(e.pos,e.pos+t,i),!n&&e.cm.display.input.needsContentAttribute&&(i||(i=e.content.appendChild(document.createElement("span"))),i.setAttribute("cm-marker",r.id)),i&&(e.cm.display.input.setUneditable(i),e.content.appendChild(i)),e.pos+=t,e.trailingSpace=!1}function rr(e,t,r){var n=e.markedSpans,i=e.text,o=0;if(n)for(var a,l,s,c,u,d,f,h=i.length,p=0,m=1,g="",v=0;;){if(v==p){s=c=u=l="",d=f=null,v=1/0;for(var y=[],b=void 0,w=0;wp||k.collapsed&&x.to==p&&x.from==p)){if(null!=x.to&&x.to!=p&&v>x.to&&(v=x.to,c=""),k.className&&(s+=" "+k.className),k.css&&(l=(l?l+";":"")+k.css),k.startStyle&&x.from==p&&(u+=" "+k.startStyle),k.endStyle&&x.to==v&&(b||(b=[])).push(k.endStyle,x.to),k.title&&((f||(f={})).title=k.title),k.attributes)for(var C in k.attributes)(f||(f={}))[C]=k.attributes[C];k.collapsed&&(!d||ze(d.marker,k)<0)&&(d=x)}else x.from>p&&v>x.from&&(v=x.from)}if(b)for(var T=0;Tr)return{map:e.measure.maps[i],cache:e.measure.caches[i],before:!0}}function Ar(e,t,r,n){return _r(e,Nr(e,t),r,n)}function Or(e,t){if(t>=e.display.viewFrom&&t=r.lineN&&tt)&&(i=(o=s-l)-1,s<=t&&(a="right")),null!=i){if(n=e[c+2],l==s&&r==(n.insertLeft?"left":"right")&&(a=r),"left"==r&&0==i)for(;c&&e[c-2]==e[c-3]&&e[c-1].insertLeft;)n=e[2+(c-=3)],a="left";if("right"==r&&i==s-l)for(;c=o.text.length?(t=o.text.length,r="before"):t<=0&&(t=0,r="after"),!c)return s("before"==r?t-1:t,"before"==r);function u(e,t,r){return s(r?e-1:e,1==c[t].level!=r)}var d=Ze(c,t,r),f=Xe,h=u(t,d,"before"==r);return null!=f&&(h.other=u(t,f,"before"!=r)),h}function Vr(e,t){var r=0;t=Ce(e.doc,t),e.options.lineWrapping||(r=en(e.display)*t.ch);var n=se(e.doc,t.line),i=Ge(n)+xr(e.display);return{left:r,right:r,top:i,bottom:i+n.height}}function Gr(e,t,r,n,i){var o=ge(e,t,r);return o.xRel=i,n&&(o.outside=!0),o}function $r(e,t,r){var n=e.doc;if((r+=e.display.viewOffset)<0)return Gr(n.first,0,null,!0,-1);var i=he(n,r),o=n.first+n.size-1;if(on},o,i)}}function Xr(e,t,r,n){return r||(r=Nr(e,t)),Yr(e,t,r,Br(e,t,_r(e,r,n),"line").top)}function Zr(e,t,r,n){return!(e.bottom<=r)&&(e.top>r||(n?e.left:e.right)>t)}function Jr(r,e,t,n,i){i-=Ge(e);var o=Nr(r,e),a=jr(e),l=0,s=e.text.length,c=!0,u=Qe(e,r.doc.direction);if(u){var d=(r.options.lineWrapping?function(e,t,r,n,i,o,a){var l=Yr(e,t,n,a),s=l.begin,c=l.end;/\s/.test(t.text.charAt(c-1))&&c--;for(var u=null,d=null,f=0;f=c||h.to<=s)){var p=1!=h.level,m=_r(e,n,p?Math.min(c,h.to)-1:Math.max(s,h.from)).right,g=mc&&(u={from:u.from,to:c,level:u.level});return u}:function(n,i,o,a,l,s,c){var e=ae(function(e){var t=l[e],r=1!=t.level;return Zr(Kr(n,ge(o,r?t.to:t.from,r?"before":"after"),"line",i,a),s,c,!0)},0,l.length-1),t=l[e];if(0c&&(t=l[e-1])}return t})(r,e,t,o,u,n,i);l=(c=1!=d.level)?d.from:d.to-1,s=c?d.to:d.from-1}var f,h,p=null,m=null,g=ae(function(e){var t=_r(r,o,e);return t.top+=a,t.bottom+=a,!!Zr(t,n,i,!1)&&(t.top<=i&&t.left<=n&&(p=e,m=t),!0)},l,s),v=!1;if(m){var y=n-m.left=w.bottom}return Gr(t,g=oe(e.text,g,1),h,v,n-f)}function Qr(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==Er){Er=N("pre");for(var t=0;t<49;++t)Er.appendChild(document.createTextNode("x")),Er.appendChild(N("br"));Er.appendChild(document.createTextNode("x"))}A(e.measure,Er);var r=Er.offsetHeight/50;return 3=e.display.viewTo)return null;if((t-=e.display.viewFrom)<0)return null;for(var r=e.display.view,n=0;n=e.display.viewTo||l.to().linet||t==r&&a.to==t)&&(n(Math.max(a.from,t),Math.min(a.to,r),1==a.level?"rtl":"ltr",o),i=!0)}i||n(t,r,"ltr")}(S,y||0,null==b?k:b,function(e,t,r,n){var i="ltr"==r,o=C(e,i?"left":"right"),a=C(t-1,i?"right":"left"),l=null==y&&0==e,s=null==b&&t==k,c=0==n,u=!S||n==S.length-1;if(a.top-o.top<=3){var d=(A?s:l)&&u,f=(A?l:s)&&c?L:(i?o:a).left,h=d?M:(i?a:o).right;O(f,o.top,h-f,o.bottom)}else{var p,m,g,v;v=i?(p=A&&l&&c?L:o.left,m=A?M:T(e,r,"before"),g=A?L:T(t,r,"after"),A&&s&&u?M:a.right):(p=A?T(e,r,"before"):L,m=!A&&l&&c?M:o.right,g=!A&&s&&u?L:a.left,A?T(t,r,"after"):M),O(p,o.top,m-p,o.bottom),o.bottome.display.sizerWidth){var f=Math.ceil(l/en(e.display));f>e.display.maxLineLength&&(e.display.maxLineLength=f,e.display.maxLine=i.line,e.display.maxLineChanged=!0)}}}}function bn(e){if(e.widgets)for(var t=0;t=a&&(o=he(t,Ge(se(t,s))-e.wrapper.clientHeight),a=s)}return{from:o,to:Math.max(a,o+1)}}function xn(e){var t=e.display,r=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var n=rn(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=n+"px",a=0;ao&&(t.bottom=t.top+o);var l=e.doc.height+kr(r),s=t.topl-n;if(t.topi+o){var u=Math.min(t.top,(c?l:t.bottom)-o);u!=i&&(a.scrollTop=u)}var d=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:r.scroller.scrollLeft,f=Sr(e)-(e.options.fixedGutter?r.gutters.offsetWidth:0),h=t.right-t.left>f;return h&&(t.right=t.left+f),t.left<10?a.scrollLeft=0:t.leftf+d-3&&(a.scrollLeft=t.right+(h?0:10)-f),a}function Tn(e,t){null!=t&&(Mn(e),e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+t)}function Sn(e){Mn(e);var t=e.getCursor();e.curOp.scrollToPos={from:t,to:t,margin:e.options.cursorScrollMargin}}function Ln(e,t,r){null==t&&null==r||Mn(e),null!=t&&(e.curOp.scrollLeft=t),null!=r&&(e.curOp.scrollTop=r)}function Mn(e){var t=e.curOp.scrollToPos;t&&(e.curOp.scrollToPos=null,An(e,Vr(e,t.from),Vr(e,t.to),t.margin))}function An(e,t,r,n){var i=Cn(e,{left:Math.min(t.left,r.left),top:Math.min(t.top,r.top)-n,right:Math.max(t.right,r.right),bottom:Math.max(t.bottom,r.bottom)+n});Ln(e,i.scrollLeft,i.scrollTop)}function On(e,t){Math.abs(e.doc.scrollTop-t)<2||(m||ai(e,{top:t}),Nn(e,t,!0),m&&ai(e),ti(e,100))}function Nn(e,t,r){t=Math.min(e.display.scroller.scrollHeight-e.display.scroller.clientHeight,t),(e.display.scroller.scrollTop!=t||r)&&(e.doc.scrollTop=t,e.display.scrollbars.setScrollTop(t),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t))}function _n(e,t,r,n){t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth),(r?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)&&!n||(e.doc.scrollLeft=t,xn(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbars.setScrollLeft(t))}function En(e){var t=e.display,r=t.gutters.offsetWidth,n=Math.round(e.doc.height+kr(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?r:0,docHeight:n,scrollHeight:n+Tr(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:r}}var Dn=function(e,t,r){this.cm=r;var n=this.vert=N("div",[N("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i=this.horiz=N("div",[N("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");n.tabIndex=i.tabIndex=-1,e(n),e(i),tt(n,"scroll",function(){n.clientHeight&&t(n.scrollTop,"vertical")}),tt(i,"scroll",function(){i.clientWidth&&t(i.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,x&&k<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};Dn.prototype.update=function(e){var t=e.scrollWidth>e.clientWidth+1,r=e.scrollHeight>e.clientHeight+1,n=e.nativeBarWidth;if(r){this.vert.style.display="block",this.vert.style.bottom=t?n+"px":"0";var i=e.viewHeight-(t?n:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+i)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(t){this.horiz.style.display="block",this.horiz.style.right=r?n+"px":"0",this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(r?n:0);this.horiz.firstChild.style.width=Math.max(0,e.scrollWidth-e.clientWidth+o)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&0=i.viewTo)||i.maxLineChanged&&n.options.lineWrapping,e.update=e.mustUpdate&&new ni(n,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function qn(e){var t=e.cm,r=t.display;e.updatedDisplay&&yn(t),e.barMeasure=En(t),r.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=Ar(t,r.maxLine,r.maxLine.text.length).left+3,t.display.sizerWidth=e.adjustWidthTo,e.barMeasure.scrollWidth=Math.max(r.scroller.clientWidth,r.sizer.offsetLeft+e.adjustWidthTo+Tr(t)+t.display.barWidth),e.maxScrollLeft=Math.max(0,r.sizer.offsetLeft+e.adjustWidthTo-Sr(t))),(e.updatedDisplay||e.selectionChanged)&&(e.preparedSelection=r.input.prepareSelection())}function Un(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null!=i&&!c){var o=N("div","​",null,"position: absolute;\n top: "+(t.top-r.viewOffset-xr(e.display))+"px;\n height: "+(t.bottom-t.top+Tr(e)+r.barHeight)+"px;\n left: "+t.left+"px; width: "+Math.max(2,t.right-t.left)+"px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(i),e.display.lineSpace.removeChild(o)}}}(t,function(e,t,r,n){var i;null==n&&(n=0),e.options.lineWrapping||t!=r||(r="before"==(t=t.ch?ge(t.line,"before"==t.sticky?t.ch-1:t.ch,"after"):t).sticky?ge(t.line,t.ch+1,"before"):t);for(var o=0;o<5;o++){var a=!1,l=Kr(e,t),s=r&&r!=t?Kr(e,r):l,c=Cn(e,i={left:Math.min(l.left,s.left),top:Math.min(l.top,s.top)-n,right:Math.max(l.left,s.left),bottom:Math.max(l.bottom,s.bottom)+n}),u=e.doc.scrollTop,d=e.doc.scrollLeft;if(null!=c.scrollTop&&(On(e,c.scrollTop),1t)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=i.viewTo)Le&&qe(e.doc,t)i.viewFrom?Jn(e):(i.viewFrom+=n,i.viewTo+=n);else if(t<=i.viewFrom&&r>=i.viewTo)Jn(e);else if(t<=i.viewFrom){var o=Qn(e,r,r+n,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=n):Jn(e)}else if(r>=i.viewTo){var a=Qn(e,t,t,-1);a?(i.view=i.view.slice(0,a.index),i.viewTo=a.lineN):Jn(e)}else{var l=Qn(e,t,t,-1),s=Qn(e,r,r+n,1);l&&s?(i.view=i.view.slice(0,l.index).concat(ir(e,l.lineN,s.lineN)).concat(i.view.slice(s.index)),i.viewTo+=n):Jn(e)}var c=i.externalMeasured;c&&(r=i.lineN&&t=n.viewTo)){var o=n.view[ln(e,t)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==R(a,r)&&a.push(r)}}}function Jn(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function Qn(e,t,r,n){var i,o=ln(e,t),a=e.display.view;if(!Le||r==e.doc.first+e.doc.size)return{index:o,lineN:r};for(var l=e.display.viewFrom,s=0;s=s.display.viewTo)){var u=+new Date+s.options.workTime,d=It(s,c.highlightFrontier),f=[];c.iter(d.line,Math.min(c.first+c.size,s.display.viewTo+500),function(e){if(d.line>=s.display.viewFrom){var t=e.styles,r=e.text.length>s.options.maxHighlightLength?_t(c.mode,d.state):null,n=Pt(s,e,d,!0);r&&(d.state=r),e.styles=n.styles;var i=e.styleClasses,o=n.classes;o?e.styleClasses=o:i&&(e.styleClasses=null);for(var a=!t||t.length!=e.styles.length||i!=o&&(!i||!o||i.bgClass!=o.bgClass||i.textClass!=o.textClass),l=0;!a&&lu)return ti(s,s.options.workDelay),!0}),c.highlightFrontier=d.line,c.modeFrontier=Math.max(c.modeFrontier,d.line),f.length&&Vn(s,function(){for(var e=0;e=r.viewFrom&&t.visible.to<=r.viewTo&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo)&&r.renderedView==r.view&&0==ei(e))return!1;kn(e)&&(Jn(e),t.dims=tn(e));var i=n.first+n.size,o=Math.max(t.visible.from-e.options.viewportMargin,n.first),a=Math.min(i,t.visible.to+e.options.viewportMargin);r.viewFroma&&r.viewTo-a<20&&(a=Math.min(i,r.viewTo)),Le&&(o=qe(e.doc,o),a=Ue(e.doc,a));var l,s,c,u,d=o!=r.viewFrom||a!=r.viewTo||r.lastWrapHeight!=t.wrapperHeight||r.lastWrapWidth!=t.wrapperWidth;s=o,c=a,0==(u=(l=e).display).view.length||s>=u.viewTo||c<=u.viewFrom?(u.view=ir(l,s,c),u.viewFrom=s):(u.viewFrom>s?u.view=ir(l,s,u.viewFrom).concat(u.view):u.viewFromc&&(u.view=u.view.slice(0,ln(l,c)))),u.viewTo=c,r.viewOffset=Ge(se(e.doc,r.viewFrom)),e.display.mover.style.top=r.viewOffset+"px";var f=ei(e);if(!d&&0==f&&!t.force&&r.renderedView==r.view&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo))return!1;var h=function(e){if(e.hasFocus())return null;var t=E();if(!t||!_(e.display.lineDiv,t))return null;var r={activeElt:t};if(window.getSelection){var n=window.getSelection();n.anchorNode&&n.extend&&_(e.display.lineDiv,n.anchorNode)&&(r.anchorNode=n.anchorNode,r.anchorOffset=n.anchorOffset,r.focusNode=n.focusNode,r.focusOffset=n.focusOffset)}return r}(e);return 4=e.display.viewFrom&&t.visible.to<=e.display.viewTo)))&&ii(e,t);n=!1){yn(e);var i=En(e);sn(e),Wn(e,i),si(e,i),t.force=!1}t.signal(e,"update",e),e.display.viewFrom==e.display.reportedViewFrom&&e.display.viewTo==e.display.reportedViewTo||(t.signal(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo),e.display.reportedViewFrom=e.display.viewFrom,e.display.reportedViewTo=e.display.viewTo)}function ai(e,t){var r=new ni(e,t);if(ii(e,r)){yn(e),oi(e,r);var n=En(e);sn(e),Wn(e,n),si(e,n),r.finish()}}function li(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function si(e,t){e.display.sizer.style.minHeight=t.docHeight+"px",e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=t.docHeight+e.display.barHeight+Tr(e)+"px"}function ci(e){var t=e.display.gutters,r=e.options.gutters;M(t);for(var n=0;na.clientWidth,s=a.scrollHeight>a.clientHeight;if(n&&l||i&&s){if(i&&w&&b)e:for(var c=t.target,u=o.view;c!=a;c=c.parentNode)for(var d=0;ds-(e.cm?e.cm.options.historyEventDelay:500)||"*"==t.origin.charAt(0)))&&(o=(l=i).lastOp==n?(Di(l.done),Y(l.done)):l.done.length&&!Y(l.done).ranges?Y(l.done):1i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(r),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=s,i.lastOp=i.lastSelOp=n,i.lastOrigin=i.lastSelOrigin=t.origin,a||it(e,"historyAdded")}function Wi(e,t,r,n){var i,o,a,l,s,c=e.history,u=n&&n.origin;r==c.lastSelOp||u&&c.lastSelOrigin==u&&(c.lastModTime==c.lastSelTime&&c.lastOrigin==u||(i=e,o=u,a=Y(c.done),l=t,"*"==(s=o.charAt(0))||"+"==s&&a.ranges.length==l.ranges.length&&a.somethingSelected()==l.somethingSelected()&&new Date-i.history.lastSelTime<=(i.cm?i.cm.options.historyEventDelay:500)))?c.done[c.done.length-1]=t:zi(t,c.done),c.lastSelTime=+new Date,c.lastSelOrigin=u,c.lastSelOp=r,n&&!1!==n.clearRedo&&Di(c.undone)}function zi(e,t){var r=Y(t);r&&r.ranges&&r.equals(e)||t.push(e)}function Pi(t,r,e,n){var i=r["spans_"+t.id],o=0;t.iter(Math.max(t.first,e),Math.min(t.first+t.size,n),function(e){e.markedSpans&&((i||(i=r["spans_"+t.id]={}))[o]=e.markedSpans),++o})}function Hi(e){if(!e)return null;for(var t,r=0;r=t.ch:l.to>t.ch))){if(i&&(it(s,"beforeCursorEnter"),s.explicitlyCleared)){if(o.markedSpans){--a;continue}break}if(!s.atomic)continue;if(r){var c=s.find(n<0?1:-1),u=void 0;if((n<0?s.inclusiveRight:s.inclusiveLeft)&&(c=eo(e,c,-n,c&&c.line==t.line?o:null)),c&&c.line==t.line&&(u=ve(c,r))&&(n<0?u<0:0e.first?Ce(e,ge(t.line-1)):null:0e.lastLine())){if(t.from.lineo&&(t={from:t.from,to:ge(o,se(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=ce(e,t.from,t.to),r||(r=ki(e,t)),e.cm?function(e,t,r){var n=e.doc,i=e.display,o=t.from,a=t.to,l=!1,s=o.line;e.options.lineWrapping||(s=fe(Be(se(n,o.line))),n.iter(s,a.line+1,function(e){if(e==i.maxLine)return l=!0}));-1i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,l=!1)}),l&&(e.curOp.updateMaxLine=!0));(function(e,t){if(e.modeFrontier=Math.min(e.modeFrontier,t),!(e.highlightFrontiert.display.maxLineLength&&(t.display.maxLine=u,t.display.maxLineLength=d,t.display.maxLineChanged=!0)}null!=i&&t&&this.collapsed&&Xn(t,i,o+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,t&&Xi(t.doc)),t&&lr(t,"markerCleared",t,this,i,o),r&&jn(t),this.parent&&this.parent.clear()}},bo.prototype.find=function(e,t){var r,n;null==e&&"bookmark"==this.type&&(e=1);for(var i=0;i=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(i,o,a){i=Ce(this,i),o=Ce(this,o);var l=[],s=i.line;return this.iter(i.line,o.line+1,function(e){var t=e.markedSpans;if(t)for(var r=0;r=n.to||null==n.from&&s!=i.line||null!=n.from&&s==o.line&&n.from>=o.ch||a&&!a(n.marker)||l.push(n.marker.parent||n.marker)}++s}),l},getAllMarks:function(){var n=[];return this.iter(function(e){var t=e.markedSpans;if(t)for(var r=0;rt&&(t=e.from),null!=e.to&&e.toe.text.length?null:n}function Go(e,t,r){var n=Vo(e,t.ch,r);return null==n?null:new ge(t.line,n,r<0?"after":"before")}function $o(e,t,r,n,i){if(e){var o=Qe(r,t.doc.direction);if(o){var a,l=i<0?Y(o):o[0],s=i<0==(1==l.level)?"after":"before";if(0a.doc.first){var o=se(a.doc,n.line-1).text;o&&(n=new ge(n.line,1),a.replaceRange(i.charAt(0)+a.doc.lineSeparator()+o.charAt(o.length-1),ge(n.line-1,o.length-1),n,"+transpose"))}t.push(new vi(n,n))}a.setSelections(t)})},newlineAndIndent:function(n){return Vn(n,function(){for(var e=n.listSelections(),t=e.length-1;0<=t;t--)n.replaceRange(n.doc.lineSeparator(),e[t].anchor,e[t].head,"+input");e=n.listSelections();for(var r=0;ru&&t.push(new vi(ge(l,u),ge(l,V(c,a,r))))}t.length||t.push(new vi(v,v)),Gi(b,yi(g,k.ranges.slice(0,x).concat(t),x),{origin:"*mouse",scroll:!1}),g.scrollIntoView(e)}else{var d,f=w,h=da(g,e,y.unit),p=f.anchor;p=0=i.to||n.lines.bottom?20:0;o&&setTimeout(Gn(g,function(){c==r&&(a.scroller.scrollTop+=o,e(t))}),50)}}(e):n(e)}),o=Gn(g,n);g.state.selectingText=o,tt(a.wrapper.ownerDocument,"mousemove",i),tt(a.wrapper.ownerDocument,"mouseup",o)}(e,n,t,o)}(t,a,s,e):ht(e)==r.scroller&&ct(e):2==l?(a&&Bi(t.doc,a),setTimeout(function(){return r.input.focus()},20)):3==l&&(C?t.display.input.onContextMenu(e):mn(t)))}}function da(e,t,r){if("char"==r)return new vi(t,t);if("word"==r)return e.findWordAt(t);if("line"==r)return new vi(ge(t.line,0),Ce(e.doc,ge(t.line+1,0)));var n=r(e,t);return new vi(n.from,n.to)}function fa(e,t,r,n){var i,o;if(t.touches)i=t.touches[0].clientX,o=t.touches[0].clientY;else try{i=t.clientX,o=t.clientY}catch(t){return!1}if(i>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;n&&ct(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(o>l.bottom||!lt(e,r))return dt(t);o-=l.top-a.viewOffset;for(var s=0;s=i)return it(e,r,e,he(e.doc,o),e.options.gutters[s],t),dt(t)}}function ha(e,t){return fa(e,t,"gutterClick",!0)}function pa(e,t){var r,n;wr(e.display,t)||(n=t,lt(r=e,"gutterContextMenu")&&fa(r,n,"gutterContextMenu",!1))||(ot(e,t,"contextmenu")||C||e.display.input.onContextMenu(t))}function ma(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),Hr(e)}ca.prototype.compare=function(e,t,r){return this.time+400>e&&0==ve(t,this.pos)&&r==this.button};var ga={toString:function(){return"CodeMirror.Init"}},va={},ya={};function ba(e){ci(e),Xn(e),xn(e)}function wa(e,t,r){if(!t!=!(r&&r!=ga)){var n=e.display.dragFunctions,i=t?tt:nt;i(e.display.scroller,"dragstart",n.start),i(e.display.scroller,"dragenter",n.enter),i(e.display.scroller,"dragover",n.over),i(e.display.scroller,"dragleave",n.leave),i(e.display.scroller,"drop",n.drop)}}function xa(e){e.options.lineWrapping?(D(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth="",e.display.sizerWidth=null):(L(e.display.wrapper,"CodeMirror-wrap"),Ye(e)),on(e),Xn(e),Hr(e),setTimeout(function(){return Wn(e)},100)}function ka(e,t){var r=this;if(!(this instanceof ka))return new ka(e,t);this.options=t=t?P(t):{},P(va,t,!1),ui(t);var n=t.value;"string"==typeof n?n=new So(n,t.mode,null,t.lineSeparator,t.direction):t.mode&&(n.modeOption=t.mode),this.doc=n;var i=new ka.inputStyles[t.inputStyle](this),o=this.display=new le(e,n,i);for(var a in ci(o.wrapper.CodeMirror=this),ma(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),Hn(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new I,keySeq:null,specialChars:null},t.autofocus&&!f&&o.input.focus(),x&&k<11&&setTimeout(function(){return r.display.input.reset(!0)},20),function(i){var o=i.display;tt(o.scroller,"mousedown",Gn(i,ua)),tt(o.scroller,"dblclick",x&&k<11?Gn(i,function(e){if(!ot(i,e)){var t=an(i,e);if(t&&!ha(i,e)&&!wr(i.display,e)){ct(e);var r=i.findWordAt(t);Bi(i.doc,r.anchor,r.head)}}}):function(e){return ot(i,e)||ct(e)});tt(o.scroller,"contextmenu",function(e){return pa(i,e)});var r,n={end:0};function a(){o.activeTouch&&(r=setTimeout(function(){return o.activeTouch=null},1e3),(n=o.activeTouch).end=+new Date)}function l(e,t){if(null==t.left)return!0;var r=t.left-e.left,n=t.top-e.top;return 400o.first?H(se(o,t-1).text,null,a):0:"add"==r?c=s+e.options.indentUnit:"subtract"==r?c=s-e.options.indentUnit:"number"==typeof r&&(c=s+r),c=Math.max(0,c);var d="",f=0;if(e.options.indentWithTabs)for(var h=Math.floor(c/a);h;--h)f+=a,d+="\t";if(f=r.text.length?(l.ch=r.text.length,l.sticky="before"):l.ch<=0&&(l.ch=0,l.sticky="after");var n=Ze(s,l.ch,l.sticky),i=s[n];if("ltr"==t.doc.direction&&i.level%2==0&&(0l.ch:i.from=i.from&&f>=u.begin)){var h=d?"before":"after";return new ge(l.line,f,h)}}var p=function(e,t,r){for(var n=function(e,t){return t?new ge(l.line,c(e,1),"before"):new ge(l.line,e,"after")};0<=e&&e=n.first+n.size||(i=new ge(r,i.ch,i.sticky),!(l=se(n,r))))return!1;i=$o(a,n.cm,l,i.line,o)}else i=t;return!0}if("char"==e)s();else if("column"==e)s(!0);else if("word"==e||"group"==e)for(var c=null,u="group"==e,d=n.cm&&n.cm.getHelper(i,"wordChars"),f=!0;!(o<0)||s(!f);f=!1){var h=l.text.charAt(i.ch)||"\n",p=te(h,d)?"w":u&&"\n"==h?"n":!u||/\s/.test(h)?null:"p";if(!u||f||p||(p="s"),c&&c!=p){o<0&&(o=1,s(),i.sticky="after");break}if(p&&(c=p),0=a.height){o.hitSide=!0;break}i+=5*r}return o}var Wa=function(e){this.cm=e,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new I,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};function za(e,t){var r=Or(e,t.line);if(!r||r.hidden)return null;var n=se(e.doc,t.line),i=Mr(r,n,t.line),o=Qe(n,e.doc.direction),a="left";o&&(a=Ze(o,t.ch)%2?"right":"left");var l=Fr(i.map,t.ch,a);return l.offset="right"==l.collapse?l.end:l.start,l}function Pa(e,t){return t&&(e.bad=!0),e}function Ha(e,t,r){var n;if(t==e.display.lineDiv){if(!(n=e.display.lineDiv.childNodes[r]))return Pa(e.clipPos(ge(e.display.viewTo-1)),!0);t=null,r=0}else for(n=t;;n=n.parentNode){if(!n||n==e.display.lineDiv)return null;if(n.parentNode&&n.parentNode==e.display.lineDiv)break}for(var i=0;i=t.display.viewTo||i.line=t.display.viewFrom&&za(t,n)||{node:l[0].measure.map[2],offset:0},c=i.linen.firstLine()&&(a=ge(a.line-1,se(n.doc,a.line-1).length)),l.ch==se(n.doc,l.line).text.length&&l.linei.viewTo-1)return!1;r=a.line==i.viewFrom||0==(e=ln(n,a.line))?(t=fe(i.view[0].line),i.view[0].node):(t=fe(i.view[e].line),i.view[e-1].node.nextSibling);var s,c,u=ln(n,l.line);if(c=u==i.view.length-1?(s=i.viewTo-1,i.lineDiv.lastChild):(s=fe(i.view[u+1].line)-1,i.view[u+1].node.previousSibling),!r)return!1;for(var d=n.doc.splitLines(function(s,e,t,c,u){var r="",d=!1,f=s.doc.lineSeparator(),h=!1;function p(){d&&(r+=f,h&&(r+=f),d=h=!1)}function m(e){e&&(p(),r+=e)}function g(e){if(1==e.nodeType){var t=e.getAttribute("cm-text");if(t)return void m(t);var r,n=e.getAttribute("cm-marker");if(n){var i=s.findMarks(ge(c,0),ge(u+1,0),(l=+n,function(e){return e.id==l}));return void(i.length&&(r=i[0].find(0))&&m(ce(s.doc,r.from,r.to).join(f)))}if("false"==e.getAttribute("contenteditable"))return;var o=/^(pre|div|p|li|table|br)$/i.test(e.nodeName);if(!/^br$/i.test(e.nodeName)&&0==e.textContent.length)return;o&&p();for(var a=0;aa.ch&&y.charCodeAt(y.length-p-1)==b.charCodeAt(b.length-p-1);)h--,p++;d[d.length-1]=y.slice(0,y.length-p).replace(/^\u200b+/,""),d[0]=d[0].slice(h).replace(/\u200b+$/,"");var x=ge(t,h),k=ge(s,f.length?Y(f).length-p:0);return 1r&&(Ta(this,i.head.line,e,!0),r=i.head.line,n==this.doc.sel.primIndex&&Sn(this));else{var o=i.from(),a=i.to(),l=Math.max(r,o.line);r=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var s=l;s>1;if((a?r[2*a-1]:0)>=o)i=a;else{if(!(r[2*a+1]d)&&e.top>t.offsetHeight?c=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=d&&(c=e.bottom),u+t.offsetWidth>f&&(u=f-t.offsetWidth)}t.style.top=c+"px",t.style.left=t.style.right="","right"==i?(u=s.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==i?u=0:"middle"==i&&(u=(s.sizer.clientWidth-t.offsetWidth)/2),t.style.left=u+"px"),r&&(o=this,a={left:u,top:c,right:u+t.offsetWidth,bottom:c+t.offsetHeight},null!=(l=Cn(o,a)).scrollTop&&On(o,l.scrollTop),null!=l.scrollLeft&&_n(o,l.scrollLeft))},triggerOnKeyDown:$n(ia),triggerOnKeyPress:$n(aa),triggerOnKeyUp:oa,triggerOnMouseDown:$n(ua),execCommand:function(e){if(Yo.hasOwnProperty(e))return Yo[e].call(null,this)},triggerElectric:$n(function(e){Oa(this,e)}),findPosH:function(e,t,r,n){var i=1;t<0&&(i=-1,t=-t);for(var o=Ce(this.doc,e),a=0;a*\/]/.test(r)?w(null,"select-op"):"."==r&&e.match(/^-?[_a-z][_a-z0-9-]*/i)?w("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(r)?w(null,r):("u"==r||"U"==r)&&e.match(/rl(-prefix)?\(/i)||("d"==r||"D"==r)&&e.match("omain(",!0,!0)||("r"==r||"R"==r)&&e.match("egexp(",!0,!0)?(e.backUp(1),t.tokenize=k,w("property","word")):/[\w\\\-]/.test(r)?(e.eatWhile(/[\w\\\-]/),w("property","word")):w(null,null):/[\d.]/.test(e.peek())?(e.eatWhile(/[\w.%]/),w("number","unit")):e.match(/^-[\w\\\-]+/)?(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?w("variable-2","variable-definition"):w("variable-2","variable")):e.match(/^\w+-/)?w("meta","meta"):void 0})(e,t);return r&&"object"==typeof r&&(n=r[1],r=r[0]),i=r,"comment"!=n&&(t.state=O[t.state](n,e,t)),i},indent:function(e,t){var r=e.context,n=t&&t.charAt(0),i=r.indent;return"prop"!=r.type||"}"!=n&&")"!=n||(r=r.prev),r.prev&&("}"!=n||"block"!=r.type&&"top"!=r.type&&"interpolation"!=r.type&&"restricted_atBlock"!=r.type?(")"!=n||"parens"!=r.type&&"atBlock_parens"!=r.type)&&("{"!=n||"at"!=r.type&&"atBlock"!=r.type)||(i=Math.max(0,r.indent-o)):i=(r=r.prev).indent),i},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:y,fold:"brace"}});var t=["domain","regexp","url","url-prefix"],r=e(t),n=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],i=e(n),o=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover"],a=e(o),l=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],s=e(l),c=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","justify-items","justify-self","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","mix-blend-mode","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","place-content","place-items","place-self","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","user-select","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],u=e(c),d=["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"],f=e(d),h=e(["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"]),p=e(["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"]),m=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],g=e(m),v=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","devanagari","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","graytext","grid","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hard-light","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","opacity","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unset","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],y=e(v),b=t.concat(n).concat(o).concat(l).concat(c).concat(d).concat(m).concat(v);function w(e,t){for(var r,n=!1;null!=(r=e.next());){if(n&&"/"==r){t.tokenize=null;break}n="*"==r}return["comment","comment"]}N.registerHelper("hintWords","css",b),N.defineMIME("text/css",{documentTypes:r,mediaTypes:i,mediaFeatures:a,mediaValueKeywords:s,propertyKeywords:u,nonStandardPropertyKeywords:f,fontProperties:h,counterDescriptors:p,colorKeywords:g,valueKeywords:y,tokenHooks:{"/":function(e,t){return!!e.eat("*")&&(t.tokenize=w)(e,t)}},name:"css"}),N.defineMIME("text/x-scss",{mediaTypes:i,mediaFeatures:a,mediaValueKeywords:s,propertyKeywords:u,nonStandardPropertyKeywords:f,colorKeywords:g,valueKeywords:y,fontProperties:h,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=w)(e,t):["operator","operator"]},":":function(e){return!!e.match(/\s*\{/,!1)&&[null,null]},$:function(e){return e.match(/^[\w-]+/),e.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(e){return!!e.eat("{")&&[null,"interpolation"]}},name:"css",helperType:"scss"}),N.defineMIME("text/x-less",{mediaTypes:i,mediaFeatures:a,mediaValueKeywords:s,propertyKeywords:u,nonStandardPropertyKeywords:f,colorKeywords:g,valueKeywords:y,fontProperties:h,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=w)(e,t):["operator","operator"]},"@":function(e){return e.eat("{")?[null,"interpolation"]:!e.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i,!1)&&(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"])},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"}),N.defineMIME("text/x-gss",{documentTypes:r,mediaTypes:i,mediaFeatures:a,propertyKeywords:u,nonStandardPropertyKeywords:f,fontProperties:h,counterDescriptors:p,colorKeywords:g,valueKeywords:y,supportsAtComponent:!0,tokenHooks:{"/":function(e,t){return!!e.eat("*")&&(t.tokenize=w)(e,t)}},name:"css",helperType:"gss"})},"object"==typeof r&&"object"==typeof t?n(e("../../lib/codemirror")):"function"==typeof o&&o.amd?o(["../../lib/codemirror"],n):n(CodeMirror)},{"../../lib/codemirror":17}],19:[function(e,t,r){var n;n=function(p){"use strict";var i={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]};var o={};function m(e,t){var r,n=e.match(o[r=t]||(o[r]=new RegExp("\\s+"+r+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")));return n?/^\s*(.*?)\s*$/.exec(n[2])[1]:""}function g(e,t){return new RegExp((t?"^":"")+"","i")}function a(e,t){for(var r in e)for(var n=t[r]||(t[r]=[]),i=e[r],o=i.length-1;0<=o;o--)n.unshift(i[o])}p.defineMode("htmlmixed",function(u,e){var d=p.getMode(u,{name:"xml",htmlMode:!0,multilineTagIndentFactor:e.multilineTagIndentFactor,multilineTagIndentPastTag:e.multilineTagIndentPastTag}),f={},t=e&&e.tags,r=e&&e.scriptTypes;if(a(i,f),t&&a(t,f),r)for(var n=r.length-1;0<=n;n--)f.script.unshift(["type",r[n].matches,r[n].mode]);function h(e,t){var r,n=d.token(e,t.htmlState),i=/\btag\b/.test(n);if(i&&!/[<>\s\/]/.test(e.current())&&(r=t.htmlState.tagName&&t.htmlState.tagName.toLowerCase())&&f.hasOwnProperty(r))t.inTag=r+" ";else if(t.inTag&&i&&/>$/.test(e.current())){var o=/^([\S]+) (.*)/.exec(t.inTag);t.inTag=null;var a=">"==e.current()&&function(e,t){for(var r=0;r!?|~^@]/,m=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;function g(e,t,r){return n=e,i=r,t}function v(e,t){var i,r=e.next();if('"'==r||"'"==r)return t.tokenize=(i=r,function(e,t){var r,n=!1;if(a&&"@"==e.peek()&&e.match(m))return t.tokenize=v,g("jsonld-keyword","meta");for(;null!=(r=e.next())&&(r!=i||n);)n=!n&&"\\"==r;return n||(t.tokenize=v),g("string","string")}),t.tokenize(e,t);if("."==r&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return g("number","number");if("."==r&&e.match(".."))return g("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(r))return g(r);if("="==r&&e.eat(">"))return g("=>","operator");if("0"==r&&e.match(/^(?:x[\da-f]+|o[0-7]+|b[01]+)n?/i))return g("number","number");if(/\d/.test(r))return e.match(/^\d*(?:n|(?:\.\d*)?(?:[eE][+\-]?\d+)?)?/),g("number","number");if("/"==r)return e.eat("*")?(t.tokenize=y)(e,t):e.eat("/")?(e.skipToEnd(),g("comment","comment")):Ve(e,t,1)?(function(e){for(var t,r=!1,n=!1;null!=(t=e.next());){if(!r){if("/"==t&&!n)return;"["==t?n=!0:n&&"]"==t&&(n=!1)}r=!r&&"\\"==t}}(e),e.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/),g("regexp","string-2")):(e.eat("="),g("operator","operator",e.current()));if("`"==r)return(t.tokenize=b)(e,t);if("#"==r)return e.skipToEnd(),g("error","error");if(p.test(r))return">"==r&&t.lexical&&">"==t.lexical.type||(e.eat("=")?"!"!=r&&"="!=r||e.eat("="):/[<>*+\-]/.test(r)&&(e.eat(r),">"==r&&e.eat(r))),g("operator","operator",e.current());if(u.test(r)){e.eatWhile(u);var n=e.current();if("."!=t.lastType){if(s.propertyIsEnumerable(n)){var o=s[n];return g(o.type,o.style,n)}if("async"==n&&e.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/,!1))return g("async","keyword",n)}return g("variable","variable",n)}}function y(e,t){for(var r,n=!1;r=e.next();){if("/"==r&&n){t.tokenize=v;break}n="*"==r}return g("comment","comment")}function b(e,t){for(var r,n=!1;null!=(r=e.next());){if(!n&&("`"==r||"$"==r&&e.eat("{"))){t.tokenize=v;break}n=!n&&"\\"==r}return g("quasi","string-2",e.current())}var w="([{}])";function o(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var r=e.string.indexOf("=>",e.start);if(!(r<0)){if(c){var n=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(e.string.slice(e.start,r));n&&(r=n.index)}for(var i=0,o=!1,a=r-1;0<=a;--a){var l=e.string.charAt(a),s=w.indexOf(l);if(0<=s&&s<3){if(!i){++a;break}if(0==--i){"("==l&&(o=!0);break}}else if(3<=s&&s<6)++i;else if(u.test(l))o=!0;else{if(/["'\/]/.test(l))return;if(o&&!i){++a;break}}}o&&!i&&(t.fatArrowAt=a)}}var x={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,"jsonld-keyword":!0};function k(e,t,r,n,i,o){this.indented=e,this.column=t,this.type=r,this.prev=i,this.info=o,null!=n&&(this.align=n)}function C(e,t){for(var r=e.localVars;r;r=r.next)if(r.name==t)return!0;for(var n=e.context;n;n=n.prev)for(r=n.vars;r;r=r.next)if(r.name==t)return!0}var T={state:null,column:null,marked:null,cc:null};function S(){for(var e=arguments.length-1;0<=e;e--)T.cc.push(arguments[e])}function L(){return S.apply(null,arguments),!0}function M(e,t){for(var r=t;r;r=r.next)if(r.name==e)return!0;return!1}function r(e){var t=T.state;if(T.marked="def",t.context)if("var"==t.lexical.info&&t.context&&t.context.block){var r=function e(t,r){{if(r){if(r.block){var n=e(t,r.prev);return n?n==r.prev?r:new O(n,r.vars,!0):null}return M(t,r.vars)?r:new O(r.prev,new N(t,r.vars),!1)}return null}}(e,t.context);if(null!=r)return void(t.context=r)}else if(!M(e,t.localVars))return void(t.localVars=new N(e,t.localVars));d.globalVars&&!M(e,t.globalVars)&&(t.globalVars=new N(e,t.globalVars))}function A(e){return"public"==e||"private"==e||"protected"==e||"abstract"==e||"readonly"==e}function O(e,t,r){this.prev=e,this.vars=t,this.block=r}function N(e,t){this.name=e,this.next=t}var t=new N("this",new N("arguments",null));function _(){T.state.context=new O(T.state.context,T.state.localVars,!1),T.state.localVars=t}function E(){T.state.context=new O(T.state.context,T.state.localVars,!0),T.state.localVars=null}function D(){T.state.localVars=T.state.context.vars,T.state.context=T.state.context.prev}function F(n,i){var e=function(){var e=T.state,t=e.indented;if("stat"==e.lexical.type)t=e.lexical.indented;else for(var r=e.lexical;r&&")"==r.type&&r.align;r=r.prev)t=r.indented;e.lexical=new k(t,T.stream.column(),n,null,e.lexical,i)};return e.lex=!0,e}function W(){var e=T.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function z(r){return function e(t){return t==r?L():";"==r||"}"==t||")"==t||"]"==t?S():L(e)}}function P(e,t){return"var"==e?L(F("vardef",t),ve,z(";"),W):"keyword a"==e?L(F("form"),j,P,W):"keyword b"==e?L(F("form"),P,W):"keyword d"==e?T.stream.match(/^\s*$/,!1)?L():L(F("stat"),q,z(";"),W):"debugger"==e?L(z(";")):"{"==e?L(F("}"),E,oe,W,D):";"==e?L():"if"==e?("else"==T.state.lexical.info&&T.state.cc[T.state.cc.length-1]==W&&T.state.cc.pop()(),L(F("form"),j,P,W,Ce)):"function"==e?L(Oe):"for"==e?L(F("form"),Te,P,W):"class"==e||c&&"interface"==t?(T.marked="keyword",L(F("form"),Ee,W)):"variable"==e?c&&"declare"==t?(T.marked="keyword",L(P)):c&&("module"==t||"enum"==t||"type"==t)&&T.stream.match(/^\s*\w/,!1)?(T.marked="keyword","enum"==t?L(Ue):"type"==t?L(ce,z("operator"),ce,z(";")):L(F("form"),ye,z("{"),F("}"),oe,W,W)):c&&"namespace"==t?(T.marked="keyword",L(F("form"),I,oe,W)):c&&"abstract"==t?(T.marked="keyword",L(P)):L(F("stat"),J):"switch"==e?L(F("form"),j,z("{"),F("}","switch"),E,oe,W,W,D):"case"==e?L(I,z(":")):"default"==e?L(z(":")):"catch"==e?L(F("form"),_,H,P,W,D):"export"==e?L(F("stat"),ze,W):"import"==e?L(F("stat"),He,W):"async"==e?L(P):"@"==t?L(I,P):S(F("stat"),I,z(";"),W)}function H(e){if("("==e)return L(Ne,z(")"))}function I(e,t){return B(e,t,!1)}function R(e,t){return B(e,t,!0)}function j(e){return"("!=e?S():L(F(")"),I,z(")"),W)}function B(e,t,r){if(T.state.fatArrowAt==T.stream.start){var n=r?Y:$;if("("==e)return L(_,F(")"),ne(Ne,")"),W,z("=>"),n,D);if("variable"==e)return S(_,ye,z("=>"),n,D)}var i,o=r?K:U;return x.hasOwnProperty(e)?L(o):"function"==e?L(Oe,o):"class"==e||c&&"interface"==t?(T.marked="keyword",L(F("form"),_e,W)):"keyword c"==e||"async"==e?L(r?R:I):"("==e?L(F(")"),q,z(")"),W,o):"operator"==e||"spread"==e?L(r?R:I):"["==e?L(F("]"),qe,W,o):"{"==e?ie(ee,"}",null,o):"quasi"==e?S(V,o):"new"==e?L((i=r,function(e){return"."==e?L(i?Z:X):"variable"==e&&c?L(pe,i?K:U):S(i?R:I)})):"import"==e?L(I):L()}function q(e){return e.match(/[;\}\)\],]/)?S():S(I)}function U(e,t){return","==e?L(I):K(e,t,!1)}function K(e,t,r){var n=0==r?U:K,i=0==r?I:R;return"=>"==e?L(_,r?Y:$,D):"operator"==e?/\+\+|--/.test(t)||c&&"!"==t?L(n):c&&"<"==t&&T.stream.match(/^([^>]|<.*?>)*>\s*\(/,!1)?L(F(">"),ne(ce,">"),W,n):"?"==t?L(I,z(":"),i):L(i):"quasi"==e?S(V,n):";"!=e?"("==e?ie(R,")","call",n):"."==e?L(Q,n):"["==e?L(F("]"),q,z("]"),W,n):c&&"as"==t?(T.marked="keyword",L(ce,n)):"regexp"==e?(T.state.lastType=T.marked="operator",T.stream.backUp(T.stream.pos-T.stream.start-1),L(i)):void 0:void 0}function V(e,t){return"quasi"!=e?S():"${"!=t.slice(t.length-2)?L(V):L(I,G)}function G(e){if("}"==e)return T.marked="string-2",T.state.tokenize=b,L(V)}function $(e){return o(T.stream,T.state),S("{"==e?P:I)}function Y(e){return o(T.stream,T.state),S("{"==e?P:R)}function X(e,t){if("target"==t)return T.marked="keyword",L(U)}function Z(e,t){if("target"==t)return T.marked="keyword",L(K)}function J(e){return":"==e?L(W,P):S(U,z(";"),W)}function Q(e){if("variable"==e)return T.marked="property",L()}function ee(e,t){if("async"==e)return T.marked="property",L(ee);if("variable"==e||"keyword"==T.style){return T.marked="property","get"==t||"set"==t?L(te):(c&&T.state.fatArrowAt==T.stream.start&&(r=T.stream.match(/^\s*:\s*/,!1))&&(T.state.fatArrowAt=T.stream.pos+r[0].length),L(re));var r}else{if("number"==e||"string"==e)return T.marked=a?"property":T.style+" property",L(re);if("jsonld-keyword"==e)return L(re);if(c&&A(t))return T.marked="keyword",L(ee);if("["==e)return L(I,ae,z("]"),re);if("spread"==e)return L(R,re);if("*"==t)return T.marked="keyword",L(ee);if(":"==e)return S(re)}}function te(e){return"variable"!=e?S(re):(T.marked="property",L(Oe))}function re(e){return":"==e?L(R):"("==e?S(Oe):void 0}function ne(n,i,o){function a(e,t){if(o?-1"),ce):void 0}function ue(e){if("=>"==e)return L(ce)}function de(e,t){return"variable"==e||"keyword"==T.style?(T.marked="property",L(de)):"?"==t?L(de):":"==e?L(ce):"["==e?L(I,ae,z("]"),de):void 0}function fe(e,t){return"variable"==e&&T.stream.match(/^\s*[?:]/,!1)||"?"==t?L(fe):":"==e?L(ce):S(ce)}function he(e,t){return"<"==t?L(F(">"),ne(ce,">"),W,he):"|"==t||"."==e||"&"==t?L(ce):"["==e?L(z("]"),he):"extends"==t||"implements"==t?(T.marked="keyword",L(ce)):void 0}function pe(e,t){if("<"==t)return L(F(">"),ne(ce,">"),W,he)}function me(){return S(ce,ge)}function ge(e,t){if("="==t)return L(ce)}function ve(e,t){return"enum"==t?(T.marked="keyword",L(Ue)):S(ye,ae,xe,ke)}function ye(e,t){return c&&A(t)?(T.marked="keyword",L(ye)):"variable"==e?(r(t),L()):"spread"==e?L(ye):"["==e?ie(we,"]"):"{"==e?ie(be,"}"):void 0}function be(e,t){return"variable"!=e||T.stream.match(/^\s*:/,!1)?("variable"==e&&(T.marked="property"),"spread"==e?L(ye):"}"==e?S():"["==e?L(I,z("]"),z(":"),be):L(z(":"),ye,xe)):(r(t),L(xe))}function we(){return S(ye,xe)}function xe(e,t){if("="==t)return L(R)}function ke(e){if(","==e)return L(ve)}function Ce(e,t){if("keyword b"==e&&"else"==t)return L(F("form","else"),P,W)}function Te(e,t){return"await"==t?L(Te):"("==e?L(F(")"),Se,z(")"),W):void 0}function Se(e){return"var"==e?L(ve,z(";"),Me):";"==e?L(Me):"variable"==e?L(Le):S(I,z(";"),Me)}function Le(e,t){return"in"==t||"of"==t?(T.marked="keyword",L(I)):L(U,Me)}function Me(e,t){return";"==e?L(Ae):"in"==t||"of"==t?(T.marked="keyword",L(I)):S(I,z(";"),Ae)}function Ae(e){")"!=e&&L(I)}function Oe(e,t){return"*"==t?(T.marked="keyword",L(Oe)):"variable"==e?(r(t),L(Oe)):"("==e?L(_,F(")"),ne(Ne,")"),W,le,P,D):c&&"<"==t?L(F(">"),ne(me,">"),W,Oe):void 0}function Ne(e,t){return"@"==t&&L(I,Ne),"spread"==e?L(Ne):c&&A(t)?(T.marked="keyword",L(Ne)):S(ye,ae,xe)}function _e(e,t){return"variable"==e?Ee(e,t):De(e,t)}function Ee(e,t){if("variable"==e)return r(t),L(De)}function De(e,t){return"<"==t?L(F(">"),ne(me,">"),W,De):"extends"==t||"implements"==t||c&&","==e?("implements"==t&&(T.marked="keyword"),L(c?ce:I,De)):"{"==e?L(F("}"),Fe,W):void 0}function Fe(e,t){return"async"==e||"variable"==e&&("static"==t||"get"==t||"set"==t||c&&A(t))&&T.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(T.marked="keyword",L(Fe)):"variable"==e||"keyword"==T.style?(T.marked="property",L(c?We:Oe,Fe)):"["==e?L(I,ae,z("]"),c?We:Oe,Fe):"*"==t?(T.marked="keyword",L(Fe)):";"==e?L(Fe):"}"==e?L():"@"==t?L(I,Fe):void 0}function We(e,t){return"?"==t?L(We):":"==e?L(ce,xe):"="==t?L(R):S(Oe)}function ze(e,t){return"*"==t?(T.marked="keyword",L(Be,z(";"))):"default"==t?(T.marked="keyword",L(I,z(";"))):"{"==e?L(ne(Pe,"}"),Be,z(";")):S(P)}function Pe(e,t){return"as"==t?(T.marked="keyword",L(z("variable"))):"variable"==e?S(R,Pe):void 0}function He(e){return"string"==e?L():"("==e?S(I):S(Ie,Re,Be)}function Ie(e,t){return"{"==e?ie(Ie,"}"):("variable"==e&&r(t),"*"==t&&(T.marked="keyword"),L(je))}function Re(e){if(","==e)return L(Ie,Re)}function je(e,t){if("as"==t)return T.marked="keyword",L(Ie)}function Be(e,t){if("from"==t)return T.marked="keyword",L(I)}function qe(e){return"]"==e?L():S(ne(R,"]"))}function Ue(){return S(F("form"),ye,z("{"),F("}"),ne(Ke,"}"),W,W)}function Ke(){return S(ye,xe)}function Ve(e,t,r){return t.tokenize==v&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(t.lastType)||"quasi"==t.lastType&&/\{\s*$/.test(e.string.slice(0,e.pos-(r||0)))}return W.lex=D.lex=!0,{startState:function(e){var t={tokenize:v,lastType:"sof",cc:[],lexical:new k((e||0)-f,0,"block",!1),localVars:d.localVars,context:d.localVars&&new O(null,null,!1),indented:e||0};return d.globalVars&&"object"==typeof d.globalVars&&(t.globalVars=d.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),o(e,t)),t.tokenize!=y&&e.eatSpace())return null;var r=t.tokenize(e,t);return"comment"==n?r:(t.lastType="operator"!=n||"++"!=i&&"--"!=i?n:"incdec",function(e,t,r,n,i){var o=e.cc;for(T.state=e,T.stream=i,T.marked=null,T.cc=o,T.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;)if((o.length?o.pop():l?I:P)(r,n)){for(;o.length&&o[o.length-1].lex;)o.pop()();return T.marked?T.marked:"variable"==r&&C(e,n)?"variable-2":t}}(t,r,n,i,e))},indent:function(e,t){if(e.tokenize==y)return Ge.Pass;if(e.tokenize!=v)return 0;var r,n=t&&t.charAt(0),i=e.lexical;if(!/^\s*else\b/.test(t))for(var o=e.cc.length-1;0<=o;--o){var a=e.cc[o];if(a==W)i=i.prev;else if(a!=Ce)break}for(;("stat"==i.type||"form"==i.type)&&("}"==n||(r=e.cc[e.cc.length-1])&&(r==U||r==K)&&!/^[,\.=+\-*:?[\(]/.test(t));)i=i.prev;h&&")"==i.type&&"stat"==i.prev.type&&(i=i.prev);var l,s,c=i.type,u=n==c;return"vardef"==c?i.indented+("operator"==e.lastType||","==e.lastType?i.info.length+1:0):"form"==c&&"{"==n?i.indented:"form"==c?i.indented+f:"stat"==c?i.indented+(s=t,"operator"==(l=e).lastType||","==l.lastType||p.test(s.charAt(0))||/[,.]/.test(s.charAt(0))?h||f:0):"switch"!=i.info||u||0==d.doubleIndentSwitch?i.align?i.column+(u?0:1):i.indented+(u?0:f):i.indented+(/^(?:case|default)\b/.test(t)?f:2*f)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:l?null:"/*",blockCommentEnd:l?null:"*/",blockCommentContinue:l?null:" * ",lineComment:l?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:l?"json":"javascript",jsonldMode:a,jsonMode:l,expressionAllowed:Ve,skipExpression:function(e){var t=e.cc[e.cc.length-1];t!=I&&t!=R||e.cc.pop()}}}),Ge.registerHelper("wordChars","javascript",/[\w$]/),Ge.defineMIME("text/javascript","javascript"),Ge.defineMIME("text/ecmascript","javascript"),Ge.defineMIME("application/javascript","javascript"),Ge.defineMIME("application/x-javascript","javascript"),Ge.defineMIME("application/ecmascript","javascript"),Ge.defineMIME("application/json",{name:"javascript",json:!0}),Ge.defineMIME("application/x-json",{name:"javascript",json:!0}),Ge.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),Ge.defineMIME("text/typescript",{name:"javascript",typescript:!0}),Ge.defineMIME("application/typescript",{name:"javascript",typescript:!0})},"object"==typeof r&&"object"==typeof t?n(e("../../lib/codemirror")):"function"==typeof o&&o.amd?o(["../../lib/codemirror"],n):n(CodeMirror)},{"../../lib/codemirror":17}],21:[function(e,t,r){var n;n=function(C){"use strict";var T={autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0},S={autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,allowMissingTagName:!1,caseFold:!1};C.defineMode("xml",function(e,t){var a,o,l=e.indentUnit,s={},r=t.htmlMode?T:S;for(var n in r)s[n]=r[n];for(var n in t)s[n]=t[n];function c(t,r){function e(e){return(r.tokenize=e)(t,r)}var n=t.next();return"<"==n?t.eat("!")?t.eat("[")?t.match("CDATA[")?e(i("atom","]]>")):null:t.match("--")?e(i("comment","--\x3e")):t.match("DOCTYPE",!0,!0)?(t.eatWhile(/[\w\._\-]/),e(function n(i){return function(e,t){for(var r;null!=(r=e.next());){if("<"==r)return t.tokenize=n(i+1),t.tokenize(e,t);if(">"==r){if(1!=i)return t.tokenize=n(i-1),t.tokenize(e,t);t.tokenize=c;break}}return"meta"}}(1))):null:t.eat("?")?(t.eatWhile(/[\w\._\-]/),r.tokenize=i("meta","?>"),"meta"):(a=t.eat("/")?"closeTag":"openTag",r.tokenize=u,"tag bracket"):"&"!=n?(t.eatWhile(/[^&<]/),null):(t.eat("#")?t.eat("x")?t.eatWhile(/[a-fA-F\d]/)&&t.eat(";"):t.eatWhile(/[\d]/)&&t.eat(";"):t.eatWhile(/[\w\.\-:]/)&&t.eat(";"))?"atom":"error"}function u(e,t){var r=e.next();if(">"==r||"/"==r&&e.eat(">"))return t.tokenize=c,a=">"==r?"endTag":"selfcloseTag","tag bracket";if("="==r)return a="equals",null;if("<"!=r)return/[\'\"]/.test(r)?(t.tokenize=(n=r,(i=function(e,t){for(;!e.eol();)if(e.next()==n){t.tokenize=u;break}return"string"}).isInAttribute=!0,i),t.stringStartCol=e.column(),t.tokenize(e,t)):(e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word");t.tokenize=c,t.state=p,t.tagName=t.tagStart=null;var n,i,o=t.tokenize(e,t);return o?o+" tag error":"tag error"}function i(r,n){return function(e,t){for(;!e.eol();){if(e.match(n)){t.tokenize=c;break}e.next()}return r}}function d(e,t,r){this.prev=e.context,this.tagName=t,this.indent=e.indented,this.startOfLine=r,(s.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)&&(this.noIndent=!0)}function f(e){e.context&&(e.context=e.context.prev)}function h(e,t){for(var r;;){if(!e.context)return;if(r=e.context.tagName,!s.contextGrabbers.hasOwnProperty(r)||!s.contextGrabbers[r].hasOwnProperty(t))return;f(e)}}function p(e,t,r){return"openTag"==e?(r.tagStart=t.column(),m):"closeTag"==e?g:p}function m(e,t,r){return"word"==e?(r.tagName=t.current(),o="tag",b):s.allowMissingTagName&&"endTag"==e?(o="tag bracket",b(e,t,r)):(o="error",m)}function g(e,t,r){if("word"!=e)return s.allowMissingTagName&&"endTag"==e?(o="tag bracket",v(e,t,r)):(o="error",y);var n=t.current();return r.context&&r.context.tagName!=n&&s.implicitlyClosed.hasOwnProperty(r.context.tagName)&&f(r),r.context&&r.context.tagName==n||!1===s.matchClosing?(o="tag",v):(o="tag error",y)}function v(e,t,r){return"endTag"!=e?(o="error",v):(f(r),p)}function y(e,t,r){return o="error",v(e,0,r)}function b(e,t,r){if("word"==e)return o="attribute",w;if("endTag"!=e&&"selfcloseTag"!=e)return o="error",b;var n=r.tagName,i=r.tagStart;return r.tagName=r.tagStart=null,"selfcloseTag"==e||s.autoSelfClosers.hasOwnProperty(n)?h(r,n):(h(r,n),r.context=new d(r,n,i==r.indented)),p}function w(e,t,r){return"equals"==e?x:(s.allowMissing||(o="error"),b(e,0,r))}function x(e,t,r){return"string"==e?k:"word"==e&&s.allowUnquoted?(o="string",b):(o="error",b(e,0,r))}function k(e,t,r){return"string"==e?k:b(e,0,r)}return c.isInText=!0,{startState:function(e){var t={tokenize:c,state:p,indented:e||0,tagName:null,tagStart:null,context:null};return null!=e&&(t.baseIndent=e),t},token:function(e,t){if(!t.tagName&&e.sol()&&(t.indented=e.indentation()),e.eatSpace())return null;a=null;var r=t.tokenize(e,t);return(r||a)&&"comment"!=r&&(o=null,t.state=t.state(a||r,e,t),o&&(r="error"==o?r+" error":o)),r},indent:function(e,t,r){var n=e.context;if(e.tokenize.isInAttribute)return e.tagStart==e.indented?e.stringStartCol+1:e.indented+l;if(n&&n.noIndent)return C.Pass;if(e.tokenize!=u&&e.tokenize!=c)return r?r.match(/^(\s*)/)[0].length:0;if(e.tagName)return!1!==s.multilineTagIndentPastTag?e.tagStart+e.tagName.length+2:e.tagStart+l*(s.multilineTagIndentFactor||1);if(s.alignCDATA&&/$/,blockCommentStart:"\x3c!--",blockCommentEnd:"--\x3e",configuration:s.htmlMode?"html":"xml",helperType:s.htmlMode?"html":"xml",skipAttribute:function(e){e.state==x&&(e.state=b)}}}),C.defineMIME("text/xml","xml"),C.defineMIME("application/xml","xml"),C.mimeModes.hasOwnProperty("text/html")||C.defineMIME("text/html",{name:"xml",htmlMode:!0})},"object"==typeof r&&"object"==typeof t?n(e("../../lib/codemirror")):"function"==typeof o&&o.amd?o(["../../lib/codemirror"],n):n(CodeMirror)},{"../../lib/codemirror":17}],22:[function(e,t,r){t.exports={prettyPrint:function(e,t){var r,n,i,o,a,c;for(n=(t=t||{}).indent_size||4,i=t.indent_char||" ",a=t.brace_style||"collapse",o=0==t.max_char?1/0:t.max_char||70,c=t.unformatted||["a","span","bdo","em","strong","dfn","code","samp","kbd","var","cite","abbr","acronym","q","sub","sup","tt","i","b","big","small","u","s","strike","font","ins","del","pre","address","dt","h1","h2","h3","h4","h5","h6"],(r=new function(){return this.pos=0,this.token="",this.current_mode="CONTENT",this.tags={parent:"parent1",parentcount:1,parent1:""},this.tag_type="",this.token_text=this.last_token=this.last_text=this.token_type="",this.Utils={whitespace:"\n\r\t ".split(""),single_token:"br,input,link,meta,!doctype,basefont,base,area,hr,wbr,param,img,isindex,?xml,embed,?php,?,?=".split(","),extra_liners:"head,body,/html".split(","),in_array:function(e,t){for(var r=0;r=this.input.length)return t.length?t.join(""):["","TK_EOF"];if(e=this.input.charAt(this.pos),this.pos++,this.line_char_count++,this.Utils.in_array(e,this.Utils.whitespace))t.length&&(r=!0),this.line_char_count--;else{if(r){if(this.line_char_count>=this.max_char){t.push("\n");for(var n=0;n","igm");r.lastIndex=this.pos;var n=r.exec(this.input),i=n?n.index:this.input.length;return this.pos=this.input.length)return n.length?n.join(""):["","TK_EOF"];r=this.input.charAt(this.pos),this.pos++,this.line_char_count++,this.Utils.in_array(r,this.Utils.whitespace)?(i=!0,this.line_char_count--):("'"!==r&&'"'!==r||n[1]&&"!"===n[1]||(r+=this.get_unformatted(r),i=!0),"="===r&&(i=!1),n.length&&"="!==n[n.length-1]&&">"!==r&&i&&(this.line_char_count>=this.max_char?(this.print_newline(!1,n),this.line_char_count=0):(n.push(" "),this.line_char_count++),i=!1),"<"===r&&(e=this.pos-1),n.push(r))}while(">"!==r);var o,a=n.join("");o=-1!=a.indexOf(" ")?a.indexOf(" "):a.indexOf(">");var l=a.substring(1,o).toLowerCase();if("/"===a.charAt(a.length-2)||this.Utils.in_array(l,this.Utils.single_token))this.tag_type="SINGLE";else if("script"===l)this.record_tag(l),this.tag_type="SCRIPT";else if("style"===l)this.record_tag(l),this.tag_type="STYLE";else if(this.Utils.in_array(l,c)){var s=this.get_unformatted("",a);n.push(s),0",a):this.get_unformatted("--\x3e",a),n.push(s),this.tag_type="SINGLE"):("/"===l.charAt(0)?(this.retrieve_tag(l.substring(1)),this.tag_type="END"):(this.record_tag(l),this.tag_type="START"),this.Utils.in_array(l,this.Utils.extra_liners)&&this.print_newline(!0,this.output));return n.join("")},this.get_unformatted=function(e,t){if(t&&-1!=t.toLowerCase().indexOf(e))return"";var r="",n="",i=!0;do{if(this.pos>=this.input.length)return n;if(r=this.input.charAt(this.pos),this.pos++,this.Utils.in_array(r,this.Utils.whitespace)){if(!i){this.line_char_count--;continue}if("\n"===r||"\r"===r){n+="\n",this.line_char_count=0;continue}}n+=r,this.line_char_count++,i=!0}while(-1==n.toLowerCase().indexOf(e));return n},this.get_token=function(){var e;if("TK_TAG_SCRIPT"!==this.last_token&&"TK_TAG_STYLE"!==this.last_token)return"CONTENT"===this.current_mode?"string"!=typeof(e=this.get_content())?e:[e,"TK_CONTENT"]:"TAG"===this.current_mode?"string"!=typeof(e=this.get_tag())?e:[e,"TK_TAG_"+this.tag_type]:void 0;var t=this.last_token.substr(7);return"string"!=typeof(e=this.get_contents_to(t))?e:[e,"TK_"+t]},this.get_full_indent=function(e){return(e=this.indent_level+e||0)<1?"":Array(e+1).join(this.indent_string)},this.printer=function(e,t,r,n,i){this.input=e||"",this.output=[],this.indent_character=t,this.indent_string="",this.indent_size=r,this.brace_style=i,this.indent_level=0,this.max_char=n;for(var o=this.line_char_count=0;o";var r=document.querySelector(".nl4wp-notices");if(!r){(r=document.createElement("div")).className="nl4wp-notices";var n=document.querySelector("h1, h2");n.parentNode.insertBefore(r,n.nextSibling)}r.innerHTML=e}t.exports={init:function(r,n){var e=function(){-1GROUPINGS fields.

Please remove these fields from your form and then re-add them through the available field buttons to make sure your data is getting through to Newsletter correctly."):a("deprecated_groupings")},t=function(){var e=n.getAllWhere("forceRequired",!0).filter(function(e){return!r.containsField(e.name().toUpperCase())}),t="Heads up! Your form is missing list fields that are required in Newsletter. Either add these fields to your form or mark them as optional in Newsletter.";t+='
  • '+e.map(function(e){return e.title()}).join("
  • ")+"
",0'"]=function(e){return function(e){if(e.getOption("disableInput"))return y.Pass;for(var t=e.listSelections(),r=[],n=e.getOption("autoCloseTags"),i=0;io.ch&&(f=f.slice(0,f.length-a.end+o.ch));var h=f.toLowerCase();if(!f||"string"==a.type&&(a.end!=o.ch||!/[\"\']/.test(a.string.charAt(a.string.length-1))||1==a.string.length)||"tag"==a.type&&"closeTag"==s.type||a.string.indexOf("/")==a.string.length-1||u&&-1"+(p?"\n\n":"")+"",newPos:p?y.Pos(o.line+1,0):y.Pos(o.line,o.ch+1)}}for(var m="object"==typeof n&&n.dontIndentOnAutoClose,i=t.length-1;0<=i;i--){var g=r[i];e.replaceRange(g.text,t[i].head,t[i].anchor,"+insert");var v=e.listSelections().slice(0);v[i]={head:g.newPos,anchor:g.newPos},e.setSelections(v),!m&&g.indent&&(e.indentLine(g.newPos.line,null,!0),e.indentLine(g.newPos.line+1,null,!0))}}(e)}),e.addKeyMap(n)}});var b=["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],w=["applet","blockquote","body","button","div","dl","fieldset","form","frameset","h1","h2","h3","h4","h5","h6","head","html","iframe","layer","legend","object","ol","p","select","table","ul"];function i(e,t){for(var r=e.listSelections(),n=[],i=t?"/":""!=e.getLine(c.line).charAt(u.end)&&(s+=">"),n[l]=s}if(e.replaceSelections(n),r=e.listSelections(),!a)for(l=0;l",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"};function d(e,t,r){var n=e.getLineHandle(t.line),i=t.ch-1,o=r&&r.afterCursor;null==o&&(o=/(^| )cm-fat-cursor($| )/.test(e.getWrapperElement().className));var a=!o&&0<=i&&g[n.text.charAt(i)]||g[n.text.charAt(++i)];if(!a)return null;var l=">"==a.charAt(1)?1:-1;if(r&&r.strict&&0o))for(u==t.line&&(f=t.ch-(r<0?1:0));f!=h;f+=r){var p=d.charAt(f);if(s.test(p)&&(void 0===n||e.getTokenTypeAt(m(u,f+1))==n))if(">"==g[p].charAt(1)==0=e.max))return e.ch=0,e.text=e.cm.getLine(++e.line),!0}function a(e){if(!(e.line<=e.min))return e.text=e.cm.getLine(--e.line),e.ch=e.text.length,!0}function d(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(o(e))continue;return}if(i(e,t+1)){var r=e.text.lastIndexOf("/",t),n=-1",e.ch-1):-1;if(-1==t){if(a(e))continue;return}if(i(e,t+1)){var r=e.text.lastIndexOf("/",t),n=-1")||-1!=n.text.indexOf("<")){var i=d(n),o=i&&s(n.line,n.ch),a=i&&f(n);if(i&&a&&!(0=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var r=e;!r.lines;)for(var n=0;;++n){var i=r.children[n],o=i.chunkSize();if(t=e.first&&to?ge(o,se(e,o).text.length):(n=se(e,(r=t).line).text.length,null==(i=r.ch)||n=t:o.to>t);(n||(n=[])).push(new Me(a,o.from,l?null:o.to))}}return n}(r,i,a),s=function(e,t,r){var n;if(e)for(var i=0;i=t:o.to>t)||o.from==t&&"bookmark"==a.type&&(!r||o.marker.insertLeft)){var l=null==o.from||(a.inclusiveLeft?o.from<=t:o.fromt)&&(!r||ze(r,o.marker)<0)&&(r=o.marker)}return r}function je(e,t,r,n,i){var o=se(e,t),a=Le&&o.markedSpans;if(a)for(var l=0;le.lastLine())return t;var r,n=se(e,t);if(!Ke(e,n))return t;for(;r=Ie(n);)n=r.find(1,!0).line;return fe(n)+1}function Ke(e,t){var r=Le&&t.markedSpans;if(r)for(var n=void 0,i=0;ir.maxLineLength&&(r.maxLineLength=t,r.maxLine=e)})}var Xe=null;function Ze(e,t,r){var n;Xe=null;for(var i=0;it)return i;o.to==t&&(o.from!=o.to&&"before"==r?n=i:Xe=i),o.from==t&&(o.from!=o.to&&"before"!=r?n=i:Xe=i)}return null!=n?n:Xe}var Je=function(){var P="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",H="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";var I=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,R=/[stwN]/,j=/[LRr]/,B=/[Lb1n]/,q=/[1n]/;function U(e,t,r){this.level=e,this.from=t,this.to=r}return function(e,t){var r="ltr"==t?"L":"R";if(0==e.length||"ltr"==t&&!I.test(e))return!1;for(var n,i=e.length,o=[],a=0;a=this.string.length},Ft.prototype.sol=function(){return this.pos==this.lineStart},Ft.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Ft.prototype.next=function(){if(this.post},Ft.prototype.eatSpace=function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},Ft.prototype.skipToEnd=function(){this.pos=this.string.length},Ft.prototype.skipTo=function(e){var t=this.string.indexOf(e,this.pos);if(-1e.options.maxHighlightLength&&_t(e.doc.mode,n.state),o=Pt(e,t,n);i&&(n.state=i),t.stateAfter=n.save(!i),t.styles=o.styles,o.classes?t.styleClasses=o.classes:t.styleClasses&&(t.styleClasses=null),r===e.doc.highlightFrontier&&(e.doc.modeFrontier=Math.max(e.doc.modeFrontier,++e.doc.highlightFrontier))}return t.styles}function It(r,n,e){var t=r.doc,i=r.display;if(!t.mode.startState)return new zt(t,!0,n);var o=function(e,t,r){for(var n,i,o=e.doc,a=r?-1:t-(e.doc.mode.innerMode?1e3:100),l=t;at.first&&se(t,o-1).stateAfter,l=a?zt.fromSaved(t,a,o):new zt(t,Dt(t.mode),o);return t.iter(o,n,function(e){Rt(r,e.text,l);var t=l.line;e.stateAfter=t==n-1||t%5==0||t>=i.viewFrom&&tt.start)return o}throw new Error("Mode "+e.name+" failed to advance stream.")}zt.prototype.lookAhead=function(e){var t=this.doc.getLine(this.line+e);return null!=t&&e>this.maxLookAhead&&(this.maxLookAhead=e),t},zt.prototype.baseToken=function(e){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=e;)this.baseTokenPos+=2;var t=this.baseTokens[this.baseTokenPos+1];return{type:t&&t.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-e}},zt.prototype.nextLine=function(){this.line++,0e.options.maxHighlightLength?(l=!1,a&&Rt(e,t,n,d.pos),d.pos=t.length,null):Kt(Bt(r,d,n.state,f),o),f){var h=f[0].name;h&&(s="m-"+(s?h+" "+s:h))}if(!l||u!=s){for(;cl&&c.from<=l);u++);if(c.to>=s)return d(e,t,r,n,i,o,a);d(e,t.slice(0,c.to-l),r,n,null,o,a),n=null,t=t.slice(c.to-l),l=c.to}}}function tr(e,t,r,n){var i=!n&&r.widgetNode;i&&e.map.push(e.pos,e.pos+t,i),!n&&e.cm.display.input.needsContentAttribute&&(i||(i=e.content.appendChild(document.createElement("span"))),i.setAttribute("cm-marker",r.id)),i&&(e.cm.display.input.setUneditable(i),e.content.appendChild(i)),e.pos+=t,e.trailingSpace=!1}function rr(e,t,r){var n=e.markedSpans,i=e.text,o=0;if(n)for(var a,l,s,c,u,d,f,h=i.length,p=0,m=1,g="",v=0;;){if(v==p){s=c=u=l="",d=f=null,v=1/0;for(var y=[],b=void 0,w=0;wp||k.collapsed&&x.to==p&&x.from==p)){if(null!=x.to&&x.to!=p&&v>x.to&&(v=x.to,c=""),k.className&&(s+=" "+k.className),k.css&&(l=(l?l+";":"")+k.css),k.startStyle&&x.from==p&&(u+=" "+k.startStyle),k.endStyle&&x.to==v&&(b||(b=[])).push(k.endStyle,x.to),k.title&&((f||(f={})).title=k.title),k.attributes)for(var C in k.attributes)(f||(f={}))[C]=k.attributes[C];k.collapsed&&(!d||ze(d.marker,k)<0)&&(d=x)}else x.from>p&&v>x.from&&(v=x.from)}if(b)for(var T=0;Tr)return{map:e.measure.maps[i],cache:e.measure.caches[i],before:!0}}function Ar(e,t,r,n){return _r(e,Nr(e,t),r,n)}function Or(e,t){if(t>=e.display.viewFrom&&t=r.lineN&&tt)&&(i=(o=s-l)-1,s<=t&&(a="right")),null!=i){if(n=e[c+2],l==s&&r==(n.insertLeft?"left":"right")&&(a=r),"left"==r&&0==i)for(;c&&e[c-2]==e[c-3]&&e[c-1].insertLeft;)n=e[2+(c-=3)],a="left";if("right"==r&&i==s-l)for(;c=o.text.length?(t=o.text.length,r="before"):t<=0&&(t=0,r="after"),!c)return s("before"==r?t-1:t,"before"==r);function u(e,t,r){return s(r?e-1:e,1==c[t].level!=r)}var d=Ze(c,t,r),f=Xe,h=u(t,d,"before"==r);return null!=f&&(h.other=u(t,f,"before"!=r)),h}function Vr(e,t){var r=0;t=Ce(e.doc,t),e.options.lineWrapping||(r=en(e.display)*t.ch);var n=se(e.doc,t.line),i=Ge(n)+xr(e.display);return{left:r,right:r,top:i,bottom:i+n.height}}function Gr(e,t,r,n,i){var o=ge(e,t,r);return o.xRel=i,n&&(o.outside=!0),o}function $r(e,t,r){var n=e.doc;if((r+=e.display.viewOffset)<0)return Gr(n.first,0,null,!0,-1);var i=he(n,r),o=n.first+n.size-1;if(on},o,i)}}function Xr(e,t,r,n){return r||(r=Nr(e,t)),Yr(e,t,r,Br(e,t,_r(e,r,n),"line").top)}function Zr(e,t,r,n){return!(e.bottom<=r)&&(e.top>r||(n?e.left:e.right)>t)}function Jr(r,e,t,n,i){i-=Ge(e);var o=Nr(r,e),a=jr(e),l=0,s=e.text.length,c=!0,u=Qe(e,r.doc.direction);if(u){var d=(r.options.lineWrapping?function(e,t,r,n,i,o,a){var l=Yr(e,t,n,a),s=l.begin,c=l.end;/\s/.test(t.text.charAt(c-1))&&c--;for(var u=null,d=null,f=0;f=c||h.to<=s)){var p=1!=h.level,m=_r(e,n,p?Math.min(c,h.to)-1:Math.max(s,h.from)).right,g=mc&&(u={from:u.from,to:c,level:u.level});return u}:function(n,i,o,a,l,s,c){var e=ae(function(e){var t=l[e],r=1!=t.level;return Zr(Kr(n,ge(o,r?t.to:t.from,r?"before":"after"),"line",i,a),s,c,!0)},0,l.length-1),t=l[e];if(0c&&(t=l[e-1])}return t})(r,e,t,o,u,n,i);l=(c=1!=d.level)?d.from:d.to-1,s=c?d.to:d.from-1}var f,h,p=null,m=null,g=ae(function(e){var t=_r(r,o,e);return t.top+=a,t.bottom+=a,!!Zr(t,n,i,!1)&&(t.top<=i&&t.left<=n&&(p=e,m=t),!0)},l,s),v=!1;if(m){var y=n-m.left=w.bottom}return Gr(t,g=oe(e.text,g,1),h,v,n-f)}function Qr(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==Er){Er=N("pre");for(var t=0;t<49;++t)Er.appendChild(document.createTextNode("x")),Er.appendChild(N("br"));Er.appendChild(document.createTextNode("x"))}A(e.measure,Er);var r=Er.offsetHeight/50;return 3=e.display.viewTo)return null;if((t-=e.display.viewFrom)<0)return null;for(var r=e.display.view,n=0;n=e.display.viewTo||l.to().linet||t==r&&a.to==t)&&(n(Math.max(a.from,t),Math.min(a.to,r),1==a.level?"rtl":"ltr",o),i=!0)}i||n(t,r,"ltr")}(S,y||0,null==b?k:b,function(e,t,r,n){var i="ltr"==r,o=C(e,i?"left":"right"),a=C(t-1,i?"right":"left"),l=null==y&&0==e,s=null==b&&t==k,c=0==n,u=!S||n==S.length-1;if(a.top-o.top<=3){var d=(A?s:l)&&u,f=(A?l:s)&&c?L:(i?o:a).left,h=d?M:(i?a:o).right;O(f,o.top,h-f,o.bottom)}else{var p,m,g,v;v=i?(p=A&&l&&c?L:o.left,m=A?M:T(e,r,"before"),g=A?L:T(t,r,"after"),A&&s&&u?M:a.right):(p=A?T(e,r,"before"):L,m=!A&&l&&c?M:o.right,g=!A&&s&&u?L:a.left,A?T(t,r,"after"):M),O(p,o.top,m-p,o.bottom),o.bottome.display.sizerWidth){var f=Math.ceil(l/en(e.display));f>e.display.maxLineLength&&(e.display.maxLineLength=f,e.display.maxLine=i.line,e.display.maxLineChanged=!0)}}}}function bn(e){if(e.widgets)for(var t=0;t=a&&(o=he(t,Ge(se(t,s))-e.wrapper.clientHeight),a=s)}return{from:o,to:Math.max(a,o+1)}}function xn(e){var t=e.display,r=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var n=rn(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=n+"px",a=0;ao&&(t.bottom=t.top+o);var l=e.doc.height+kr(r),s=t.topl-n;if(t.topi+o){var u=Math.min(t.top,(c?l:t.bottom)-o);u!=i&&(a.scrollTop=u)}var d=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:r.scroller.scrollLeft,f=Sr(e)-(e.options.fixedGutter?r.gutters.offsetWidth:0),h=t.right-t.left>f;return h&&(t.right=t.left+f),t.left<10?a.scrollLeft=0:t.leftf+d-3&&(a.scrollLeft=t.right+(h?0:10)-f),a}function Tn(e,t){null!=t&&(Mn(e),e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+t)}function Sn(e){Mn(e);var t=e.getCursor();e.curOp.scrollToPos={from:t,to:t,margin:e.options.cursorScrollMargin}}function Ln(e,t,r){null==t&&null==r||Mn(e),null!=t&&(e.curOp.scrollLeft=t),null!=r&&(e.curOp.scrollTop=r)}function Mn(e){var t=e.curOp.scrollToPos;t&&(e.curOp.scrollToPos=null,An(e,Vr(e,t.from),Vr(e,t.to),t.margin))}function An(e,t,r,n){var i=Cn(e,{left:Math.min(t.left,r.left),top:Math.min(t.top,r.top)-n,right:Math.max(t.right,r.right),bottom:Math.max(t.bottom,r.bottom)+n});Ln(e,i.scrollLeft,i.scrollTop)}function On(e,t){Math.abs(e.doc.scrollTop-t)<2||(m||ai(e,{top:t}),Nn(e,t,!0),m&&ai(e),ti(e,100))}function Nn(e,t,r){t=Math.min(e.display.scroller.scrollHeight-e.display.scroller.clientHeight,t),(e.display.scroller.scrollTop!=t||r)&&(e.doc.scrollTop=t,e.display.scrollbars.setScrollTop(t),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t))}function _n(e,t,r,n){t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth),(r?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)&&!n||(e.doc.scrollLeft=t,xn(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbars.setScrollLeft(t))}function En(e){var t=e.display,r=t.gutters.offsetWidth,n=Math.round(e.doc.height+kr(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?r:0,docHeight:n,scrollHeight:n+Tr(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:r}}var Dn=function(e,t,r){this.cm=r;var n=this.vert=N("div",[N("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i=this.horiz=N("div",[N("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");n.tabIndex=i.tabIndex=-1,e(n),e(i),tt(n,"scroll",function(){n.clientHeight&&t(n.scrollTop,"vertical")}),tt(i,"scroll",function(){i.clientWidth&&t(i.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,x&&k<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};Dn.prototype.update=function(e){var t=e.scrollWidth>e.clientWidth+1,r=e.scrollHeight>e.clientHeight+1,n=e.nativeBarWidth;if(r){this.vert.style.display="block",this.vert.style.bottom=t?n+"px":"0";var i=e.viewHeight-(t?n:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+i)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(t){this.horiz.style.display="block",this.horiz.style.right=r?n+"px":"0",this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(r?n:0);this.horiz.firstChild.style.width=Math.max(0,e.scrollWidth-e.clientWidth+o)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&0=i.viewTo)||i.maxLineChanged&&n.options.lineWrapping,e.update=e.mustUpdate&&new ni(n,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function qn(e){var t=e.cm,r=t.display;e.updatedDisplay&&yn(t),e.barMeasure=En(t),r.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=Ar(t,r.maxLine,r.maxLine.text.length).left+3,t.display.sizerWidth=e.adjustWidthTo,e.barMeasure.scrollWidth=Math.max(r.scroller.clientWidth,r.sizer.offsetLeft+e.adjustWidthTo+Tr(t)+t.display.barWidth),e.maxScrollLeft=Math.max(0,r.sizer.offsetLeft+e.adjustWidthTo-Sr(t))),(e.updatedDisplay||e.selectionChanged)&&(e.preparedSelection=r.input.prepareSelection())}function Un(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null!=i&&!c){var o=N("div","​",null,"position: absolute;\n top: "+(t.top-r.viewOffset-xr(e.display))+"px;\n height: "+(t.bottom-t.top+Tr(e)+r.barHeight)+"px;\n left: "+t.left+"px; width: "+Math.max(2,t.right-t.left)+"px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(i),e.display.lineSpace.removeChild(o)}}}(t,function(e,t,r,n){var i;null==n&&(n=0),e.options.lineWrapping||t!=r||(r="before"==(t=t.ch?ge(t.line,"before"==t.sticky?t.ch-1:t.ch,"after"):t).sticky?ge(t.line,t.ch+1,"before"):t);for(var o=0;o<5;o++){var a=!1,l=Kr(e,t),s=r&&r!=t?Kr(e,r):l,c=Cn(e,i={left:Math.min(l.left,s.left),top:Math.min(l.top,s.top)-n,right:Math.max(l.left,s.left),bottom:Math.max(l.bottom,s.bottom)+n}),u=e.doc.scrollTop,d=e.doc.scrollLeft;if(null!=c.scrollTop&&(On(e,c.scrollTop),1t)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=i.viewTo)Le&&qe(e.doc,t)i.viewFrom?Jn(e):(i.viewFrom+=n,i.viewTo+=n);else if(t<=i.viewFrom&&r>=i.viewTo)Jn(e);else if(t<=i.viewFrom){var o=Qn(e,r,r+n,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=n):Jn(e)}else if(r>=i.viewTo){var a=Qn(e,t,t,-1);a?(i.view=i.view.slice(0,a.index),i.viewTo=a.lineN):Jn(e)}else{var l=Qn(e,t,t,-1),s=Qn(e,r,r+n,1);l&&s?(i.view=i.view.slice(0,l.index).concat(ir(e,l.lineN,s.lineN)).concat(i.view.slice(s.index)),i.viewTo+=n):Jn(e)}var c=i.externalMeasured;c&&(r=i.lineN&&t=n.viewTo)){var o=n.view[ln(e,t)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==R(a,r)&&a.push(r)}}}function Jn(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function Qn(e,t,r,n){var i,o=ln(e,t),a=e.display.view;if(!Le||r==e.doc.first+e.doc.size)return{index:o,lineN:r};for(var l=e.display.viewFrom,s=0;s=s.display.viewTo)){var u=+new Date+s.options.workTime,d=It(s,c.highlightFrontier),f=[];c.iter(d.line,Math.min(c.first+c.size,s.display.viewTo+500),function(e){if(d.line>=s.display.viewFrom){var t=e.styles,r=e.text.length>s.options.maxHighlightLength?_t(c.mode,d.state):null,n=Pt(s,e,d,!0);r&&(d.state=r),e.styles=n.styles;var i=e.styleClasses,o=n.classes;o?e.styleClasses=o:i&&(e.styleClasses=null);for(var a=!t||t.length!=e.styles.length||i!=o&&(!i||!o||i.bgClass!=o.bgClass||i.textClass!=o.textClass),l=0;!a&&lu)return ti(s,s.options.workDelay),!0}),c.highlightFrontier=d.line,c.modeFrontier=Math.max(c.modeFrontier,d.line),f.length&&Vn(s,function(){for(var e=0;e=r.viewFrom&&t.visible.to<=r.viewTo&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo)&&r.renderedView==r.view&&0==ei(e))return!1;kn(e)&&(Jn(e),t.dims=tn(e));var i=n.first+n.size,o=Math.max(t.visible.from-e.options.viewportMargin,n.first),a=Math.min(i,t.visible.to+e.options.viewportMargin);r.viewFroma&&r.viewTo-a<20&&(a=Math.min(i,r.viewTo)),Le&&(o=qe(e.doc,o),a=Ue(e.doc,a));var l,s,c,u,d=o!=r.viewFrom||a!=r.viewTo||r.lastWrapHeight!=t.wrapperHeight||r.lastWrapWidth!=t.wrapperWidth;s=o,c=a,0==(u=(l=e).display).view.length||s>=u.viewTo||c<=u.viewFrom?(u.view=ir(l,s,c),u.viewFrom=s):(u.viewFrom>s?u.view=ir(l,s,u.viewFrom).concat(u.view):u.viewFromc&&(u.view=u.view.slice(0,ln(l,c)))),u.viewTo=c,r.viewOffset=Ge(se(e.doc,r.viewFrom)),e.display.mover.style.top=r.viewOffset+"px";var f=ei(e);if(!d&&0==f&&!t.force&&r.renderedView==r.view&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo))return!1;var h=function(e){if(e.hasFocus())return null;var t=E();if(!t||!_(e.display.lineDiv,t))return null;var r={activeElt:t};if(window.getSelection){var n=window.getSelection();n.anchorNode&&n.extend&&_(e.display.lineDiv,n.anchorNode)&&(r.anchorNode=n.anchorNode,r.anchorOffset=n.anchorOffset,r.focusNode=n.focusNode,r.focusOffset=n.focusOffset)}return r}(e);return 4=e.display.viewFrom&&t.visible.to<=e.display.viewTo)))&&ii(e,t);n=!1){yn(e);var i=En(e);sn(e),Wn(e,i),si(e,i),t.force=!1}t.signal(e,"update",e),e.display.viewFrom==e.display.reportedViewFrom&&e.display.viewTo==e.display.reportedViewTo||(t.signal(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo),e.display.reportedViewFrom=e.display.viewFrom,e.display.reportedViewTo=e.display.viewTo)}function ai(e,t){var r=new ni(e,t);if(ii(e,r)){yn(e),oi(e,r);var n=En(e);sn(e),Wn(e,n),si(e,n),r.finish()}}function li(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function si(e,t){e.display.sizer.style.minHeight=t.docHeight+"px",e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=t.docHeight+e.display.barHeight+Tr(e)+"px"}function ci(e){var t=e.display.gutters,r=e.options.gutters;M(t);for(var n=0;na.clientWidth,s=a.scrollHeight>a.clientHeight;if(n&&l||i&&s){if(i&&w&&b)e:for(var c=t.target,u=o.view;c!=a;c=c.parentNode)for(var d=0;ds-(e.cm?e.cm.options.historyEventDelay:500)||"*"==t.origin.charAt(0)))&&(o=(l=i).lastOp==n?(Di(l.done),Y(l.done)):l.done.length&&!Y(l.done).ranges?Y(l.done):1i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(r),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=s,i.lastOp=i.lastSelOp=n,i.lastOrigin=i.lastSelOrigin=t.origin,a||it(e,"historyAdded")}function Wi(e,t,r,n){var i,o,a,l,s,c=e.history,u=n&&n.origin;r==c.lastSelOp||u&&c.lastSelOrigin==u&&(c.lastModTime==c.lastSelTime&&c.lastOrigin==u||(i=e,o=u,a=Y(c.done),l=t,"*"==(s=o.charAt(0))||"+"==s&&a.ranges.length==l.ranges.length&&a.somethingSelected()==l.somethingSelected()&&new Date-i.history.lastSelTime<=(i.cm?i.cm.options.historyEventDelay:500)))?c.done[c.done.length-1]=t:zi(t,c.done),c.lastSelTime=+new Date,c.lastSelOrigin=u,c.lastSelOp=r,n&&!1!==n.clearRedo&&Di(c.undone)}function zi(e,t){var r=Y(t);r&&r.ranges&&r.equals(e)||t.push(e)}function Pi(t,r,e,n){var i=r["spans_"+t.id],o=0;t.iter(Math.max(t.first,e),Math.min(t.first+t.size,n),function(e){e.markedSpans&&((i||(i=r["spans_"+t.id]={}))[o]=e.markedSpans),++o})}function Hi(e){if(!e)return null;for(var t,r=0;r=t.ch:l.to>t.ch))){if(i&&(it(s,"beforeCursorEnter"),s.explicitlyCleared)){if(o.markedSpans){--a;continue}break}if(!s.atomic)continue;if(r){var c=s.find(n<0?1:-1),u=void 0;if((n<0?s.inclusiveRight:s.inclusiveLeft)&&(c=eo(e,c,-n,c&&c.line==t.line?o:null)),c&&c.line==t.line&&(u=ve(c,r))&&(n<0?u<0:0e.first?Ce(e,ge(t.line-1)):null:0e.lastLine())){if(t.from.lineo&&(t={from:t.from,to:ge(o,se(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=ce(e,t.from,t.to),r||(r=ki(e,t)),e.cm?function(e,t,r){var n=e.doc,i=e.display,o=t.from,a=t.to,l=!1,s=o.line;e.options.lineWrapping||(s=fe(Be(se(n,o.line))),n.iter(s,a.line+1,function(e){if(e==i.maxLine)return l=!0}));-1i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,l=!1)}),l&&(e.curOp.updateMaxLine=!0));(function(e,t){if(e.modeFrontier=Math.min(e.modeFrontier,t),!(e.highlightFrontiert.display.maxLineLength&&(t.display.maxLine=u,t.display.maxLineLength=d,t.display.maxLineChanged=!0)}null!=i&&t&&this.collapsed&&Xn(t,i,o+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,t&&Xi(t.doc)),t&&lr(t,"markerCleared",t,this,i,o),r&&jn(t),this.parent&&this.parent.clear()}},bo.prototype.find=function(e,t){var r,n;null==e&&"bookmark"==this.type&&(e=1);for(var i=0;i=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(i,o,a){i=Ce(this,i),o=Ce(this,o);var l=[],s=i.line;return this.iter(i.line,o.line+1,function(e){var t=e.markedSpans;if(t)for(var r=0;r=n.to||null==n.from&&s!=i.line||null!=n.from&&s==o.line&&n.from>=o.ch||a&&!a(n.marker)||l.push(n.marker.parent||n.marker)}++s}),l},getAllMarks:function(){var n=[];return this.iter(function(e){var t=e.markedSpans;if(t)for(var r=0;rt&&(t=e.from),null!=e.to&&e.toe.text.length?null:n}function Go(e,t,r){var n=Vo(e,t.ch,r);return null==n?null:new ge(t.line,n,r<0?"after":"before")}function $o(e,t,r,n,i){if(e){var o=Qe(r,t.doc.direction);if(o){var a,l=i<0?Y(o):o[0],s=i<0==(1==l.level)?"after":"before";if(0a.doc.first){var o=se(a.doc,n.line-1).text;o&&(n=new ge(n.line,1),a.replaceRange(i.charAt(0)+a.doc.lineSeparator()+o.charAt(o.length-1),ge(n.line-1,o.length-1),n,"+transpose"))}t.push(new vi(n,n))}a.setSelections(t)})},newlineAndIndent:function(n){return Vn(n,function(){for(var e=n.listSelections(),t=e.length-1;0<=t;t--)n.replaceRange(n.doc.lineSeparator(),e[t].anchor,e[t].head,"+input");e=n.listSelections();for(var r=0;ru&&t.push(new vi(ge(l,u),ge(l,V(c,a,r))))}t.length||t.push(new vi(v,v)),Gi(b,yi(g,k.ranges.slice(0,x).concat(t),x),{origin:"*mouse",scroll:!1}),g.scrollIntoView(e)}else{var d,f=w,h=da(g,e,y.unit),p=f.anchor;p=0=i.to||n.lines.bottom?20:0;o&&setTimeout(Gn(g,function(){c==r&&(a.scroller.scrollTop+=o,e(t))}),50)}}(e):n(e)}),o=Gn(g,n);g.state.selectingText=o,tt(a.wrapper.ownerDocument,"mousemove",i),tt(a.wrapper.ownerDocument,"mouseup",o)}(e,n,t,o)}(t,a,s,e):ht(e)==r.scroller&&ct(e):2==l?(a&&Bi(t.doc,a),setTimeout(function(){return r.input.focus()},20)):3==l&&(C?t.display.input.onContextMenu(e):mn(t)))}}function da(e,t,r){if("char"==r)return new vi(t,t);if("word"==r)return e.findWordAt(t);if("line"==r)return new vi(ge(t.line,0),Ce(e.doc,ge(t.line+1,0)));var n=r(e,t);return new vi(n.from,n.to)}function fa(e,t,r,n){var i,o;if(t.touches)i=t.touches[0].clientX,o=t.touches[0].clientY;else try{i=t.clientX,o=t.clientY}catch(t){return!1}if(i>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;n&&ct(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(o>l.bottom||!lt(e,r))return dt(t);o-=l.top-a.viewOffset;for(var s=0;s=i)return it(e,r,e,he(e.doc,o),e.options.gutters[s],t),dt(t)}}function ha(e,t){return fa(e,t,"gutterClick",!0)}function pa(e,t){var r,n;wr(e.display,t)||(n=t,lt(r=e,"gutterContextMenu")&&fa(r,n,"gutterContextMenu",!1))||(ot(e,t,"contextmenu")||C||e.display.input.onContextMenu(t))}function ma(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),Hr(e)}ca.prototype.compare=function(e,t,r){return this.time+400>e&&0==ve(t,this.pos)&&r==this.button};var ga={toString:function(){return"CodeMirror.Init"}},va={},ya={};function ba(e){ci(e),Xn(e),xn(e)}function wa(e,t,r){if(!t!=!(r&&r!=ga)){var n=e.display.dragFunctions,i=t?tt:nt;i(e.display.scroller,"dragstart",n.start),i(e.display.scroller,"dragenter",n.enter),i(e.display.scroller,"dragover",n.over),i(e.display.scroller,"dragleave",n.leave),i(e.display.scroller,"drop",n.drop)}}function xa(e){e.options.lineWrapping?(D(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth="",e.display.sizerWidth=null):(L(e.display.wrapper,"CodeMirror-wrap"),Ye(e)),on(e),Xn(e),Hr(e),setTimeout(function(){return Wn(e)},100)}function ka(e,t){var r=this;if(!(this instanceof ka))return new ka(e,t);this.options=t=t?P(t):{},P(va,t,!1),ui(t);var n=t.value;"string"==typeof n?n=new So(n,t.mode,null,t.lineSeparator,t.direction):t.mode&&(n.modeOption=t.mode),this.doc=n;var i=new ka.inputStyles[t.inputStyle](this),o=this.display=new le(e,n,i);for(var a in ci(o.wrapper.CodeMirror=this),ma(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),Hn(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new I,keySeq:null,specialChars:null},t.autofocus&&!f&&o.input.focus(),x&&k<11&&setTimeout(function(){return r.display.input.reset(!0)},20),function(i){var o=i.display;tt(o.scroller,"mousedown",Gn(i,ua)),tt(o.scroller,"dblclick",x&&k<11?Gn(i,function(e){if(!ot(i,e)){var t=an(i,e);if(t&&!ha(i,e)&&!wr(i.display,e)){ct(e);var r=i.findWordAt(t);Bi(i.doc,r.anchor,r.head)}}}):function(e){return ot(i,e)||ct(e)});tt(o.scroller,"contextmenu",function(e){return pa(i,e)});var r,n={end:0};function a(){o.activeTouch&&(r=setTimeout(function(){return o.activeTouch=null},1e3),(n=o.activeTouch).end=+new Date)}function l(e,t){if(null==t.left)return!0;var r=t.left-e.left,n=t.top-e.top;return 400o.first?H(se(o,t-1).text,null,a):0:"add"==r?c=s+e.options.indentUnit:"subtract"==r?c=s-e.options.indentUnit:"number"==typeof r&&(c=s+r),c=Math.max(0,c);var d="",f=0;if(e.options.indentWithTabs)for(var h=Math.floor(c/a);h;--h)f+=a,d+="\t";if(f=r.text.length?(l.ch=r.text.length,l.sticky="before"):l.ch<=0&&(l.ch=0,l.sticky="after");var n=Ze(s,l.ch,l.sticky),i=s[n];if("ltr"==t.doc.direction&&i.level%2==0&&(0l.ch:i.from=i.from&&f>=u.begin)){var h=d?"before":"after";return new ge(l.line,f,h)}}var p=function(e,t,r){for(var n=function(e,t){return t?new ge(l.line,c(e,1),"before"):new ge(l.line,e,"after")};0<=e&&e=n.first+n.size||(i=new ge(r,i.ch,i.sticky),!(l=se(n,r))))return!1;i=$o(a,n.cm,l,i.line,o)}else i=t;return!0}if("char"==e)s();else if("column"==e)s(!0);else if("word"==e||"group"==e)for(var c=null,u="group"==e,d=n.cm&&n.cm.getHelper(i,"wordChars"),f=!0;!(o<0)||s(!f);f=!1){var h=l.text.charAt(i.ch)||"\n",p=te(h,d)?"w":u&&"\n"==h?"n":!u||/\s/.test(h)?null:"p";if(!u||f||p||(p="s"),c&&c!=p){o<0&&(o=1,s(),i.sticky="after");break}if(p&&(c=p),0=a.height){o.hitSide=!0;break}i+=5*r}return o}var Wa=function(e){this.cm=e,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new I,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};function za(e,t){var r=Or(e,t.line);if(!r||r.hidden)return null;var n=se(e.doc,t.line),i=Mr(r,n,t.line),o=Qe(n,e.doc.direction),a="left";o&&(a=Ze(o,t.ch)%2?"right":"left");var l=Fr(i.map,t.ch,a);return l.offset="right"==l.collapse?l.end:l.start,l}function Pa(e,t){return t&&(e.bad=!0),e}function Ha(e,t,r){var n;if(t==e.display.lineDiv){if(!(n=e.display.lineDiv.childNodes[r]))return Pa(e.clipPos(ge(e.display.viewTo-1)),!0);t=null,r=0}else for(n=t;;n=n.parentNode){if(!n||n==e.display.lineDiv)return null;if(n.parentNode&&n.parentNode==e.display.lineDiv)break}for(var i=0;i=t.display.viewTo||i.line=t.display.viewFrom&&za(t,n)||{node:l[0].measure.map[2],offset:0},c=i.linen.firstLine()&&(a=ge(a.line-1,se(n.doc,a.line-1).length)),l.ch==se(n.doc,l.line).text.length&&l.linei.viewTo-1)return!1;r=a.line==i.viewFrom||0==(e=ln(n,a.line))?(t=fe(i.view[0].line),i.view[0].node):(t=fe(i.view[e].line),i.view[e-1].node.nextSibling);var s,c,u=ln(n,l.line);if(c=u==i.view.length-1?(s=i.viewTo-1,i.lineDiv.lastChild):(s=fe(i.view[u+1].line)-1,i.view[u+1].node.previousSibling),!r)return!1;for(var d=n.doc.splitLines(function(s,e,t,c,u){var r="",d=!1,f=s.doc.lineSeparator(),h=!1;function p(){d&&(r+=f,h&&(r+=f),d=h=!1)}function m(e){e&&(p(),r+=e)}function g(e){if(1==e.nodeType){var t=e.getAttribute("cm-text");if(t)return void m(t);var r,n=e.getAttribute("cm-marker");if(n){var i=s.findMarks(ge(c,0),ge(u+1,0),(l=+n,function(e){return e.id==l}));return void(i.length&&(r=i[0].find(0))&&m(ce(s.doc,r.from,r.to).join(f)))}if("false"==e.getAttribute("contenteditable"))return;var o=/^(pre|div|p|li|table|br)$/i.test(e.nodeName);if(!/^br$/i.test(e.nodeName)&&0==e.textContent.length)return;o&&p();for(var a=0;aa.ch&&y.charCodeAt(y.length-p-1)==b.charCodeAt(b.length-p-1);)h--,p++;d[d.length-1]=y.slice(0,y.length-p).replace(/^\u200b+/,""),d[0]=d[0].slice(h).replace(/\u200b+$/,"");var x=ge(t,h),k=ge(s,f.length?Y(f).length-p:0);return 1r&&(Ta(this,i.head.line,e,!0),r=i.head.line,n==this.doc.sel.primIndex&&Sn(this));else{var o=i.from(),a=i.to(),l=Math.max(r,o.line);r=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var s=l;s>1;if((a?r[2*a-1]:0)>=o)i=a;else{if(!(r[2*a+1]d)&&e.top>t.offsetHeight?c=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=d&&(c=e.bottom),u+t.offsetWidth>f&&(u=f-t.offsetWidth)}t.style.top=c+"px",t.style.left=t.style.right="","right"==i?(u=s.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==i?u=0:"middle"==i&&(u=(s.sizer.clientWidth-t.offsetWidth)/2),t.style.left=u+"px"),r&&(o=this,a={left:u,top:c,right:u+t.offsetWidth,bottom:c+t.offsetHeight},null!=(l=Cn(o,a)).scrollTop&&On(o,l.scrollTop),null!=l.scrollLeft&&_n(o,l.scrollLeft))},triggerOnKeyDown:$n(ia),triggerOnKeyPress:$n(aa),triggerOnKeyUp:oa,triggerOnMouseDown:$n(ua),execCommand:function(e){if(Yo.hasOwnProperty(e))return Yo[e].call(null,this)},triggerElectric:$n(function(e){Oa(this,e)}),findPosH:function(e,t,r,n){var i=1;t<0&&(i=-1,t=-t);for(var o=Ce(this.doc,e),a=0;a*\/]/.test(r)?w(null,"select-op"):"."==r&&e.match(/^-?[_a-z][_a-z0-9-]*/i)?w("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(r)?w(null,r):("u"==r||"U"==r)&&e.match(/rl(-prefix)?\(/i)||("d"==r||"D"==r)&&e.match("omain(",!0,!0)||("r"==r||"R"==r)&&e.match("egexp(",!0,!0)?(e.backUp(1),t.tokenize=k,w("property","word")):/[\w\\\-]/.test(r)?(e.eatWhile(/[\w\\\-]/),w("property","word")):w(null,null):/[\d.]/.test(e.peek())?(e.eatWhile(/[\w.%]/),w("number","unit")):e.match(/^-[\w\\\-]+/)?(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?w("variable-2","variable-definition"):w("variable-2","variable")):e.match(/^\w+-/)?w("meta","meta"):void 0})(e,t);return r&&"object"==typeof r&&(n=r[1],r=r[0]),i=r,"comment"!=n&&(t.state=O[t.state](n,e,t)),i},indent:function(e,t){var r=e.context,n=t&&t.charAt(0),i=r.indent;return"prop"!=r.type||"}"!=n&&")"!=n||(r=r.prev),r.prev&&("}"!=n||"block"!=r.type&&"top"!=r.type&&"interpolation"!=r.type&&"restricted_atBlock"!=r.type?(")"!=n||"parens"!=r.type&&"atBlock_parens"!=r.type)&&("{"!=n||"at"!=r.type&&"atBlock"!=r.type)||(i=Math.max(0,r.indent-o)):i=(r=r.prev).indent),i},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:y,fold:"brace"}});var t=["domain","regexp","url","url-prefix"],r=e(t),n=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],i=e(n),o=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover"],a=e(o),l=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],s=e(l),c=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","justify-items","justify-self","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","mix-blend-mode","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","place-content","place-items","place-self","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","user-select","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],u=e(c),d=["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"],f=e(d),h=e(["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"]),p=e(["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"]),m=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],g=e(m),v=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","devanagari","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","graytext","grid","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hard-light","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","opacity","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unset","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],y=e(v),b=t.concat(n).concat(o).concat(l).concat(c).concat(d).concat(m).concat(v);function w(e,t){for(var r,n=!1;null!=(r=e.next());){if(n&&"/"==r){t.tokenize=null;break}n="*"==r}return["comment","comment"]}N.registerHelper("hintWords","css",b),N.defineMIME("text/css",{documentTypes:r,mediaTypes:i,mediaFeatures:a,mediaValueKeywords:s,propertyKeywords:u,nonStandardPropertyKeywords:f,fontProperties:h,counterDescriptors:p,colorKeywords:g,valueKeywords:y,tokenHooks:{"/":function(e,t){return!!e.eat("*")&&(t.tokenize=w)(e,t)}},name:"css"}),N.defineMIME("text/x-scss",{mediaTypes:i,mediaFeatures:a,mediaValueKeywords:s,propertyKeywords:u,nonStandardPropertyKeywords:f,colorKeywords:g,valueKeywords:y,fontProperties:h,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=w)(e,t):["operator","operator"]},":":function(e){return!!e.match(/\s*\{/,!1)&&[null,null]},$:function(e){return e.match(/^[\w-]+/),e.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(e){return!!e.eat("{")&&[null,"interpolation"]}},name:"css",helperType:"scss"}),N.defineMIME("text/x-less",{mediaTypes:i,mediaFeatures:a,mediaValueKeywords:s,propertyKeywords:u,nonStandardPropertyKeywords:f,colorKeywords:g,valueKeywords:y,fontProperties:h,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=w)(e,t):["operator","operator"]},"@":function(e){return e.eat("{")?[null,"interpolation"]:!e.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i,!1)&&(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"])},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"}),N.defineMIME("text/x-gss",{documentTypes:r,mediaTypes:i,mediaFeatures:a,propertyKeywords:u,nonStandardPropertyKeywords:f,fontProperties:h,counterDescriptors:p,colorKeywords:g,valueKeywords:y,supportsAtComponent:!0,tokenHooks:{"/":function(e,t){return!!e.eat("*")&&(t.tokenize=w)(e,t)}},name:"css",helperType:"gss"})},"object"==typeof r&&"object"==typeof t?n(e("../../lib/codemirror")):"function"==typeof o&&o.amd?o(["../../lib/codemirror"],n):n(CodeMirror)},{"../../lib/codemirror":17}],19:[function(e,t,r){var n;n=function(p){"use strict";var i={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]};var o={};function m(e,t){var r,n=e.match(o[r=t]||(o[r]=new RegExp("\\s+"+r+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")));return n?/^\s*(.*?)\s*$/.exec(n[2])[1]:""}function g(e,t){return new RegExp((t?"^":"")+"","i")}function a(e,t){for(var r in e)for(var n=t[r]||(t[r]=[]),i=e[r],o=i.length-1;0<=o;o--)n.unshift(i[o])}p.defineMode("htmlmixed",function(u,e){var d=p.getMode(u,{name:"xml",htmlMode:!0,multilineTagIndentFactor:e.multilineTagIndentFactor,multilineTagIndentPastTag:e.multilineTagIndentPastTag}),f={},t=e&&e.tags,r=e&&e.scriptTypes;if(a(i,f),t&&a(t,f),r)for(var n=r.length-1;0<=n;n--)f.script.unshift(["type",r[n].matches,r[n].mode]);function h(e,t){var r,n=d.token(e,t.htmlState),i=/\btag\b/.test(n);if(i&&!/[<>\s\/]/.test(e.current())&&(r=t.htmlState.tagName&&t.htmlState.tagName.toLowerCase())&&f.hasOwnProperty(r))t.inTag=r+" ";else if(t.inTag&&i&&/>$/.test(e.current())){var o=/^([\S]+) (.*)/.exec(t.inTag);t.inTag=null;var a=">"==e.current()&&function(e,t){for(var r=0;r!?|~^@]/,m=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;function g(e,t,r){return n=e,i=r,t}function v(e,t){var i,r=e.next();if('"'==r||"'"==r)return t.tokenize=(i=r,function(e,t){var r,n=!1;if(a&&"@"==e.peek()&&e.match(m))return t.tokenize=v,g("jsonld-keyword","meta");for(;null!=(r=e.next())&&(r!=i||n);)n=!n&&"\\"==r;return n||(t.tokenize=v),g("string","string")}),t.tokenize(e,t);if("."==r&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return g("number","number");if("."==r&&e.match(".."))return g("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(r))return g(r);if("="==r&&e.eat(">"))return g("=>","operator");if("0"==r&&e.match(/^(?:x[\da-f]+|o[0-7]+|b[01]+)n?/i))return g("number","number");if(/\d/.test(r))return e.match(/^\d*(?:n|(?:\.\d*)?(?:[eE][+\-]?\d+)?)?/),g("number","number");if("/"==r)return e.eat("*")?(t.tokenize=y)(e,t):e.eat("/")?(e.skipToEnd(),g("comment","comment")):Ve(e,t,1)?(function(e){for(var t,r=!1,n=!1;null!=(t=e.next());){if(!r){if("/"==t&&!n)return;"["==t?n=!0:n&&"]"==t&&(n=!1)}r=!r&&"\\"==t}}(e),e.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/),g("regexp","string-2")):(e.eat("="),g("operator","operator",e.current()));if("`"==r)return(t.tokenize=b)(e,t);if("#"==r)return e.skipToEnd(),g("error","error");if(p.test(r))return">"==r&&t.lexical&&">"==t.lexical.type||(e.eat("=")?"!"!=r&&"="!=r||e.eat("="):/[<>*+\-]/.test(r)&&(e.eat(r),">"==r&&e.eat(r))),g("operator","operator",e.current());if(u.test(r)){e.eatWhile(u);var n=e.current();if("."!=t.lastType){if(s.propertyIsEnumerable(n)){var o=s[n];return g(o.type,o.style,n)}if("async"==n&&e.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/,!1))return g("async","keyword",n)}return g("variable","variable",n)}}function y(e,t){for(var r,n=!1;r=e.next();){if("/"==r&&n){t.tokenize=v;break}n="*"==r}return g("comment","comment")}function b(e,t){for(var r,n=!1;null!=(r=e.next());){if(!n&&("`"==r||"$"==r&&e.eat("{"))){t.tokenize=v;break}n=!n&&"\\"==r}return g("quasi","string-2",e.current())}var w="([{}])";function o(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var r=e.string.indexOf("=>",e.start);if(!(r<0)){if(c){var n=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(e.string.slice(e.start,r));n&&(r=n.index)}for(var i=0,o=!1,a=r-1;0<=a;--a){var l=e.string.charAt(a),s=w.indexOf(l);if(0<=s&&s<3){if(!i){++a;break}if(0==--i){"("==l&&(o=!0);break}}else if(3<=s&&s<6)++i;else if(u.test(l))o=!0;else{if(/["'\/]/.test(l))return;if(o&&!i){++a;break}}}o&&!i&&(t.fatArrowAt=a)}}var x={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,"jsonld-keyword":!0};function k(e,t,r,n,i,o){this.indented=e,this.column=t,this.type=r,this.prev=i,this.info=o,null!=n&&(this.align=n)}function C(e,t){for(var r=e.localVars;r;r=r.next)if(r.name==t)return!0;for(var n=e.context;n;n=n.prev)for(r=n.vars;r;r=r.next)if(r.name==t)return!0}var T={state:null,column:null,marked:null,cc:null};function S(){for(var e=arguments.length-1;0<=e;e--)T.cc.push(arguments[e])}function L(){return S.apply(null,arguments),!0}function M(e,t){for(var r=t;r;r=r.next)if(r.name==e)return!0;return!1}function r(e){var t=T.state;if(T.marked="def",t.context)if("var"==t.lexical.info&&t.context&&t.context.block){var r=function e(t,r){{if(r){if(r.block){var n=e(t,r.prev);return n?n==r.prev?r:new O(n,r.vars,!0):null}return M(t,r.vars)?r:new O(r.prev,new N(t,r.vars),!1)}return null}}(e,t.context);if(null!=r)return void(t.context=r)}else if(!M(e,t.localVars))return void(t.localVars=new N(e,t.localVars));d.globalVars&&!M(e,t.globalVars)&&(t.globalVars=new N(e,t.globalVars))}function A(e){return"public"==e||"private"==e||"protected"==e||"abstract"==e||"readonly"==e}function O(e,t,r){this.prev=e,this.vars=t,this.block=r}function N(e,t){this.name=e,this.next=t}var t=new N("this",new N("arguments",null));function _(){T.state.context=new O(T.state.context,T.state.localVars,!1),T.state.localVars=t}function E(){T.state.context=new O(T.state.context,T.state.localVars,!0),T.state.localVars=null}function D(){T.state.localVars=T.state.context.vars,T.state.context=T.state.context.prev}function F(n,i){var e=function(){var e=T.state,t=e.indented;if("stat"==e.lexical.type)t=e.lexical.indented;else for(var r=e.lexical;r&&")"==r.type&&r.align;r=r.prev)t=r.indented;e.lexical=new k(t,T.stream.column(),n,null,e.lexical,i)};return e.lex=!0,e}function W(){var e=T.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function z(r){return function e(t){return t==r?L():";"==r||"}"==t||")"==t||"]"==t?S():L(e)}}function P(e,t){return"var"==e?L(F("vardef",t),ve,z(";"),W):"keyword a"==e?L(F("form"),j,P,W):"keyword b"==e?L(F("form"),P,W):"keyword d"==e?T.stream.match(/^\s*$/,!1)?L():L(F("stat"),q,z(";"),W):"debugger"==e?L(z(";")):"{"==e?L(F("}"),E,oe,W,D):";"==e?L():"if"==e?("else"==T.state.lexical.info&&T.state.cc[T.state.cc.length-1]==W&&T.state.cc.pop()(),L(F("form"),j,P,W,Ce)):"function"==e?L(Oe):"for"==e?L(F("form"),Te,P,W):"class"==e||c&&"interface"==t?(T.marked="keyword",L(F("form"),Ee,W)):"variable"==e?c&&"declare"==t?(T.marked="keyword",L(P)):c&&("module"==t||"enum"==t||"type"==t)&&T.stream.match(/^\s*\w/,!1)?(T.marked="keyword","enum"==t?L(Ue):"type"==t?L(ce,z("operator"),ce,z(";")):L(F("form"),ye,z("{"),F("}"),oe,W,W)):c&&"namespace"==t?(T.marked="keyword",L(F("form"),I,oe,W)):c&&"abstract"==t?(T.marked="keyword",L(P)):L(F("stat"),J):"switch"==e?L(F("form"),j,z("{"),F("}","switch"),E,oe,W,W,D):"case"==e?L(I,z(":")):"default"==e?L(z(":")):"catch"==e?L(F("form"),_,H,P,W,D):"export"==e?L(F("stat"),ze,W):"import"==e?L(F("stat"),He,W):"async"==e?L(P):"@"==t?L(I,P):S(F("stat"),I,z(";"),W)}function H(e){if("("==e)return L(Ne,z(")"))}function I(e,t){return B(e,t,!1)}function R(e,t){return B(e,t,!0)}function j(e){return"("!=e?S():L(F(")"),I,z(")"),W)}function B(e,t,r){if(T.state.fatArrowAt==T.stream.start){var n=r?Y:$;if("("==e)return L(_,F(")"),ne(Ne,")"),W,z("=>"),n,D);if("variable"==e)return S(_,ye,z("=>"),n,D)}var i,o=r?K:U;return x.hasOwnProperty(e)?L(o):"function"==e?L(Oe,o):"class"==e||c&&"interface"==t?(T.marked="keyword",L(F("form"),_e,W)):"keyword c"==e||"async"==e?L(r?R:I):"("==e?L(F(")"),q,z(")"),W,o):"operator"==e||"spread"==e?L(r?R:I):"["==e?L(F("]"),qe,W,o):"{"==e?ie(ee,"}",null,o):"quasi"==e?S(V,o):"new"==e?L((i=r,function(e){return"."==e?L(i?Z:X):"variable"==e&&c?L(pe,i?K:U):S(i?R:I)})):"import"==e?L(I):L()}function q(e){return e.match(/[;\}\)\],]/)?S():S(I)}function U(e,t){return","==e?L(I):K(e,t,!1)}function K(e,t,r){var n=0==r?U:K,i=0==r?I:R;return"=>"==e?L(_,r?Y:$,D):"operator"==e?/\+\+|--/.test(t)||c&&"!"==t?L(n):c&&"<"==t&&T.stream.match(/^([^>]|<.*?>)*>\s*\(/,!1)?L(F(">"),ne(ce,">"),W,n):"?"==t?L(I,z(":"),i):L(i):"quasi"==e?S(V,n):";"!=e?"("==e?ie(R,")","call",n):"."==e?L(Q,n):"["==e?L(F("]"),q,z("]"),W,n):c&&"as"==t?(T.marked="keyword",L(ce,n)):"regexp"==e?(T.state.lastType=T.marked="operator",T.stream.backUp(T.stream.pos-T.stream.start-1),L(i)):void 0:void 0}function V(e,t){return"quasi"!=e?S():"${"!=t.slice(t.length-2)?L(V):L(I,G)}function G(e){if("}"==e)return T.marked="string-2",T.state.tokenize=b,L(V)}function $(e){return o(T.stream,T.state),S("{"==e?P:I)}function Y(e){return o(T.stream,T.state),S("{"==e?P:R)}function X(e,t){if("target"==t)return T.marked="keyword",L(U)}function Z(e,t){if("target"==t)return T.marked="keyword",L(K)}function J(e){return":"==e?L(W,P):S(U,z(";"),W)}function Q(e){if("variable"==e)return T.marked="property",L()}function ee(e,t){if("async"==e)return T.marked="property",L(ee);if("variable"==e||"keyword"==T.style){return T.marked="property","get"==t||"set"==t?L(te):(c&&T.state.fatArrowAt==T.stream.start&&(r=T.stream.match(/^\s*:\s*/,!1))&&(T.state.fatArrowAt=T.stream.pos+r[0].length),L(re));var r}else{if("number"==e||"string"==e)return T.marked=a?"property":T.style+" property",L(re);if("jsonld-keyword"==e)return L(re);if(c&&A(t))return T.marked="keyword",L(ee);if("["==e)return L(I,ae,z("]"),re);if("spread"==e)return L(R,re);if("*"==t)return T.marked="keyword",L(ee);if(":"==e)return S(re)}}function te(e){return"variable"!=e?S(re):(T.marked="property",L(Oe))}function re(e){return":"==e?L(R):"("==e?S(Oe):void 0}function ne(n,i,o){function a(e,t){if(o?-1"),ce):void 0}function ue(e){if("=>"==e)return L(ce)}function de(e,t){return"variable"==e||"keyword"==T.style?(T.marked="property",L(de)):"?"==t?L(de):":"==e?L(ce):"["==e?L(I,ae,z("]"),de):void 0}function fe(e,t){return"variable"==e&&T.stream.match(/^\s*[?:]/,!1)||"?"==t?L(fe):":"==e?L(ce):S(ce)}function he(e,t){return"<"==t?L(F(">"),ne(ce,">"),W,he):"|"==t||"."==e||"&"==t?L(ce):"["==e?L(z("]"),he):"extends"==t||"implements"==t?(T.marked="keyword",L(ce)):void 0}function pe(e,t){if("<"==t)return L(F(">"),ne(ce,">"),W,he)}function me(){return S(ce,ge)}function ge(e,t){if("="==t)return L(ce)}function ve(e,t){return"enum"==t?(T.marked="keyword",L(Ue)):S(ye,ae,xe,ke)}function ye(e,t){return c&&A(t)?(T.marked="keyword",L(ye)):"variable"==e?(r(t),L()):"spread"==e?L(ye):"["==e?ie(we,"]"):"{"==e?ie(be,"}"):void 0}function be(e,t){return"variable"!=e||T.stream.match(/^\s*:/,!1)?("variable"==e&&(T.marked="property"),"spread"==e?L(ye):"}"==e?S():"["==e?L(I,z("]"),z(":"),be):L(z(":"),ye,xe)):(r(t),L(xe))}function we(){return S(ye,xe)}function xe(e,t){if("="==t)return L(R)}function ke(e){if(","==e)return L(ve)}function Ce(e,t){if("keyword b"==e&&"else"==t)return L(F("form","else"),P,W)}function Te(e,t){return"await"==t?L(Te):"("==e?L(F(")"),Se,z(")"),W):void 0}function Se(e){return"var"==e?L(ve,z(";"),Me):";"==e?L(Me):"variable"==e?L(Le):S(I,z(";"),Me)}function Le(e,t){return"in"==t||"of"==t?(T.marked="keyword",L(I)):L(U,Me)}function Me(e,t){return";"==e?L(Ae):"in"==t||"of"==t?(T.marked="keyword",L(I)):S(I,z(";"),Ae)}function Ae(e){")"!=e&&L(I)}function Oe(e,t){return"*"==t?(T.marked="keyword",L(Oe)):"variable"==e?(r(t),L(Oe)):"("==e?L(_,F(")"),ne(Ne,")"),W,le,P,D):c&&"<"==t?L(F(">"),ne(me,">"),W,Oe):void 0}function Ne(e,t){return"@"==t&&L(I,Ne),"spread"==e?L(Ne):c&&A(t)?(T.marked="keyword",L(Ne)):S(ye,ae,xe)}function _e(e,t){return"variable"==e?Ee(e,t):De(e,t)}function Ee(e,t){if("variable"==e)return r(t),L(De)}function De(e,t){return"<"==t?L(F(">"),ne(me,">"),W,De):"extends"==t||"implements"==t||c&&","==e?("implements"==t&&(T.marked="keyword"),L(c?ce:I,De)):"{"==e?L(F("}"),Fe,W):void 0}function Fe(e,t){return"async"==e||"variable"==e&&("static"==t||"get"==t||"set"==t||c&&A(t))&&T.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(T.marked="keyword",L(Fe)):"variable"==e||"keyword"==T.style?(T.marked="property",L(c?We:Oe,Fe)):"["==e?L(I,ae,z("]"),c?We:Oe,Fe):"*"==t?(T.marked="keyword",L(Fe)):";"==e?L(Fe):"}"==e?L():"@"==t?L(I,Fe):void 0}function We(e,t){return"?"==t?L(We):":"==e?L(ce,xe):"="==t?L(R):S(Oe)}function ze(e,t){return"*"==t?(T.marked="keyword",L(Be,z(";"))):"default"==t?(T.marked="keyword",L(I,z(";"))):"{"==e?L(ne(Pe,"}"),Be,z(";")):S(P)}function Pe(e,t){return"as"==t?(T.marked="keyword",L(z("variable"))):"variable"==e?S(R,Pe):void 0}function He(e){return"string"==e?L():"("==e?S(I):S(Ie,Re,Be)}function Ie(e,t){return"{"==e?ie(Ie,"}"):("variable"==e&&r(t),"*"==t&&(T.marked="keyword"),L(je))}function Re(e){if(","==e)return L(Ie,Re)}function je(e,t){if("as"==t)return T.marked="keyword",L(Ie)}function Be(e,t){if("from"==t)return T.marked="keyword",L(I)}function qe(e){return"]"==e?L():S(ne(R,"]"))}function Ue(){return S(F("form"),ye,z("{"),F("}"),ne(Ke,"}"),W,W)}function Ke(){return S(ye,xe)}function Ve(e,t,r){return t.tokenize==v&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(t.lastType)||"quasi"==t.lastType&&/\{\s*$/.test(e.string.slice(0,e.pos-(r||0)))}return W.lex=D.lex=!0,{startState:function(e){var t={tokenize:v,lastType:"sof",cc:[],lexical:new k((e||0)-f,0,"block",!1),localVars:d.localVars,context:d.localVars&&new O(null,null,!1),indented:e||0};return d.globalVars&&"object"==typeof d.globalVars&&(t.globalVars=d.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),o(e,t)),t.tokenize!=y&&e.eatSpace())return null;var r=t.tokenize(e,t);return"comment"==n?r:(t.lastType="operator"!=n||"++"!=i&&"--"!=i?n:"incdec",function(e,t,r,n,i){var o=e.cc;for(T.state=e,T.stream=i,T.marked=null,T.cc=o,T.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;)if((o.length?o.pop():l?I:P)(r,n)){for(;o.length&&o[o.length-1].lex;)o.pop()();return T.marked?T.marked:"variable"==r&&C(e,n)?"variable-2":t}}(t,r,n,i,e))},indent:function(e,t){if(e.tokenize==y)return Ge.Pass;if(e.tokenize!=v)return 0;var r,n=t&&t.charAt(0),i=e.lexical;if(!/^\s*else\b/.test(t))for(var o=e.cc.length-1;0<=o;--o){var a=e.cc[o];if(a==W)i=i.prev;else if(a!=Ce)break}for(;("stat"==i.type||"form"==i.type)&&("}"==n||(r=e.cc[e.cc.length-1])&&(r==U||r==K)&&!/^[,\.=+\-*:?[\(]/.test(t));)i=i.prev;h&&")"==i.type&&"stat"==i.prev.type&&(i=i.prev);var l,s,c=i.type,u=n==c;return"vardef"==c?i.indented+("operator"==e.lastType||","==e.lastType?i.info.length+1:0):"form"==c&&"{"==n?i.indented:"form"==c?i.indented+f:"stat"==c?i.indented+(s=t,"operator"==(l=e).lastType||","==l.lastType||p.test(s.charAt(0))||/[,.]/.test(s.charAt(0))?h||f:0):"switch"!=i.info||u||0==d.doubleIndentSwitch?i.align?i.column+(u?0:1):i.indented+(u?0:f):i.indented+(/^(?:case|default)\b/.test(t)?f:2*f)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:l?null:"/*",blockCommentEnd:l?null:"*/",blockCommentContinue:l?null:" * ",lineComment:l?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:l?"json":"javascript",jsonldMode:a,jsonMode:l,expressionAllowed:Ve,skipExpression:function(e){var t=e.cc[e.cc.length-1];t!=I&&t!=R||e.cc.pop()}}}),Ge.registerHelper("wordChars","javascript",/[\w$]/),Ge.defineMIME("text/javascript","javascript"),Ge.defineMIME("text/ecmascript","javascript"),Ge.defineMIME("application/javascript","javascript"),Ge.defineMIME("application/x-javascript","javascript"),Ge.defineMIME("application/ecmascript","javascript"),Ge.defineMIME("application/json",{name:"javascript",json:!0}),Ge.defineMIME("application/x-json",{name:"javascript",json:!0}),Ge.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),Ge.defineMIME("text/typescript",{name:"javascript",typescript:!0}),Ge.defineMIME("application/typescript",{name:"javascript",typescript:!0})},"object"==typeof r&&"object"==typeof t?n(e("../../lib/codemirror")):"function"==typeof o&&o.amd?o(["../../lib/codemirror"],n):n(CodeMirror)},{"../../lib/codemirror":17}],21:[function(e,t,r){var n;n=function(C){"use strict";var T={autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0},S={autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,allowMissingTagName:!1,caseFold:!1};C.defineMode("xml",function(e,t){var a,o,l=e.indentUnit,s={},r=t.htmlMode?T:S;for(var n in r)s[n]=r[n];for(var n in t)s[n]=t[n];function c(t,r){function e(e){return(r.tokenize=e)(t,r)}var n=t.next();return"<"==n?t.eat("!")?t.eat("[")?t.match("CDATA[")?e(i("atom","]]>")):null:t.match("--")?e(i("comment","--\x3e")):t.match("DOCTYPE",!0,!0)?(t.eatWhile(/[\w\._\-]/),e(function n(i){return function(e,t){for(var r;null!=(r=e.next());){if("<"==r)return t.tokenize=n(i+1),t.tokenize(e,t);if(">"==r){if(1!=i)return t.tokenize=n(i-1),t.tokenize(e,t);t.tokenize=c;break}}return"meta"}}(1))):null:t.eat("?")?(t.eatWhile(/[\w\._\-]/),r.tokenize=i("meta","?>"),"meta"):(a=t.eat("/")?"closeTag":"openTag",r.tokenize=u,"tag bracket"):"&"!=n?(t.eatWhile(/[^&<]/),null):(t.eat("#")?t.eat("x")?t.eatWhile(/[a-fA-F\d]/)&&t.eat(";"):t.eatWhile(/[\d]/)&&t.eat(";"):t.eatWhile(/[\w\.\-:]/)&&t.eat(";"))?"atom":"error"}function u(e,t){var r=e.next();if(">"==r||"/"==r&&e.eat(">"))return t.tokenize=c,a=">"==r?"endTag":"selfcloseTag","tag bracket";if("="==r)return a="equals",null;if("<"!=r)return/[\'\"]/.test(r)?(t.tokenize=(n=r,(i=function(e,t){for(;!e.eol();)if(e.next()==n){t.tokenize=u;break}return"string"}).isInAttribute=!0,i),t.stringStartCol=e.column(),t.tokenize(e,t)):(e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word");t.tokenize=c,t.state=p,t.tagName=t.tagStart=null;var n,i,o=t.tokenize(e,t);return o?o+" tag error":"tag error"}function i(r,n){return function(e,t){for(;!e.eol();){if(e.match(n)){t.tokenize=c;break}e.next()}return r}}function d(e,t,r){this.prev=e.context,this.tagName=t,this.indent=e.indented,this.startOfLine=r,(s.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)&&(this.noIndent=!0)}function f(e){e.context&&(e.context=e.context.prev)}function h(e,t){for(var r;;){if(!e.context)return;if(r=e.context.tagName,!s.contextGrabbers.hasOwnProperty(r)||!s.contextGrabbers[r].hasOwnProperty(t))return;f(e)}}function p(e,t,r){return"openTag"==e?(r.tagStart=t.column(),m):"closeTag"==e?g:p}function m(e,t,r){return"word"==e?(r.tagName=t.current(),o="tag",b):s.allowMissingTagName&&"endTag"==e?(o="tag bracket",b(e,t,r)):(o="error",m)}function g(e,t,r){if("word"!=e)return s.allowMissingTagName&&"endTag"==e?(o="tag bracket",v(e,t,r)):(o="error",y);var n=t.current();return r.context&&r.context.tagName!=n&&s.implicitlyClosed.hasOwnProperty(r.context.tagName)&&f(r),r.context&&r.context.tagName==n||!1===s.matchClosing?(o="tag",v):(o="tag error",y)}function v(e,t,r){return"endTag"!=e?(o="error",v):(f(r),p)}function y(e,t,r){return o="error",v(e,0,r)}function b(e,t,r){if("word"==e)return o="attribute",w;if("endTag"!=e&&"selfcloseTag"!=e)return o="error",b;var n=r.tagName,i=r.tagStart;return r.tagName=r.tagStart=null,"selfcloseTag"==e||s.autoSelfClosers.hasOwnProperty(n)?h(r,n):(h(r,n),r.context=new d(r,n,i==r.indented)),p}function w(e,t,r){return"equals"==e?x:(s.allowMissing||(o="error"),b(e,0,r))}function x(e,t,r){return"string"==e?k:"word"==e&&s.allowUnquoted?(o="string",b):(o="error",b(e,0,r))}function k(e,t,r){return"string"==e?k:b(e,0,r)}return c.isInText=!0,{startState:function(e){var t={tokenize:c,state:p,indented:e||0,tagName:null,tagStart:null,context:null};return null!=e&&(t.baseIndent=e),t},token:function(e,t){if(!t.tagName&&e.sol()&&(t.indented=e.indentation()),e.eatSpace())return null;a=null;var r=t.tokenize(e,t);return(r||a)&&"comment"!=r&&(o=null,t.state=t.state(a||r,e,t),o&&(r="error"==o?r+" error":o)),r},indent:function(e,t,r){var n=e.context;if(e.tokenize.isInAttribute)return e.tagStart==e.indented?e.stringStartCol+1:e.indented+l;if(n&&n.noIndent)return C.Pass;if(e.tokenize!=u&&e.tokenize!=c)return r?r.match(/^(\s*)/)[0].length:0;if(e.tagName)return!1!==s.multilineTagIndentPastTag?e.tagStart+e.tagName.length+2:e.tagStart+l*(s.multilineTagIndentFactor||1);if(s.alignCDATA&&/$/,blockCommentStart:"\x3c!--",blockCommentEnd:"--\x3e",configuration:s.htmlMode?"html":"xml",helperType:s.htmlMode?"html":"xml",skipAttribute:function(e){e.state==x&&(e.state=b)}}}),C.defineMIME("text/xml","xml"),C.defineMIME("application/xml","xml"),C.mimeModes.hasOwnProperty("text/html")||C.defineMIME("text/html",{name:"xml",htmlMode:!0})},"object"==typeof r&&"object"==typeof t?n(e("../../lib/codemirror")):"function"==typeof o&&o.amd?o(["../../lib/codemirror"],n):n(CodeMirror)},{"../../lib/codemirror":17}],22:[function(e,t,r){t.exports={prettyPrint:function(e,t){var r,n,i,o,a,c;for(n=(t=t||{}).indent_size||4,i=t.indent_char||" ",a=t.brace_style||"collapse",o=0==t.max_char?1/0:t.max_char||70,c=t.unformatted||["a","span","bdo","em","strong","dfn","code","samp","kbd","var","cite","abbr","acronym","q","sub","sup","tt","i","b","big","small","u","s","strike","font","ins","del","pre","address","dt","h1","h2","h3","h4","h5","h6"],(r=new function(){return this.pos=0,this.token="",this.current_mode="CONTENT",this.tags={parent:"parent1",parentcount:1,parent1:""},this.tag_type="",this.token_text=this.last_token=this.last_text=this.token_type="",this.Utils={whitespace:"\n\r\t ".split(""),single_token:"br,input,link,meta,!doctype,basefont,base,area,hr,wbr,param,img,isindex,?xml,embed,?php,?,?=".split(","),extra_liners:"head,body,/html".split(","),in_array:function(e,t){for(var r=0;r=this.input.length)return t.length?t.join(""):["","TK_EOF"];if(e=this.input.charAt(this.pos),this.pos++,this.line_char_count++,this.Utils.in_array(e,this.Utils.whitespace))t.length&&(r=!0),this.line_char_count--;else{if(r){if(this.line_char_count>=this.max_char){t.push("\n");for(var n=0;n","igm");r.lastIndex=this.pos;var n=r.exec(this.input),i=n?n.index:this.input.length;return this.pos=this.input.length)return n.length?n.join(""):["","TK_EOF"];r=this.input.charAt(this.pos),this.pos++,this.line_char_count++,this.Utils.in_array(r,this.Utils.whitespace)?(i=!0,this.line_char_count--):("'"!==r&&'"'!==r||n[1]&&"!"===n[1]||(r+=this.get_unformatted(r),i=!0),"="===r&&(i=!1),n.length&&"="!==n[n.length-1]&&">"!==r&&i&&(this.line_char_count>=this.max_char?(this.print_newline(!1,n),this.line_char_count=0):(n.push(" "),this.line_char_count++),i=!1),"<"===r&&(e=this.pos-1),n.push(r))}while(">"!==r);var o,a=n.join("");o=-1!=a.indexOf(" ")?a.indexOf(" "):a.indexOf(">");var l=a.substring(1,o).toLowerCase();if("/"===a.charAt(a.length-2)||this.Utils.in_array(l,this.Utils.single_token))this.tag_type="SINGLE";else if("script"===l)this.record_tag(l),this.tag_type="SCRIPT";else if("style"===l)this.record_tag(l),this.tag_type="STYLE";else if(this.Utils.in_array(l,c)){var s=this.get_unformatted("",a);n.push(s),0",a):this.get_unformatted("--\x3e",a),n.push(s),this.tag_type="SINGLE"):("/"===l.charAt(0)?(this.retrieve_tag(l.substring(1)),this.tag_type="END"):(this.record_tag(l),this.tag_type="START"),this.Utils.in_array(l,this.Utils.extra_liners)&&this.print_newline(!0,this.output));return n.join("")},this.get_unformatted=function(e,t){if(t&&-1!=t.toLowerCase().indexOf(e))return"";var r="",n="",i=!0;do{if(this.pos>=this.input.length)return n;if(r=this.input.charAt(this.pos),this.pos++,this.Utils.in_array(r,this.Utils.whitespace)){if(!i){this.line_char_count--;continue}if("\n"===r||"\r"===r){n+="\n",this.line_char_count=0;continue}}n+=r,this.line_char_count++,i=!0}while(-1==n.toLowerCase().indexOf(e));return n},this.get_token=function(){var e;if("TK_TAG_SCRIPT"!==this.last_token&&"TK_TAG_STYLE"!==this.last_token)return"CONTENT"===this.current_mode?"string"!=typeof(e=this.get_content())?e:[e,"TK_CONTENT"]:"TAG"===this.current_mode?"string"!=typeof(e=this.get_tag())?e:[e,"TK_TAG_"+this.tag_type]:void 0;var t=this.last_token.substr(7);return"string"!=typeof(e=this.get_contents_to(t))?e:[e,"TK_"+t]},this.get_full_indent=function(e){return(e=this.indent_level+e||0)<1?"":Array(e+1).join(this.indent_string)},this.printer=function(e,t,r,n,i){this.input=e||"",this.output=[],this.indent_character=t,this.indent_string="",this.indent_size=r,this.brace_style=i,this.indent_level=0,this.max_char=n;for(var o=this.line_char_count=0;o field\n * @param config\n * @returns {*}\n */\n\n generators.select = function (config) {\n var attributes = {\n name: config.name(),\n required: config.required()\n };\n var hasSelection = false;\n var options = config.choices().map(function (choice) {\n if (choice.selected()) {\n hasSelection = true;\n }\n\n return m('option', {\n value: choice.value() !== choice.label() ? choice.value() : undefined,\n \"selected\": choice.selected(),\n oncreate: setAttributes\n }, choice.label());\n });\n var placeholder = config.placeholder();\n\n if (placeholder.length > 0) {\n options.unshift(m('option', {\n 'disabled': true,\n 'value': '',\n 'selected': !hasSelection,\n oncreate: setAttributes\n }, placeholder));\n }\n\n return m('select', attributes, options);\n };\n\n generators['terms-checkbox'] = function (config) {\n var label;\n\n if (config.link().length > 0) {\n label = m('a', {\n href: config.link(),\n target: \"_blank\"\n }, config.label());\n } else {\n label = config.label();\n }\n\n return m('label', [m('input', {\n name: config.name(),\n type: 'checkbox',\n value: config.value(),\n required: config.required()\n }), ' ', label]);\n };\n /**\n * Generates a checkbox or radio type input field.\n *\n * @param config\n * @returns {*}\n */\n\n\n generators.checkbox = function (config) {\n var fields = config.choices().map(function (choice) {\n var name = config.name() + (config.type() === 'checkbox' ? '[]' : '');\n var required = config.required() && config.type() === 'radio';\n return m('label', [m('input', {\n name: name,\n type: config.type(),\n value: choice.value(),\n checked: choice.selected(),\n required: required,\n oncreate: setAttributes\n }), ' ', m('span', choice.label())]);\n });\n return fields;\n };\n\n generators.radio = generators.checkbox;\n /**\n * Generates a default field\n *\n * - text, url, number, email, date\n *\n * @param config\n * @returns {*}\n */\n\n generators['default'] = function (config) {\n var attributes = {\n type: config.type()\n };\n\n if (config.name()) {\n attributes.name = config.name();\n }\n\n if (config.min()) {\n attributes.min = config.min();\n }\n\n if (config.max()) {\n attributes.max = config.max();\n }\n\n if (config.value().length > 0) {\n attributes.value = config.value();\n }\n\n if (config.placeholder().length > 0) {\n attributes.placeholder = config.placeholder();\n }\n\n attributes.required = config.required();\n attributes.oncreate = setAttributes;\n return m('input', attributes);\n };\n /**\n * Generates an HTML string based on a field (config) object\n *\n * @param config\n * @returns {*}\n */\n\n\n function generate(config) {\n var label,\n field,\n htmlTemplate,\n html,\n vdom = document.createElement('div');\n label = config.label().length > 0 && config.showLabel() ? m(\"label\", {}, config.label()) : '';\n field = typeof generators[config.type()] === \"function\" ? generators[config.type()](config) : generators['default'](config);\n htmlTemplate = config.wrap() ? m('p', [label, field]) : [label, field]; // render in vdom\n\n m.render(vdom, htmlTemplate); // prettify html\n\n html = htmlutil.prettyPrint(vdom.innerHTML);\n return html + \"\\n\";\n }\n\n return generate;\n};\n\nmodule.exports = g;\n\n},{\"html\":22}],4:[function(require,module,exports){\n\"use strict\";\n\nvar FieldHelper = function FieldHelper(m, tabs, editor, fields, events, i18n) {\n 'use strict';\n\n var generate = require('./field-generator.js')(m);\n\n var overlay = require('./overlay.js')(m, i18n);\n\n var forms = require('./field-forms.js')(m, i18n);\n\n var fieldConfig;\n editor.on('blur', m.redraw);\n /**\n * Choose a field to open the helper form for\n *\n * @param index\n * @returns {*}\n */\n\n function setActiveField(index) {\n fieldConfig = fields.get(index); // if this hidden field has choices (hidden groups), glue them together by their label.\n\n if (fieldConfig && fieldConfig.choices().length > 0) {\n fieldConfig.value(fieldConfig.choices().map(function (c) {\n return c.label();\n }).join('|'));\n }\n\n m.redraw();\n }\n /**\n * Controller\n */\n\n\n function controller() {}\n /**\n * Create HTML based on current config object\n */\n\n\n function createFieldHTMLAndAddToForm() {\n // generate html\n var html = generate(fieldConfig); // add to editor\n\n editor.insert(html); // reset field form\n\n setActiveField(''); // redraw\n\n m.redraw();\n }\n /**\n * View\n * @returns {*}\n */\n\n\n function view() {\n // build DOM for fields choice\n var fieldCategories = fields.getCategories();\n var availableFields = fields.getAll();\n var fieldsChoice = m(\"div.available-fields.small-margin\", [m(\"h4\", i18n.chooseField), fieldCategories.map(function (category) {\n var categoryFields = availableFields.filter(function (f) {\n return f.category === category;\n });\n\n if (!categoryFields.length) {\n return;\n }\n\n return m(\"div.tiny-margin\", [m(\"strong\", category), // render fields\n categoryFields.map(function (field) {\n var className = \"button\";\n\n if (field.forceRequired()) {\n className += \" is-required\";\n }\n\n var inForm = field.inFormContent();\n\n if (inForm !== null) {\n className += \" \" + (inForm ? 'in-form' : 'not-in-form');\n }\n\n return m(\"button\", {\n className: className,\n type: 'button',\n onclick: m.withAttr(\"value\", setActiveField),\n value: field.index\n }, field.title());\n })]);\n })]); // build DOM for overlay\n\n var form = null;\n\n if (fieldConfig) {\n form = m(overlay( // field wizard\n m(\"div.field-wizard\", [//heading\n m(\"h3\", [fieldConfig.title(), fieldConfig.forceRequired() ? m('span.red', '*') : '', fieldConfig.name().length ? m(\"code\", fieldConfig.name()) : '']), // help text\n fieldConfig.help().length ? m('p', m.trust(fieldConfig.help())) : '', // actual form\n forms.render(fieldConfig), // add to form button\n m(\"p\", [m(\"button\", {\n \"class\": \"button-primary\",\n type: \"button\",\n onkeydown: function onkeydown(e) {\n e = e || window.event;\n\n if (e.keyCode == 13) {\n createFieldHTMLAndAddToForm();\n }\n },\n onclick: createFieldHTMLAndAddToForm\n }, i18n.addToForm)])]), setActiveField));\n }\n\n return [fieldsChoice, form];\n } // expose some variables\n\n\n return {\n view: view,\n controller: controller\n };\n};\n\nmodule.exports = FieldHelper;\n\n},{\"./field-forms.js\":2,\"./field-generator.js\":3,\"./overlay.js\":10}],5:[function(require,module,exports){\n\"use strict\";\n\nvar FieldFactory = function FieldFactory(fields, i18n) {\n 'use strict';\n /**\n * Array of registered fields\n *\n * @type {Array}\n */\n\n var registeredFields = [];\n /**\n * Reset all previously registered fields\n */\n\n function reset() {\n // clear all of our fields\n registeredFields.forEach(fields.deregister);\n }\n /**\n * Helper function to quickly register a field and store it in local scope\n *\n * @param {object} data\n * @param {boolean} sticky\n */\n\n\n function register(category, data, sticky) {\n var field = fields.register(category, data);\n\n if (!sticky) {\n registeredFields.push(field);\n }\n }\n /**\n * Normalizes the field type which is passed by Newsletter\n *\n * @param type\n * @returns {*}\n */\n\n\n function getFieldType(type) {\n var map = {\n 'phone': 'tel',\n 'dropdown': 'select',\n 'checkboxes': 'checkbox',\n 'birthday': 'text'\n };\n return typeof map[type] !== \"undefined\" ? map[type] : type;\n }\n /**\n * Register the various fields for a merge var\n *\n * @param mergeField\n * @returns {boolean}\n */\n\n\n function registerMergeField(mergeField) {\n var category = i18n.listFields;\n var fieldType = getFieldType(mergeField.field_type); // name, type, title, value, required, label, placeholder, choices, wrap\n\n var data = {\n name: mergeField.tag,\n title: mergeField.name,\n required: mergeField.required,\n forceRequired: mergeField.required,\n type: fieldType,\n choices: mergeField.choices,\n acceptsMultipleValues: false // merge fields never accept multiple values.\n\n };\n\n if (data.type !== 'address') {\n register(category, data, false);\n } else {\n register(category, {\n name: data.name + '[addr1]',\n type: 'text',\n newsletterType: 'address',\n title: i18n.streetAddress\n });\n register(category, {\n name: data.name + '[city]',\n type: 'text',\n newsletterType: 'address',\n title: i18n.city\n });\n register(category, {\n name: data.name + '[state]',\n type: 'text',\n newsletterType: 'address',\n title: i18n.state\n });\n register(category, {\n name: data.name + '[zip]',\n type: 'text',\n newsletterType: 'address',\n title: i18n.zip\n });\n register(category, {\n name: data.name + '[country]',\n type: 'select',\n newsletterType: 'address',\n title: i18n.country,\n choices: nl4wp_vars.countries\n });\n }\n\n return true;\n }\n /**\n * Register a field for a Newsletter grouping\n *\n * @param interestCategory\n */\n\n\n function registerInterestCategory(interestCategory) {\n var category = i18n.interestCategories;\n var fieldType = getFieldType(interestCategory.field_type);\n var data = {\n title: interestCategory.name,\n name: 'INTERESTS[' + interestCategory.id + ']',\n type: fieldType,\n choices: interestCategory.interests,\n acceptsMultipleValues: fieldType === 'checkbox'\n };\n register(category, data, false);\n }\n /**\n * Register all fields belonging to a list\n *\n * @param list\n */\n\n\n function registerListFields(list) {\n // make sure EMAIL && public fields come first\n list.merge_fields = list.merge_fields.sort(function (a, b) {\n if (a.tag === 'EMAIL' || a.public && !b.public) {\n return -1;\n }\n\n if (!a.public && b.public) {\n return 1;\n }\n\n return 0;\n }); // loop through merge vars\n\n list.merge_fields.forEach(registerMergeField); // loop through groupings\n\n list.interest_categories.forEach(registerInterestCategory);\n }\n /**\n * Register all lists fields\n *\n * @param lists\n */\n\n\n function registerListsFields(lists) {\n reset();\n lists.forEach(registerListFields);\n }\n\n function registerCustomFields(lists) {\n var choices,\n category = i18n.formFields; // register submit button\n\n register(category, {\n name: '',\n value: i18n.subscribe,\n type: \"submit\",\n title: i18n.submitButton\n }, true); // register lists choice field\n\n choices = {};\n\n for (var key in lists) {\n choices[lists[key].id] = lists[key].name;\n }\n\n register(category, {\n name: '_nl4wp_lists',\n type: 'checkbox',\n title: i18n.listChoice,\n choices: choices,\n help: i18n.listChoiceDescription,\n acceptsMultipleValues: true\n }, true);\n choices = {\n 'subscribe': \"Subscribe\",\n 'unsubscribe': \"Unsubscribe\"\n };\n register(category, {\n name: '_nl4wp_action',\n type: 'radio',\n title: i18n.formAction,\n choices: choices,\n value: 'subscribe',\n help: i18n.formActionDescription\n }, true);\n register(category, {\n name: 'AGREE_TO_TERMS',\n value: 1,\n type: \"terms-checkbox\",\n label: i18n.agreeToTerms,\n title: i18n.agreeToTermsShort,\n showLabel: false,\n required: true\n }, true);\n }\n /**\n * Expose some methods\n */\n\n\n return {\n 'registerCustomFields': registerCustomFields,\n 'registerListFields': registerListFields,\n 'registerListsFields': registerListsFields\n };\n};\n\nmodule.exports = FieldFactory;\n\n},{}],6:[function(require,module,exports){\n'use strict';\n\nvar prop = require(\"mithril/stream\");\n\nmodule.exports = function (m, events) {\n var timeout;\n var fields = [];\n var categories = [];\n /**\n * @internal\n *\n *\n * @param data\n * @constructor\n */\n\n var Field = function Field(data) {\n this.name = prop(data.name);\n this.title = prop(data.title || data.name);\n this.type = prop(data.type);\n this.newsletterType = prop(data.newsletterType || '');\n this.label = prop(data.label || data.title || '');\n this.showLabel = prop(data.showLabel !== undefined ? data.showLabel : true);\n this.value = prop(data.value || '');\n this.placeholder = prop(data.placeholder || '');\n this.required = prop(data.required || false);\n this.forceRequired = prop(data.forceRequired || false);\n this.wrap = prop(data.wrap !== undefined ? data.wrap : true);\n this.min = prop(data.min || null);\n this.max = prop(data.max || null);\n this.help = prop(data.help || '');\n this.choices = prop(data.choices || []);\n this.inFormContent = prop(null);\n this.acceptsMultipleValues = data.acceptsMultipleValues;\n this.link = prop(data.link || '');\n\n this.selectChoice = function (value) {\n var field = this;\n this.choices(this.choices().map(function (choice) {\n if (choice.value() === value) {\n choice.selected(true);\n } else {\n // only checkboxes allow for multiple selections\n if (field.type() !== 'checkbox') {\n choice.selected(false);\n }\n }\n\n return choice;\n }));\n };\n };\n /**\n * @internal\n *\n * @param data\n * @constructor\n */\n\n\n var FieldChoice = function FieldChoice(data) {\n this.label = prop(data.label);\n this.title = prop(data.title || data.label);\n this.selected = prop(data.selected || false);\n this.value = prop(data.value || data.label);\n };\n /**\n * Creates FieldChoice objects from an (associative) array of data objects\n *\n * @param data\n * @returns {Array}\n */\n\n\n function createChoices(data) {\n var choices = [];\n\n if (typeof data.map === \"function\") {\n choices = data.map(function (choiceLabel) {\n return new FieldChoice({\n label: choiceLabel\n });\n });\n } else {\n choices = Object.keys(data).map(function (key) {\n var choiceLabel = data[key];\n return new FieldChoice({\n label: choiceLabel,\n value: key\n });\n });\n }\n\n return choices;\n }\n /**\n * Factory method\n *\n * @api\n *\n * @param data\n * @returns {Field}\n */\n\n\n function register(category, data) {\n var field;\n var existingField = getAllWhere('name', data.name).shift(); // a field with the same \"name\" already exists\n\n if (existingField) {\n // update \"required\" status\n if (!existingField.forceRequired() && data.forceRequired) {\n existingField.forceRequired(true);\n } // bail\n\n\n return undefined;\n } // array of choices given? convert to FieldChoice objects\n\n\n if (data.choices) {\n data.choices = createChoices(data.choices);\n\n if (data.value) {\n data.choices = data.choices.map(function (choice) {\n if (choice.value() === data.value) {\n choice.selected(true);\n }\n\n return choice;\n });\n }\n } // register category\n\n\n if (categories.indexOf(category) < 0) {\n categories.push(category);\n } // create Field object\n\n\n field = new Field(data);\n field.category = category; // add to array\n\n fields.push(field); // redraw view\n\n timeout && window.clearTimeout(timeout);\n timeout = window.setTimeout(m.redraw, 200); // trigger event\n\n events.trigger('fields.change');\n return field;\n }\n /**\n * @api\n *\n * @param field\n */\n\n\n function deregister(field) {\n var index = fields.indexOf(field);\n\n if (index > -1) {\n delete fields[index];\n m.redraw();\n }\n }\n /**\n * Get a field config object\n *\n * @param name\n * @returns {*}\n */\n\n\n function get(name) {\n return fields[name];\n }\n /**\n * Get all field config objects\n *\n * @returns {Array|*}\n */\n\n\n function getAll() {\n // rebuild index property on all fields\n fields = fields.map(function (f, i) {\n f.index = i;\n return f;\n });\n return fields;\n }\n\n function getCategories() {\n return categories;\n }\n /**\n * Get all fields where a property matches the given value\n *\n * @param searchKey\n * @param searchValue\n * @returns {Array|*}\n */\n\n\n function getAllWhere(searchKey, searchValue) {\n return fields.filter(function (field) {\n return field[searchKey]() === searchValue;\n });\n }\n /**\n * Exposed methods\n */\n\n\n return {\n 'get': get,\n 'getAll': getAll,\n 'getCategories': getCategories,\n 'deregister': deregister,\n 'register': register,\n 'getAllWhere': getAllWhere\n };\n};\n\n},{\"mithril/stream\":23}],7:[function(require,module,exports){\n'use strict'; // load CodeMirror & plugins\n\nvar CodeMirror = require('codemirror');\n\nrequire('codemirror/mode/xml/xml');\n\nrequire('codemirror/mode/javascript/javascript');\n\nrequire('codemirror/mode/css/css');\n\nrequire('codemirror/mode/htmlmixed/htmlmixed');\n\nrequire('codemirror/addon/fold/xml-fold.js');\n\nrequire('codemirror/addon/edit/matchtags.js');\n\nrequire('codemirror/addon/edit/closetag.js');\n\nrequire('codemirror/addon/selection/active-line.js');\n\nrequire('codemirror/addon/edit/matchbrackets.js');\n/* variables */\n\n\nvar FormEditor = {};\n\nvar _dom = document.createElement('form');\n\nvar domDirty = false;\nvar editor;\nvar element = document.getElementById('nl4wp-form-content');\nvar previewFrame = document.getElementById('nl4wp-form-preview');\nvar previewDom;\nvar templateRegex = /\\{[^{}]+\\}/g;\n/* functions */\n\nfunction setPreviewDom() {\n var frameContent = previewFrame.contentDocument || previewFrame.contentWindow.document;\n previewDom = frameContent.querySelector('.nl4wp-form-fields');\n\n if (previewDom) {\n updatePreview();\n }\n}\n\nfunction updatePreview() {\n var markup = FormEditor.getValue(); // replace template tags (twice, to allow for nested tags)\n\n markup = markup.replace(templateRegex, '').replace(templateRegex, ''); // update dom\n\n previewDom.innerHTML = markup;\n previewDom.dispatchEvent(new Event('nl4wp-refresh'));\n}\n\nwindow.addEventListener('load', function () {\n CodeMirror.signal(editor, \"change\");\n}); // set domDirty to true everytime the \"change\" event fires (a lot..)\n\nelement.addEventListener('change', function () {\n domDirty = true;\n updatePreview();\n});\n\nfunction dom() {\n if (domDirty) {\n _dom.innerHTML = FormEditor.getValue().toLowerCase();\n domDirty = false;\n }\n\n return _dom;\n}\n\nFormEditor.getValue = function () {\n return editor ? editor.getValue() : element.value;\n};\n\nFormEditor.query = function (query) {\n return dom().querySelectorAll(query.toLowerCase());\n};\n\nFormEditor.containsField = function (fieldName) {\n return dom().elements.namedItem(fieldName.toLowerCase()) !== null;\n};\n\nFormEditor.insert = function (html) {\n if (editor) {\n editor.replaceSelection(html);\n editor.focus();\n } else {\n element.value += html;\n }\n};\n\nFormEditor.on = function (event, callback) {\n if (editor) {\n // translate \"input\" event for CodeMirror\n event = event === 'input' ? 'changes' : event;\n return editor.on(event, callback);\n }\n\n return element.addEventListener(event, callback);\n};\n\nFormEditor.refresh = function () {\n editor && editor.refresh();\n};\n/* bootstrap */\n\n\n_dom.innerHTML = element.value.toLowerCase();\n\nif (CodeMirror) {\n editor = CodeMirror.fromTextArea(element, {\n selectionPointer: true,\n mode: \"htmlmixed\",\n htmlMode: true,\n autoCloseTags: true,\n autoRefresh: true,\n styleActiveLine: true,\n matchBrackets: true,\n matchTags: {\n bothTags: true\n }\n }); // dispatch regular \"change\" on element event every time editor changes (IE9+ only)\n\n window.dispatchEvent && editor.on('change', function () {\n if (typeof Event === \"function\") {\n // Create a new 'change' event\n var event = new Event('change', {\n bubbles: true\n });\n element.dispatchEvent(event);\n }\n });\n}\n\npreviewFrame.addEventListener('load', setPreviewDom);\nsetPreviewDom.call();\n/* exports */\n\nmodule.exports = FormEditor;\n\n},{\"codemirror\":17,\"codemirror/addon/edit/closetag.js\":12,\"codemirror/addon/edit/matchbrackets.js\":13,\"codemirror/addon/edit/matchtags.js\":14,\"codemirror/addon/fold/xml-fold.js\":15,\"codemirror/addon/selection/active-line.js\":16,\"codemirror/mode/css/css\":18,\"codemirror/mode/htmlmixed/htmlmixed\":19,\"codemirror/mode/javascript/javascript\":20,\"codemirror/mode/xml/xml\":21}],8:[function(require,module,exports){\n\"use strict\";\n\nvar FormWatcher = function FormWatcher(m, editor, settings, fields, events, helpers) {\n 'use strict';\n\n var requiredFieldsInput = document.getElementById('required-fields');\n\n function updateFields() {\n fields.getAll().forEach(function (field) {\n // don't run for empty field names\n if (field.name().length <= 0) return;\n var fieldName = field.name();\n\n if (field.type() === 'checkbox') {\n fieldName += '[]';\n }\n\n var inForm = editor.containsField(fieldName);\n field.inFormContent(inForm); // if form contains 1 address field of group, mark all fields in this group as \"required\"\n\n if (field.newsletterType() === 'address') {\n field.originalRequiredValue = field.originalRequiredValue === undefined ? field.forceRequired() : field.originalRequiredValue; // query other fields for this address group\n\n var nameGroup = field.name().replace(/\\[(\\w+)\\]/g, '');\n\n if (editor.query('[name^=\"' + nameGroup + '\"]').length > 0) {\n if (field.originalRequiredValue === undefined) {\n field.originalRequiredValue = field.forceRequired();\n }\n\n field.forceRequired(true);\n } else {\n field.forceRequired(field.originalRequiredValue);\n }\n }\n });\n findRequiredFields();\n m.redraw();\n }\n\n function findRequiredFields() {\n // query fields required by Newsletter\n var requiredFields = fields.getAllWhere('forceRequired', true).map(function (f) {\n return f.name().toUpperCase().replace(/\\[(\\w+)\\]/g, '.$1');\n }); // query fields in form with [required] attribute\n\n var requiredFieldElements = editor.query('[required]');\n Array.prototype.forEach.call(requiredFieldElements, function (el) {\n var name = el.name; // bail if name attr empty or starts with underscore\n\n if (!name || name.length < 0 || name[0] === '_') {\n return;\n } // replace array brackets with dot style notation\n\n\n name = name.replace(/\\[(\\w+)\\]/g, '.$1'); // replace array-style fields\n\n name = name.replace(/\\[\\]$/, ''); // uppercase everything before the .\n\n var pos = name.indexOf('.');\n pos = pos > 0 ? pos : name.length;\n name = name.substr(0, pos).toUpperCase() + name.substr(pos); // only add field if it's not already in it\n\n if (requiredFields.indexOf(name) === -1) {\n requiredFields.push(name);\n }\n }); // update meta\n\n requiredFieldsInput.value = requiredFields.join(',');\n } // events\n\n\n editor.on('change', helpers.debounce(updateFields, 500));\n events.on('fields.change', helpers.debounce(updateFields, 500));\n};\n\nmodule.exports = FormWatcher;\n\n},{}],9:[function(require,module,exports){\n'use strict';\n\nvar notices = {};\n\nfunction show(id, text) {\n notices[id] = text;\n render();\n}\n\nfunction hide(id) {\n delete notices[id];\n render();\n}\n\nfunction render() {\n var html = '';\n\n for (var key in notices) {\n html += '

' + notices[key] + '

';\n }\n\n var container = document.querySelector('.nl4wp-notices');\n\n if (!container) {\n container = document.createElement('div');\n container.className = 'nl4wp-notices';\n var heading = document.querySelector('h1, h2');\n heading.parentNode.insertBefore(container, heading.nextSibling);\n }\n\n container.innerHTML = html;\n}\n\nfunction init(editor, fields) {\n var groupingsNotice = function groupingsNotice() {\n var text = \"Your form contains old style GROUPINGS fields.

Please remove these fields from your form and then re-add them through the available field buttons to make sure your data is getting through to Newsletter correctly.\";\n var formCode = editor.getValue().toLowerCase();\n formCode.indexOf('name=\"groupings') > -1 ? show('deprecated_groupings', text) : hide('deprecated_groupings');\n };\n\n var requiredFieldsNotice = function requiredFieldsNotice() {\n var requiredFields = fields.getAllWhere('forceRequired', true);\n var missingFields = requiredFields.filter(function (f) {\n return !editor.containsField(f.name().toUpperCase());\n });\n var text = 'Heads up! Your form is missing list fields that are required in Newsletter. Either add these fields to your form or mark them as optional in Newsletter.';\n text += \"
  • \" + missingFields.map(function (f) {\n return f.title();\n }).join('
  • ') + '
';\n missingFields.length > 0 ? show('required_fields_missing', text) : hide('required_fields_missing');\n }; // old groupings\n\n\n groupingsNotice();\n editor.on('focus', groupingsNotice);\n editor.on('blur', groupingsNotice); // missing required fields\n\n requiredFieldsNotice();\n editor.on('blur', requiredFieldsNotice);\n editor.on('focus', requiredFieldsNotice);\n}\n\nmodule.exports = {\n \"init\": init\n};\n\n},{}],10:[function(require,module,exports){\n\"use strict\";\n\nvar overlay = function overlay(m, i18n) {\n 'use strict';\n\n var _element, _onCloseCallback;\n\n function close() {\n document.removeEventListener('keydown', onKeyDown);\n window.removeEventListener('resize', position);\n\n _onCloseCallback();\n }\n\n function onKeyDown(e) {\n e = e || window.event; // close overlay when pressing ESC\n\n if (e.keyCode == 27) {\n close();\n } // prevent ENTER\n\n\n if (e.keyCode == 13) {\n e.preventDefault();\n }\n }\n\n function position() {\n if (!_element) return; // fix for window width in IE8\n\n var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;\n var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;\n var marginLeft = (windowWidth - _element.clientWidth - 40) / 2;\n var marginTop = (windowHeight - _element.clientHeight - 40) / 2;\n _element.style.left = (marginLeft > 0 ? marginLeft : 0) + \"px\";\n _element.style.top = (marginTop > 0 ? marginTop : 0) + \"px\";\n }\n\n function storeElementReference(vnode) {\n _element = vnode.dom;\n position();\n }\n\n return function (content, onCloseCallback) {\n _onCloseCallback = onCloseCallback;\n return {\n oncreate: function oncreate() {\n document.addEventListener('keydown', onKeyDown);\n window.addEventListener('resize', position);\n },\n onremove: function onremove() {\n document.removeEventListener('keydown', onKeyDown);\n window.removeEventListener('resize', position);\n },\n view: function view() {\n return [m('div.overlay-wrap', m(\"div.overlay\", {\n oncreate: storeElementReference\n }, [// close icon\n m('span', {\n \"class\": 'close dashicons dashicons-no',\n title: i18n.close,\n onclick: close\n }), content])), m('div.overlay-background', {\n title: i18n.close,\n onclick: close\n })];\n }\n };\n };\n};\n\nmodule.exports = overlay;\n\n},{}],11:[function(require,module,exports){\n'use strict'; // deps\n\nvar i18n = window.nl4wp_forms_i18n;\nvar m = window.nl4wp.deps.mithril;\nvar events = nl4wp.events;\nvar settings = nl4wp.settings;\nvar helpers = nl4wp.helpers;\nvar tabs = nl4wp.tabs;\n\nvar FormWatcher = require('./admin/form-watcher.js');\n\nvar FormEditor = require('./admin/form-editor.js');\n\nvar FieldHelper = require('./admin/field-helper.js');\n\nvar FieldsFactory = require('./admin/fields-factory.js');\n\nvar fields = require('./admin/fields.js')(m, events); // vars\n\n\nvar editor = window.formEditor = FormEditor;\nvar watcher = new FormWatcher(m, formEditor, settings, fields, events, helpers);\nvar fieldHelper = new FieldHelper(m, tabs, formEditor, fields, events, i18n);\n\nvar notices = require('./admin/notices'); // mount field helper on element\n\n\nm.mount(document.getElementById('nl4wp-field-wizard'), fieldHelper); // register fields and redraw screen in 2 seconds (fixes IE8 bug)\n\nvar fieldsFactory = new FieldsFactory(fields, i18n);\nevents.on('selectedLists.change', fieldsFactory.registerListsFields);\nfieldsFactory.registerListsFields(settings.getSelectedLists());\nfieldsFactory.registerCustomFields(nl4wp_vars.newsletter.lists);\nwindow.setTimeout(function () {\n m.redraw();\n}, 2000); // init notices\n\nnotices.init(editor, fields); // expose some methods\n\nwindow.nl4wp = window.nl4wp || {};\nwindow.nl4wp.forms = window.nl4wp.forms || {};\nwindow.nl4wp.forms.editor = editor;\nwindow.nl4wp.forms.fields = fields;\n\n},{\"./admin/field-helper.js\":4,\"./admin/fields-factory.js\":5,\"./admin/fields.js\":6,\"./admin/form-editor.js\":7,\"./admin/form-watcher.js\":8,\"./admin/notices\":9}],12:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**\n * Tag-closer extension for CodeMirror.\n *\n * This extension adds an \"autoCloseTags\" option that can be set to\n * either true to get the default behavior, or an object to further\n * configure its behavior.\n *\n * These are supported options:\n *\n * `whenClosing` (default true)\n * Whether to autoclose when the '/' of a closing tag is typed.\n * `whenOpening` (default true)\n * Whether to autoclose the tag when the final '>' of an opening\n * tag is typed.\n * `dontCloseTags` (default is empty tags for HTML, none for XML)\n * An array of tag names that should not be autoclosed.\n * `indentTags` (default is block tags for HTML, none for XML)\n * An array of tag names that should, when opened, cause a\n * blank line to be added inside the tag, and the blank line and\n * closing line to be indented.\n *\n * See demos/closetag.html for a usage example.\n */\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"), require(\"../fold/xml-fold\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\", \"../fold/xml-fold\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n CodeMirror.defineOption(\"autoCloseTags\", false, function(cm, val, old) {\n if (old != CodeMirror.Init && old)\n cm.removeKeyMap(\"autoCloseTags\");\n if (!val) return;\n var map = {name: \"autoCloseTags\"};\n if (typeof val != \"object\" || val.whenClosing)\n map[\"'/'\"] = function(cm) { return autoCloseSlash(cm); };\n if (typeof val != \"object\" || val.whenOpening)\n map[\"'>'\"] = function(cm) { return autoCloseGT(cm); };\n cm.addKeyMap(map);\n });\n\n var htmlDontClose = [\"area\", \"base\", \"br\", \"col\", \"command\", \"embed\", \"hr\", \"img\", \"input\", \"keygen\", \"link\", \"meta\", \"param\",\n \"source\", \"track\", \"wbr\"];\n var htmlIndent = [\"applet\", \"blockquote\", \"body\", \"button\", \"div\", \"dl\", \"fieldset\", \"form\", \"frameset\", \"h1\", \"h2\", \"h3\", \"h4\",\n \"h5\", \"h6\", \"head\", \"html\", \"iframe\", \"layer\", \"legend\", \"object\", \"ol\", \"p\", \"select\", \"table\", \"ul\"];\n\n function autoCloseGT(cm) {\n if (cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n var ranges = cm.listSelections(), replacements = [];\n var opt = cm.getOption(\"autoCloseTags\");\n for (var i = 0; i < ranges.length; i++) {\n if (!ranges[i].empty()) return CodeMirror.Pass;\n var pos = ranges[i].head, tok = cm.getTokenAt(pos);\n var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;\n if (inner.mode.name != \"xml\" || !state.tagName) return CodeMirror.Pass;\n\n var html = inner.mode.configuration == \"html\";\n var dontCloseTags = (typeof opt == \"object\" && opt.dontCloseTags) || (html && htmlDontClose);\n var indentTags = (typeof opt == \"object\" && opt.indentTags) || (html && htmlIndent);\n\n var tagName = state.tagName;\n if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);\n var lowerTagName = tagName.toLowerCase();\n // Don't process the '>' at the end of an end-tag or self-closing tag\n if (!tagName ||\n tok.type == \"string\" && (tok.end != pos.ch || !/[\\\"\\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||\n tok.type == \"tag\" && state.type == \"closeTag\" ||\n tok.string.indexOf(\"/\") == (tok.string.length - 1) || // match something like \n dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||\n closingTagExists(cm, tagName, pos, state, true))\n return CodeMirror.Pass;\n\n var indent = indentTags && indexOf(indentTags, lowerTagName) > -1;\n replacements[i] = {indent: indent,\n text: \">\" + (indent ? \"\\n\\n\" : \"\") + \"\",\n newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)};\n }\n\n var dontIndentOnAutoClose = (typeof opt == \"object\" && opt.dontIndentOnAutoClose);\n for (var i = ranges.length - 1; i >= 0; i--) {\n var info = replacements[i];\n cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, \"+insert\");\n var sel = cm.listSelections().slice(0);\n sel[i] = {head: info.newPos, anchor: info.newPos};\n cm.setSelections(sel);\n if (!dontIndentOnAutoClose && info.indent) {\n cm.indentLine(info.newPos.line, null, true);\n cm.indentLine(info.newPos.line + 1, null, true);\n }\n }\n }\n\n function autoCloseCurrent(cm, typingSlash) {\n var ranges = cm.listSelections(), replacements = [];\n var head = typingSlash ? \"/\" : \"\") replacement += \">\";\n replacements[i] = replacement;\n }\n cm.replaceSelections(replacements);\n ranges = cm.listSelections();\n if (!dontIndentOnAutoClose) {\n for (var i = 0; i < ranges.length; i++)\n if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line)\n cm.indentLine(ranges[i].head.line);\n }\n }\n\n function autoCloseSlash(cm) {\n if (cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n return autoCloseCurrent(cm, true);\n }\n\n CodeMirror.commands.closeTag = function(cm) { return autoCloseCurrent(cm); };\n\n function indexOf(collection, elt) {\n if (collection.indexOf) return collection.indexOf(elt);\n for (var i = 0, e = collection.length; i < e; ++i)\n if (collection[i] == elt) return i;\n return -1;\n }\n\n // If xml-fold is loaded, we use its functionality to try and verify\n // whether a given tag is actually unclosed.\n function closingTagExists(cm, tagName, pos, state, newTag) {\n if (!CodeMirror.scanForClosingTag) return false;\n var end = Math.min(cm.lastLine() + 1, pos.line + 500);\n var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);\n if (!nextClose || nextClose.tag != tagName) return false;\n var cx = state.context;\n // If the immediate wrapping context contains onCx instances of\n // the same tag, a closing tag only exists if there are at least\n // that many closing tags of that type following.\n for (var onCx = newTag ? 1 : 0; cx && cx.tagName == tagName; cx = cx.prev) ++onCx;\n pos = nextClose.to;\n for (var i = 1; i < onCx; i++) {\n var next = CodeMirror.scanForClosingTag(cm, pos, null, end);\n if (!next || next.tag != tagName) return false;\n pos = next.to;\n }\n return true;\n }\n});\n\n},{\"../../lib/codemirror\":17,\"../fold/xml-fold\":15}],13:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n var ie_lt8 = /MSIE \\d/.test(navigator.userAgent) &&\n (document.documentMode == null || document.documentMode < 8);\n\n var Pos = CodeMirror.Pos;\n\n var matching = {\"(\": \")>\", \")\": \"(<\", \"[\": \"]>\", \"]\": \"[<\", \"{\": \"}>\", \"}\": \"{<\"};\n\n function findMatchingBracket(cm, where, config) {\n var line = cm.getLineHandle(where.line), pos = where.ch - 1;\n var afterCursor = config && config.afterCursor\n if (afterCursor == null)\n afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)\n\n // A cursor is defined as between two characters, but in in vim command mode\n // (i.e. not insert mode), the cursor is visually represented as a\n // highlighted box on top of the 2nd character. Otherwise, we allow matches\n // from before or after the cursor.\n var match = (!afterCursor && pos >= 0 && matching[line.text.charAt(pos)]) ||\n matching[line.text.charAt(++pos)];\n if (!match) return null;\n var dir = match.charAt(1) == \">\" ? 1 : -1;\n if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;\n var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));\n\n var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);\n if (found == null) return null;\n return {from: Pos(where.line, pos), to: found && found.pos,\n match: found && found.ch == match.charAt(0), forward: dir > 0};\n }\n\n // bracketRegex is used to specify which type of bracket to scan\n // should be a regexp, e.g. /[[\\]]/\n //\n // Note: If \"where\" is on an open bracket, then this bracket is ignored.\n //\n // Returns false when no bracket was found, null when it reached\n // maxScanLines and gave up\n function scanForBracket(cm, where, dir, style, config) {\n var maxScanLen = (config && config.maxScanLineLength) || 10000;\n var maxScanLines = (config && config.maxScanLines) || 1000;\n\n var stack = [];\n var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\\]]/;\n var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)\n : Math.max(cm.firstLine() - 1, where.line - maxScanLines);\n for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {\n var line = cm.getLine(lineNo);\n if (!line) continue;\n var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;\n if (line.length > maxScanLen) continue;\n if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);\n for (; pos != end; pos += dir) {\n var ch = line.charAt(pos);\n if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {\n var match = matching[ch];\n if ((match.charAt(1) == \">\") == (dir > 0)) stack.push(ch);\n else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};\n else stack.pop();\n }\n }\n }\n return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;\n }\n\n function matchBrackets(cm, autoclear, config) {\n // Disable brace matching in long lines, since it'll cause hugely slow updates\n var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;\n var marks = [], ranges = cm.listSelections();\n for (var i = 0; i < ranges.length; i++) {\n var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);\n if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {\n var style = match.match ? \"CodeMirror-matchingbracket\" : \"CodeMirror-nonmatchingbracket\";\n marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));\n if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)\n marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));\n }\n }\n\n if (marks.length) {\n // Kludge to work around the IE bug from issue #1193, where text\n // input stops going to the textare whever this fires.\n if (ie_lt8 && cm.state.focused) cm.focus();\n\n var clear = function() {\n cm.operation(function() {\n for (var i = 0; i < marks.length; i++) marks[i].clear();\n });\n };\n if (autoclear) setTimeout(clear, 800);\n else return clear;\n }\n }\n\n function doMatchBrackets(cm) {\n cm.operation(function() {\n if (cm.state.matchBrackets.currentlyHighlighted) {\n cm.state.matchBrackets.currentlyHighlighted();\n cm.state.matchBrackets.currentlyHighlighted = null;\n }\n cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);\n });\n }\n\n CodeMirror.defineOption(\"matchBrackets\", false, function(cm, val, old) {\n if (old && old != CodeMirror.Init) {\n cm.off(\"cursorActivity\", doMatchBrackets);\n if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {\n cm.state.matchBrackets.currentlyHighlighted();\n cm.state.matchBrackets.currentlyHighlighted = null;\n }\n }\n if (val) {\n cm.state.matchBrackets = typeof val == \"object\" ? val : {};\n cm.on(\"cursorActivity\", doMatchBrackets);\n }\n });\n\n CodeMirror.defineExtension(\"matchBrackets\", function() {matchBrackets(this, true);});\n CodeMirror.defineExtension(\"findMatchingBracket\", function(pos, config, oldConfig){\n // Backwards-compatibility kludge\n if (oldConfig || typeof config == \"boolean\") {\n if (!oldConfig) {\n config = config ? {strict: true} : null\n } else {\n oldConfig.strict = config\n config = oldConfig\n }\n }\n return findMatchingBracket(this, pos, config)\n });\n CodeMirror.defineExtension(\"scanForBracket\", function(pos, dir, style, config){\n return scanForBracket(this, pos, dir, style, config);\n });\n});\n\n},{\"../../lib/codemirror\":17}],14:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"), require(\"../fold/xml-fold\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\", \"../fold/xml-fold\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n\n CodeMirror.defineOption(\"matchTags\", false, function(cm, val, old) {\n if (old && old != CodeMirror.Init) {\n cm.off(\"cursorActivity\", doMatchTags);\n cm.off(\"viewportChange\", maybeUpdateMatch);\n clear(cm);\n }\n if (val) {\n cm.state.matchBothTags = typeof val == \"object\" && val.bothTags;\n cm.on(\"cursorActivity\", doMatchTags);\n cm.on(\"viewportChange\", maybeUpdateMatch);\n doMatchTags(cm);\n }\n });\n\n function clear(cm) {\n if (cm.state.tagHit) cm.state.tagHit.clear();\n if (cm.state.tagOther) cm.state.tagOther.clear();\n cm.state.tagHit = cm.state.tagOther = null;\n }\n\n function doMatchTags(cm) {\n cm.state.failedTagMatch = false;\n cm.operation(function() {\n clear(cm);\n if (cm.somethingSelected()) return;\n var cur = cm.getCursor(), range = cm.getViewport();\n range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);\n var match = CodeMirror.findMatchingTag(cm, cur, range);\n if (!match) return;\n if (cm.state.matchBothTags) {\n var hit = match.at == \"open\" ? match.open : match.close;\n if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: \"CodeMirror-matchingtag\"});\n }\n var other = match.at == \"close\" ? match.open : match.close;\n if (other)\n cm.state.tagOther = cm.markText(other.from, other.to, {className: \"CodeMirror-matchingtag\"});\n else\n cm.state.failedTagMatch = true;\n });\n }\n\n function maybeUpdateMatch(cm) {\n if (cm.state.failedTagMatch) doMatchTags(cm);\n }\n\n CodeMirror.commands.toMatchingTag = function(cm) {\n var found = CodeMirror.findMatchingTag(cm, cm.getCursor());\n if (found) {\n var other = found.at == \"close\" ? found.open : found.close;\n if (other) cm.extendSelection(other.to, other.from);\n }\n };\n});\n\n},{\"../../lib/codemirror\":17,\"../fold/xml-fold\":15}],15:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n\n var Pos = CodeMirror.Pos;\n function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }\n\n var nameStartChar = \"A-Z_a-z\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD\";\n var nameChar = nameStartChar + \"\\-\\:\\.0-9\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040\";\n var xmlTagStart = new RegExp(\"<(/?)([\" + nameStartChar + \"][\" + nameChar + \"]*)\", \"g\");\n\n function Iter(cm, line, ch, range) {\n this.line = line; this.ch = ch;\n this.cm = cm; this.text = cm.getLine(line);\n this.min = range ? Math.max(range.from, cm.firstLine()) : cm.firstLine();\n this.max = range ? Math.min(range.to - 1, cm.lastLine()) : cm.lastLine();\n }\n\n function tagAt(iter, ch) {\n var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));\n return type && /\\btag\\b/.test(type);\n }\n\n function nextLine(iter) {\n if (iter.line >= iter.max) return;\n iter.ch = 0;\n iter.text = iter.cm.getLine(++iter.line);\n return true;\n }\n function prevLine(iter) {\n if (iter.line <= iter.min) return;\n iter.text = iter.cm.getLine(--iter.line);\n iter.ch = iter.text.length;\n return true;\n }\n\n function toTagEnd(iter) {\n for (;;) {\n var gt = iter.text.indexOf(\">\", iter.ch);\n if (gt == -1) { if (nextLine(iter)) continue; else return; }\n if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }\n var lastSlash = iter.text.lastIndexOf(\"/\", gt);\n var selfClose = lastSlash > -1 && !/\\S/.test(iter.text.slice(lastSlash + 1, gt));\n iter.ch = gt + 1;\n return selfClose ? \"selfClose\" : \"regular\";\n }\n }\n function toTagStart(iter) {\n for (;;) {\n var lt = iter.ch ? iter.text.lastIndexOf(\"<\", iter.ch - 1) : -1;\n if (lt == -1) { if (prevLine(iter)) continue; else return; }\n if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }\n xmlTagStart.lastIndex = lt;\n iter.ch = lt;\n var match = xmlTagStart.exec(iter.text);\n if (match && match.index == lt) return match;\n }\n }\n\n function toNextTag(iter) {\n for (;;) {\n xmlTagStart.lastIndex = iter.ch;\n var found = xmlTagStart.exec(iter.text);\n if (!found) { if (nextLine(iter)) continue; else return; }\n if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }\n iter.ch = found.index + found[0].length;\n return found;\n }\n }\n function toPrevTag(iter) {\n for (;;) {\n var gt = iter.ch ? iter.text.lastIndexOf(\">\", iter.ch - 1) : -1;\n if (gt == -1) { if (prevLine(iter)) continue; else return; }\n if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }\n var lastSlash = iter.text.lastIndexOf(\"/\", gt);\n var selfClose = lastSlash > -1 && !/\\S/.test(iter.text.slice(lastSlash + 1, gt));\n iter.ch = gt + 1;\n return selfClose ? \"selfClose\" : \"regular\";\n }\n }\n\n function findMatchingClose(iter, tag) {\n var stack = [];\n for (;;) {\n var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);\n if (!next || !(end = toTagEnd(iter))) return;\n if (end == \"selfClose\") continue;\n if (next[1]) { // closing tag\n for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {\n stack.length = i;\n break;\n }\n if (i < 0 && (!tag || tag == next[2])) return {\n tag: next[2],\n from: Pos(startLine, startCh),\n to: Pos(iter.line, iter.ch)\n };\n } else { // opening tag\n stack.push(next[2]);\n }\n }\n }\n function findMatchingOpen(iter, tag) {\n var stack = [];\n for (;;) {\n var prev = toPrevTag(iter);\n if (!prev) return;\n if (prev == \"selfClose\") { toTagStart(iter); continue; }\n var endLine = iter.line, endCh = iter.ch;\n var start = toTagStart(iter);\n if (!start) return;\n if (start[1]) { // closing tag\n stack.push(start[2]);\n } else { // opening tag\n for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {\n stack.length = i;\n break;\n }\n if (i < 0 && (!tag || tag == start[2])) return {\n tag: start[2],\n from: Pos(iter.line, iter.ch),\n to: Pos(endLine, endCh)\n };\n }\n }\n }\n\n CodeMirror.registerHelper(\"fold\", \"xml\", function(cm, start) {\n var iter = new Iter(cm, start.line, 0);\n for (;;) {\n var openTag = toNextTag(iter)\n if (!openTag || iter.line != start.line) return\n var end = toTagEnd(iter)\n if (!end) return\n if (!openTag[1] && end != \"selfClose\") {\n var startPos = Pos(iter.line, iter.ch);\n var endPos = findMatchingClose(iter, openTag[2]);\n return endPos && cmp(endPos.from, startPos) > 0 ? {from: startPos, to: endPos.from} : null\n }\n }\n });\n CodeMirror.findMatchingTag = function(cm, pos, range) {\n var iter = new Iter(cm, pos.line, pos.ch, range);\n if (iter.text.indexOf(\">\") == -1 && iter.text.indexOf(\"<\") == -1) return;\n var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);\n var start = end && toTagStart(iter);\n if (!end || !start || cmp(iter, pos) > 0) return;\n var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};\n if (end == \"selfClose\") return {open: here, close: null, at: \"open\"};\n\n if (start[1]) { // closing tag\n return {open: findMatchingOpen(iter, start[2]), close: here, at: \"close\"};\n } else { // opening tag\n iter = new Iter(cm, to.line, to.ch, range);\n return {open: here, close: findMatchingClose(iter, start[2]), at: \"open\"};\n }\n };\n\n CodeMirror.findEnclosingTag = function(cm, pos, range, tag) {\n var iter = new Iter(cm, pos.line, pos.ch, range);\n for (;;) {\n var open = findMatchingOpen(iter, tag);\n if (!open) break;\n var forward = new Iter(cm, pos.line, pos.ch, range);\n var close = findMatchingClose(forward, open.tag);\n if (close) return {open: open, close: close};\n }\n };\n\n // Used by addon/edit/closetag.js\n CodeMirror.scanForClosingTag = function(cm, pos, name, end) {\n var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);\n return findMatchingClose(iter, name);\n };\n});\n\n},{\"../../lib/codemirror\":17}],16:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n var WRAP_CLASS = \"CodeMirror-activeline\";\n var BACK_CLASS = \"CodeMirror-activeline-background\";\n var GUTT_CLASS = \"CodeMirror-activeline-gutter\";\n\n CodeMirror.defineOption(\"styleActiveLine\", false, function(cm, val, old) {\n var prev = old == CodeMirror.Init ? false : old;\n if (val == prev) return\n if (prev) {\n cm.off(\"beforeSelectionChange\", selectionChange);\n clearActiveLines(cm);\n delete cm.state.activeLines;\n }\n if (val) {\n cm.state.activeLines = [];\n updateActiveLines(cm, cm.listSelections());\n cm.on(\"beforeSelectionChange\", selectionChange);\n }\n });\n\n function clearActiveLines(cm) {\n for (var i = 0; i < cm.state.activeLines.length; i++) {\n cm.removeLineClass(cm.state.activeLines[i], \"wrap\", WRAP_CLASS);\n cm.removeLineClass(cm.state.activeLines[i], \"background\", BACK_CLASS);\n cm.removeLineClass(cm.state.activeLines[i], \"gutter\", GUTT_CLASS);\n }\n }\n\n function sameArray(a, b) {\n if (a.length != b.length) return false;\n for (var i = 0; i < a.length; i++)\n if (a[i] != b[i]) return false;\n return true;\n }\n\n function updateActiveLines(cm, ranges) {\n var active = [];\n for (var i = 0; i < ranges.length; i++) {\n var range = ranges[i];\n var option = cm.getOption(\"styleActiveLine\");\n if (typeof option == \"object\" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())\n continue\n var line = cm.getLineHandleVisualStart(range.head.line);\n if (active[active.length - 1] != line) active.push(line);\n }\n if (sameArray(cm.state.activeLines, active)) return;\n cm.operation(function() {\n clearActiveLines(cm);\n for (var i = 0; i < active.length; i++) {\n cm.addLineClass(active[i], \"wrap\", WRAP_CLASS);\n cm.addLineClass(active[i], \"background\", BACK_CLASS);\n cm.addLineClass(active[i], \"gutter\", GUTT_CLASS);\n }\n cm.state.activeLines = active;\n });\n }\n\n function selectionChange(cm, sel) {\n updateActiveLines(cm, sel.ranges);\n }\n});\n\n},{\"../../lib/codemirror\":17}],17:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// This is CodeMirror (https://codemirror.net), a code editor\n// implemented in JavaScript on top of the browser's DOM.\n//\n// You can find some technical background for some of the code below\n// at http://marijnhaverbeke.nl/blog/#cm-internals .\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.CodeMirror = factory());\n}(this, (function () { 'use strict';\n\n // Kludges for bugs and behavior differences that can't be feature\n // detected are enabled based on userAgent etc sniffing.\n var userAgent = navigator.userAgent;\n var platform = navigator.platform;\n\n var gecko = /gecko\\/\\d/i.test(userAgent);\n var ie_upto10 = /MSIE \\d/.test(userAgent);\n var ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(userAgent);\n var edge = /Edge\\/(\\d+)/.exec(userAgent);\n var ie = ie_upto10 || ie_11up || edge;\n var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);\n var webkit = !edge && /WebKit\\//.test(userAgent);\n var qtwebkit = webkit && /Qt\\/\\d+\\.\\d+/.test(userAgent);\n var chrome = !edge && /Chrome\\//.test(userAgent);\n var presto = /Opera\\//.test(userAgent);\n var safari = /Apple Computer/.test(navigator.vendor);\n var mac_geMountainLion = /Mac OS X 1\\d\\D([8-9]|\\d\\d)\\D/.test(userAgent);\n var phantom = /PhantomJS/.test(userAgent);\n\n var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\\/\\w+/.test(userAgent);\n var android = /Android/.test(userAgent);\n // This is woefully incomplete. Suggestions for alternative methods welcome.\n var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);\n var mac = ios || /Mac/.test(platform);\n var chromeOS = /\\bCrOS\\b/.test(userAgent);\n var windows = /win/i.test(platform);\n\n var presto_version = presto && userAgent.match(/Version\\/(\\d*\\.\\d*)/);\n if (presto_version) { presto_version = Number(presto_version[1]); }\n if (presto_version && presto_version >= 15) { presto = false; webkit = true; }\n // Some browsers use the wrong event properties to signal cmd/ctrl on OS X\n var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));\n var captureRightClick = gecko || (ie && ie_version >= 9);\n\n function classTest(cls) { return new RegExp(\"(^|\\\\s)\" + cls + \"(?:$|\\\\s)\\\\s*\") }\n\n var rmClass = function(node, cls) {\n var current = node.className;\n var match = classTest(cls).exec(current);\n if (match) {\n var after = current.slice(match.index + match[0].length);\n node.className = current.slice(0, match.index) + (after ? match[1] + after : \"\");\n }\n };\n\n function removeChildren(e) {\n for (var count = e.childNodes.length; count > 0; --count)\n { e.removeChild(e.firstChild); }\n return e\n }\n\n function removeChildrenAndAdd(parent, e) {\n return removeChildren(parent).appendChild(e)\n }\n\n function elt(tag, content, className, style) {\n var e = document.createElement(tag);\n if (className) { e.className = className; }\n if (style) { e.style.cssText = style; }\n if (typeof content == \"string\") { e.appendChild(document.createTextNode(content)); }\n else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }\n return e\n }\n // wrapper for elt, which removes the elt from the accessibility tree\n function eltP(tag, content, className, style) {\n var e = elt(tag, content, className, style);\n e.setAttribute(\"role\", \"presentation\");\n return e\n }\n\n var range;\n if (document.createRange) { range = function(node, start, end, endNode) {\n var r = document.createRange();\n r.setEnd(endNode || node, end);\n r.setStart(node, start);\n return r\n }; }\n else { range = function(node, start, end) {\n var r = document.body.createTextRange();\n try { r.moveToElementText(node.parentNode); }\n catch(e) { return r }\n r.collapse(true);\n r.moveEnd(\"character\", end);\n r.moveStart(\"character\", start);\n return r\n }; }\n\n function contains(parent, child) {\n if (child.nodeType == 3) // Android browser always returns false when child is a textnode\n { child = child.parentNode; }\n if (parent.contains)\n { return parent.contains(child) }\n do {\n if (child.nodeType == 11) { child = child.host; }\n if (child == parent) { return true }\n } while (child = child.parentNode)\n }\n\n function activeElt() {\n // IE and Edge may throw an \"Unspecified Error\" when accessing document.activeElement.\n // IE < 10 will throw when accessed while the page is loading or in an iframe.\n // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.\n var activeElement;\n try {\n activeElement = document.activeElement;\n } catch(e) {\n activeElement = document.body || null;\n }\n while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)\n { activeElement = activeElement.shadowRoot.activeElement; }\n return activeElement\n }\n\n function addClass(node, cls) {\n var current = node.className;\n if (!classTest(cls).test(current)) { node.className += (current ? \" \" : \"\") + cls; }\n }\n function joinClasses(a, b) {\n var as = a.split(\" \");\n for (var i = 0; i < as.length; i++)\n { if (as[i] && !classTest(as[i]).test(b)) { b += \" \" + as[i]; } }\n return b\n }\n\n var selectInput = function(node) { node.select(); };\n if (ios) // Mobile Safari apparently has a bug where select() is broken.\n { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }\n else if (ie) // Suppress mysterious IE10 errors\n { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }\n\n function bind(f) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function(){return f.apply(null, args)}\n }\n\n function copyObj(obj, target, overwrite) {\n if (!target) { target = {}; }\n for (var prop in obj)\n { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))\n { target[prop] = obj[prop]; } }\n return target\n }\n\n // Counts the column offset in a string, taking tabs into account.\n // Used mostly to find indentation.\n function countColumn(string, end, tabSize, startIndex, startValue) {\n if (end == null) {\n end = string.search(/[^\\s\\u00a0]/);\n if (end == -1) { end = string.length; }\n }\n for (var i = startIndex || 0, n = startValue || 0;;) {\n var nextTab = string.indexOf(\"\\t\", i);\n if (nextTab < 0 || nextTab >= end)\n { return n + (end - i) }\n n += nextTab - i;\n n += tabSize - (n % tabSize);\n i = nextTab + 1;\n }\n }\n\n var Delayed = function() {this.id = null;};\n Delayed.prototype.set = function (ms, f) {\n clearTimeout(this.id);\n this.id = setTimeout(f, ms);\n };\n\n function indexOf(array, elt) {\n for (var i = 0; i < array.length; ++i)\n { if (array[i] == elt) { return i } }\n return -1\n }\n\n // Number of pixels added to scroller and sizer to hide scrollbar\n var scrollerGap = 30;\n\n // Returned or thrown by various protocols to signal 'I'm not\n // handling this'.\n var Pass = {toString: function(){return \"CodeMirror.Pass\"}};\n\n // Reused option objects for setSelection & friends\n var sel_dontScroll = {scroll: false}, sel_mouse = {origin: \"*mouse\"}, sel_move = {origin: \"+move\"};\n\n // The inverse of countColumn -- find the offset that corresponds to\n // a particular column.\n function findColumn(string, goal, tabSize) {\n for (var pos = 0, col = 0;;) {\n var nextTab = string.indexOf(\"\\t\", pos);\n if (nextTab == -1) { nextTab = string.length; }\n var skipped = nextTab - pos;\n if (nextTab == string.length || col + skipped >= goal)\n { return pos + Math.min(skipped, goal - col) }\n col += nextTab - pos;\n col += tabSize - (col % tabSize);\n pos = nextTab + 1;\n if (col >= goal) { return pos }\n }\n }\n\n var spaceStrs = [\"\"];\n function spaceStr(n) {\n while (spaceStrs.length <= n)\n { spaceStrs.push(lst(spaceStrs) + \" \"); }\n return spaceStrs[n]\n }\n\n function lst(arr) { return arr[arr.length-1] }\n\n function map(array, f) {\n var out = [];\n for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }\n return out\n }\n\n function insertSorted(array, value, score) {\n var pos = 0, priority = score(value);\n while (pos < array.length && score(array[pos]) <= priority) { pos++; }\n array.splice(pos, 0, value);\n }\n\n function nothing() {}\n\n function createObj(base, props) {\n var inst;\n if (Object.create) {\n inst = Object.create(base);\n } else {\n nothing.prototype = base;\n inst = new nothing();\n }\n if (props) { copyObj(props, inst); }\n return inst\n }\n\n var nonASCIISingleCaseWordChar = /[\\u00df\\u0587\\u0590-\\u05f4\\u0600-\\u06ff\\u3040-\\u309f\\u30a0-\\u30ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\uac00-\\ud7af]/;\n function isWordCharBasic(ch) {\n return /\\w/.test(ch) || ch > \"\\x80\" &&\n (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))\n }\n function isWordChar(ch, helper) {\n if (!helper) { return isWordCharBasic(ch) }\n if (helper.source.indexOf(\"\\\\w\") > -1 && isWordCharBasic(ch)) { return true }\n return helper.test(ch)\n }\n\n function isEmpty(obj) {\n for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }\n return true\n }\n\n // Extending unicode characters. A series of a non-extending char +\n // any number of extending chars is treated as a single unit as far\n // as editing and measuring is concerned. This is not fully correct,\n // since some scripts/fonts/browsers also treat other configurations\n // of code points as a group.\n var extendingChars = /[\\u0300-\\u036f\\u0483-\\u0489\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u065e\\u0670\\u06d6-\\u06dc\\u06de-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07eb-\\u07f3\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0900-\\u0902\\u093c\\u0941-\\u0948\\u094d\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09bc\\u09be\\u09c1-\\u09c4\\u09cd\\u09d7\\u09e2\\u09e3\\u0a01\\u0a02\\u0a3c\\u0a41\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a70\\u0a71\\u0a75\\u0a81\\u0a82\\u0abc\\u0ac1-\\u0ac5\\u0ac7\\u0ac8\\u0acd\\u0ae2\\u0ae3\\u0b01\\u0b3c\\u0b3e\\u0b3f\\u0b41-\\u0b44\\u0b4d\\u0b56\\u0b57\\u0b62\\u0b63\\u0b82\\u0bbe\\u0bc0\\u0bcd\\u0bd7\\u0c3e-\\u0c40\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0cbc\\u0cbf\\u0cc2\\u0cc6\\u0ccc\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0d3e\\u0d41-\\u0d44\\u0d4d\\u0d57\\u0d62\\u0d63\\u0dca\\u0dcf\\u0dd2-\\u0dd4\\u0dd6\\u0ddf\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0eb1\\u0eb4-\\u0eb9\\u0ebb\\u0ebc\\u0ec8-\\u0ecd\\u0f18\\u0f19\\u0f35\\u0f37\\u0f39\\u0f71-\\u0f7e\\u0f80-\\u0f84\\u0f86\\u0f87\\u0f90-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102d-\\u1030\\u1032-\\u1037\\u1039\\u103a\\u103d\\u103e\\u1058\\u1059\\u105e-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108d\\u109d\\u135f\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b7-\\u17bd\\u17c6\\u17c9-\\u17d3\\u17dd\\u180b-\\u180d\\u18a9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193b\\u1a17\\u1a18\\u1a56\\u1a58-\\u1a5e\\u1a60\\u1a62\\u1a65-\\u1a6c\\u1a73-\\u1a7c\\u1a7f\\u1b00-\\u1b03\\u1b34\\u1b36-\\u1b3a\\u1b3c\\u1b42\\u1b6b-\\u1b73\\u1b80\\u1b81\\u1ba2-\\u1ba5\\u1ba8\\u1ba9\\u1c2c-\\u1c33\\u1c36\\u1c37\\u1cd0-\\u1cd2\\u1cd4-\\u1ce0\\u1ce2-\\u1ce8\\u1ced\\u1dc0-\\u1de6\\u1dfd-\\u1dff\\u200c\\u200d\\u20d0-\\u20f0\\u2cef-\\u2cf1\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua66f-\\ua672\\ua67c\\ua67d\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua825\\ua826\\ua8c4\\ua8e0-\\ua8f1\\ua926-\\ua92d\\ua947-\\ua951\\ua980-\\ua982\\ua9b3\\ua9b6-\\ua9b9\\ua9bc\\uaa29-\\uaa2e\\uaa31\\uaa32\\uaa35\\uaa36\\uaa43\\uaa4c\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uabe5\\uabe8\\uabed\\udc00-\\udfff\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe26\\uff9e\\uff9f]/;\n function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }\n\n // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.\n function skipExtendingChars(str, pos, dir) {\n while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }\n return pos\n }\n\n // Returns the value from the range [`from`; `to`] that satisfies\n // `pred` and is closest to `from`. Assumes that at least `to`\n // satisfies `pred`. Supports `from` being greater than `to`.\n function findFirst(pred, from, to) {\n // At any point we are certain `to` satisfies `pred`, don't know\n // whether `from` does.\n var dir = from > to ? -1 : 1;\n for (;;) {\n if (from == to) { return from }\n var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);\n if (mid == from) { return pred(mid) ? from : to }\n if (pred(mid)) { to = mid; }\n else { from = mid + dir; }\n }\n }\n\n // The display handles the DOM integration, both for input reading\n // and content drawing. It holds references to DOM nodes and\n // display-related state.\n\n function Display(place, doc, input) {\n var d = this;\n this.input = input;\n\n // Covers bottom-right square when both scrollbars are present.\n d.scrollbarFiller = elt(\"div\", null, \"CodeMirror-scrollbar-filler\");\n d.scrollbarFiller.setAttribute(\"cm-not-content\", \"true\");\n // Covers bottom of gutter when coverGutterNextToScrollbar is on\n // and h scrollbar is present.\n d.gutterFiller = elt(\"div\", null, \"CodeMirror-gutter-filler\");\n d.gutterFiller.setAttribute(\"cm-not-content\", \"true\");\n // Will contain the actual code, positioned to cover the viewport.\n d.lineDiv = eltP(\"div\", null, \"CodeMirror-code\");\n // Elements are added to these to represent selection and cursors.\n d.selectionDiv = elt(\"div\", null, null, \"position: relative; z-index: 1\");\n d.cursorDiv = elt(\"div\", null, \"CodeMirror-cursors\");\n // A visibility: hidden element used to find the size of things.\n d.measure = elt(\"div\", null, \"CodeMirror-measure\");\n // When lines outside of the viewport are measured, they are drawn in this.\n d.lineMeasure = elt(\"div\", null, \"CodeMirror-measure\");\n // Wraps everything that needs to exist inside the vertically-padded coordinate system\n d.lineSpace = eltP(\"div\", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],\n null, \"position: relative; outline: none\");\n var lines = eltP(\"div\", [d.lineSpace], \"CodeMirror-lines\");\n // Moved around its parent to cover visible view.\n d.mover = elt(\"div\", [lines], null, \"position: relative\");\n // Set to the height of the document, allowing scrolling.\n d.sizer = elt(\"div\", [d.mover], \"CodeMirror-sizer\");\n d.sizerWidth = null;\n // Behavior of elts with overflow: auto and padding is\n // inconsistent across browsers. This is used to ensure the\n // scrollable area is big enough.\n d.heightForcer = elt(\"div\", null, null, \"position: absolute; height: \" + scrollerGap + \"px; width: 1px;\");\n // Will contain the gutters, if any.\n d.gutters = elt(\"div\", null, \"CodeMirror-gutters\");\n d.lineGutter = null;\n // Actual scrollable element.\n d.scroller = elt(\"div\", [d.sizer, d.heightForcer, d.gutters], \"CodeMirror-scroll\");\n d.scroller.setAttribute(\"tabIndex\", \"-1\");\n // The element in which the editor lives.\n d.wrapper = elt(\"div\", [d.scrollbarFiller, d.gutterFiller, d.scroller], \"CodeMirror\");\n\n // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)\n if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }\n if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }\n\n if (place) {\n if (place.appendChild) { place.appendChild(d.wrapper); }\n else { place(d.wrapper); }\n }\n\n // Current rendered range (may be bigger than the view window).\n d.viewFrom = d.viewTo = doc.first;\n d.reportedViewFrom = d.reportedViewTo = doc.first;\n // Information about the rendered lines.\n d.view = [];\n d.renderedView = null;\n // Holds info about a single rendered line when it was rendered\n // for measurement, while not in view.\n d.externalMeasured = null;\n // Empty space (in pixels) above the view\n d.viewOffset = 0;\n d.lastWrapHeight = d.lastWrapWidth = 0;\n d.updateLineNumbers = null;\n\n d.nativeBarWidth = d.barHeight = d.barWidth = 0;\n d.scrollbarsClipped = false;\n\n // Used to only resize the line number gutter when necessary (when\n // the amount of lines crosses a boundary that makes its width change)\n d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;\n // Set to true when a non-horizontal-scrolling line widget is\n // added. As an optimization, line widget aligning is skipped when\n // this is false.\n d.alignWidgets = false;\n\n d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n\n // Tracks the maximum line length so that the horizontal scrollbar\n // can be kept static when scrolling.\n d.maxLine = null;\n d.maxLineLength = 0;\n d.maxLineChanged = false;\n\n // Used for measuring wheel scrolling granularity\n d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;\n\n // True when shift is held down.\n d.shift = false;\n\n // Used to track whether anything happened since the context menu\n // was opened.\n d.selForContextMenu = null;\n\n d.activeTouch = null;\n\n input.init(d);\n }\n\n // Find the line object corresponding to the given line number.\n function getLine(doc, n) {\n n -= doc.first;\n if (n < 0 || n >= doc.size) { throw new Error(\"There is no line \" + (n + doc.first) + \" in the document.\") }\n var chunk = doc;\n while (!chunk.lines) {\n for (var i = 0;; ++i) {\n var child = chunk.children[i], sz = child.chunkSize();\n if (n < sz) { chunk = child; break }\n n -= sz;\n }\n }\n return chunk.lines[n]\n }\n\n // Get the part of a document between two positions, as an array of\n // strings.\n function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }\n // Get the lines between from and to, as array of strings.\n function getLines(doc, from, to) {\n var out = [];\n doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value\n return out\n }\n\n // Update the height of a line, propagating the height change\n // upwards to parent nodes.\n function updateLineHeight(line, height) {\n var diff = height - line.height;\n if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }\n }\n\n // Given a line object, find its line number by walking up through\n // its parent links.\n function lineNo(line) {\n if (line.parent == null) { return null }\n var cur = line.parent, no = indexOf(cur.lines, line);\n for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {\n for (var i = 0;; ++i) {\n if (chunk.children[i] == cur) { break }\n no += chunk.children[i].chunkSize();\n }\n }\n return no + cur.first\n }\n\n // Find the line at the given vertical position, using the height\n // information in the document tree.\n function lineAtHeight(chunk, h) {\n var n = chunk.first;\n outer: do {\n for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {\n var child = chunk.children[i$1], ch = child.height;\n if (h < ch) { chunk = child; continue outer }\n h -= ch;\n n += child.chunkSize();\n }\n return n\n } while (!chunk.lines)\n var i = 0;\n for (; i < chunk.lines.length; ++i) {\n var line = chunk.lines[i], lh = line.height;\n if (h < lh) { break }\n h -= lh;\n }\n return n + i\n }\n\n function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}\n\n function lineNumberFor(options, i) {\n return String(options.lineNumberFormatter(i + options.firstLineNumber))\n }\n\n // A Pos instance represents a position within the text.\n function Pos(line, ch, sticky) {\n if ( sticky === void 0 ) sticky = null;\n\n if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }\n this.line = line;\n this.ch = ch;\n this.sticky = sticky;\n }\n\n // Compare two positions, return 0 if they are the same, a negative\n // number when a is less, and a positive number otherwise.\n function cmp(a, b) { return a.line - b.line || a.ch - b.ch }\n\n function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }\n\n function copyPos(x) {return Pos(x.line, x.ch)}\n function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }\n function minPos(a, b) { return cmp(a, b) < 0 ? a : b }\n\n // Most of the external API clips given positions to make sure they\n // actually exist within the document.\n function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}\n function clipPos(doc, pos) {\n if (pos.line < doc.first) { return Pos(doc.first, 0) }\n var last = doc.first + doc.size - 1;\n if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }\n return clipToLen(pos, getLine(doc, pos.line).text.length)\n }\n function clipToLen(pos, linelen) {\n var ch = pos.ch;\n if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }\n else if (ch < 0) { return Pos(pos.line, 0) }\n else { return pos }\n }\n function clipPosArray(doc, array) {\n var out = [];\n for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }\n return out\n }\n\n // Optimize some code when these features are not used.\n var sawReadOnlySpans = false, sawCollapsedSpans = false;\n\n function seeReadOnlySpans() {\n sawReadOnlySpans = true;\n }\n\n function seeCollapsedSpans() {\n sawCollapsedSpans = true;\n }\n\n // TEXTMARKER SPANS\n\n function MarkedSpan(marker, from, to) {\n this.marker = marker;\n this.from = from; this.to = to;\n }\n\n // Search an array of spans for a span matching the given marker.\n function getMarkedSpanFor(spans, marker) {\n if (spans) { for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if (span.marker == marker) { return span }\n } }\n }\n // Remove a span from an array, returning undefined if no spans are\n // left (we don't store arrays for lines without spans).\n function removeMarkedSpan(spans, span) {\n var r;\n for (var i = 0; i < spans.length; ++i)\n { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }\n return r\n }\n // Add a span to a line.\n function addMarkedSpan(line, span) {\n line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];\n span.marker.attachLine(line);\n }\n\n // Used for the algorithm that adjusts markers for a change in the\n // document. These functions cut an array of spans at a given\n // character position, returning an array of remaining chunks (or\n // undefined if nothing remains).\n function markedSpansBefore(old, startCh, isInsert) {\n var nw;\n if (old) { for (var i = 0; i < old.length; ++i) {\n var span = old[i], marker = span.marker;\n var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);\n if (startsBefore || span.from == startCh && marker.type == \"bookmark\" && (!isInsert || !span.marker.insertLeft)) {\n var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)\n ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));\n }\n } }\n return nw\n }\n function markedSpansAfter(old, endCh, isInsert) {\n var nw;\n if (old) { for (var i = 0; i < old.length; ++i) {\n var span = old[i], marker = span.marker;\n var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);\n if (endsAfter || span.from == endCh && marker.type == \"bookmark\" && (!isInsert || span.marker.insertLeft)) {\n var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)\n ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,\n span.to == null ? null : span.to - endCh));\n }\n } }\n return nw\n }\n\n // Given a change object, compute the new set of marker spans that\n // cover the line in which the change took place. Removes spans\n // entirely within the change, reconnects spans belonging to the\n // same marker that appear on both sides of the change, and cuts off\n // spans partially within the change. Returns an array of span\n // arrays with one element for each line in (after) the change.\n function stretchSpansOverChange(doc, change) {\n if (change.full) { return null }\n var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;\n var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;\n if (!oldFirst && !oldLast) { return null }\n\n var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;\n // Get the spans that 'stick out' on both sides\n var first = markedSpansBefore(oldFirst, startCh, isInsert);\n var last = markedSpansAfter(oldLast, endCh, isInsert);\n\n // Next, merge those two ends\n var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);\n if (first) {\n // Fix up .to properties of first\n for (var i = 0; i < first.length; ++i) {\n var span = first[i];\n if (span.to == null) {\n var found = getMarkedSpanFor(last, span.marker);\n if (!found) { span.to = startCh; }\n else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }\n }\n }\n }\n if (last) {\n // Fix up .from in last (or move them into first in case of sameLine)\n for (var i$1 = 0; i$1 < last.length; ++i$1) {\n var span$1 = last[i$1];\n if (span$1.to != null) { span$1.to += offset; }\n if (span$1.from == null) {\n var found$1 = getMarkedSpanFor(first, span$1.marker);\n if (!found$1) {\n span$1.from = offset;\n if (sameLine) { (first || (first = [])).push(span$1); }\n }\n } else {\n span$1.from += offset;\n if (sameLine) { (first || (first = [])).push(span$1); }\n }\n }\n }\n // Make sure we didn't create any zero-length spans\n if (first) { first = clearEmptySpans(first); }\n if (last && last != first) { last = clearEmptySpans(last); }\n\n var newMarkers = [first];\n if (!sameLine) {\n // Fill gap with whole-line-spans\n var gap = change.text.length - 2, gapMarkers;\n if (gap > 0 && first)\n { for (var i$2 = 0; i$2 < first.length; ++i$2)\n { if (first[i$2].to == null)\n { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }\n for (var i$3 = 0; i$3 < gap; ++i$3)\n { newMarkers.push(gapMarkers); }\n newMarkers.push(last);\n }\n return newMarkers\n }\n\n // Remove spans that are empty and don't have a clearWhenEmpty\n // option of false.\n function clearEmptySpans(spans) {\n for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)\n { spans.splice(i--, 1); }\n }\n if (!spans.length) { return null }\n return spans\n }\n\n // Used to 'clip' out readOnly ranges when making a change.\n function removeReadOnlyRanges(doc, from, to) {\n var markers = null;\n doc.iter(from.line, to.line + 1, function (line) {\n if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {\n var mark = line.markedSpans[i].marker;\n if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))\n { (markers || (markers = [])).push(mark); }\n } }\n });\n if (!markers) { return null }\n var parts = [{from: from, to: to}];\n for (var i = 0; i < markers.length; ++i) {\n var mk = markers[i], m = mk.find(0);\n for (var j = 0; j < parts.length; ++j) {\n var p = parts[j];\n if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }\n var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);\n if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)\n { newParts.push({from: p.from, to: m.from}); }\n if (dto > 0 || !mk.inclusiveRight && !dto)\n { newParts.push({from: m.to, to: p.to}); }\n parts.splice.apply(parts, newParts);\n j += newParts.length - 3;\n }\n }\n return parts\n }\n\n // Connect or disconnect spans from a line.\n function detachMarkedSpans(line) {\n var spans = line.markedSpans;\n if (!spans) { return }\n for (var i = 0; i < spans.length; ++i)\n { spans[i].marker.detachLine(line); }\n line.markedSpans = null;\n }\n function attachMarkedSpans(line, spans) {\n if (!spans) { return }\n for (var i = 0; i < spans.length; ++i)\n { spans[i].marker.attachLine(line); }\n line.markedSpans = spans;\n }\n\n // Helpers used when computing which overlapping collapsed span\n // counts as the larger one.\n function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }\n function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }\n\n // Returns a number indicating which of two overlapping collapsed\n // spans is larger (and thus includes the other). Falls back to\n // comparing ids when the spans cover exactly the same range.\n function compareCollapsedMarkers(a, b) {\n var lenDiff = a.lines.length - b.lines.length;\n if (lenDiff != 0) { return lenDiff }\n var aPos = a.find(), bPos = b.find();\n var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);\n if (fromCmp) { return -fromCmp }\n var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);\n if (toCmp) { return toCmp }\n return b.id - a.id\n }\n\n // Find out whether a line ends or starts in a collapsed span. If\n // so, return the marker for that span.\n function collapsedSpanAtSide(line, start) {\n var sps = sawCollapsedSpans && line.markedSpans, found;\n if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {\n sp = sps[i];\n if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&\n (!found || compareCollapsedMarkers(found, sp.marker) < 0))\n { found = sp.marker; }\n } }\n return found\n }\n function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }\n function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }\n\n function collapsedSpanAround(line, ch) {\n var sps = sawCollapsedSpans && line.markedSpans, found;\n if (sps) { for (var i = 0; i < sps.length; ++i) {\n var sp = sps[i];\n if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&\n (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }\n } }\n return found\n }\n\n // Test whether there exists a collapsed span that partially\n // overlaps (covers the start or end, but not both) of a new span.\n // Such overlap is not allowed.\n function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {\n var line = getLine(doc, lineNo$$1);\n var sps = sawCollapsedSpans && line.markedSpans;\n if (sps) { for (var i = 0; i < sps.length; ++i) {\n var sp = sps[i];\n if (!sp.marker.collapsed) { continue }\n var found = sp.marker.find(0);\n var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);\n var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);\n if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }\n if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||\n fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))\n { return true }\n } }\n }\n\n // A visual line is a line as drawn on the screen. Folding, for\n // example, can cause multiple logical lines to appear on the same\n // visual line. This finds the start of the visual line that the\n // given line is part of (usually that is the line itself).\n function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }\n\n function visualLineEnd(line) {\n var merged;\n while (merged = collapsedSpanAtEnd(line))\n { line = merged.find(1, true).line; }\n return line\n }\n\n // Returns an array of logical lines that continue the visual line\n // started by the argument, or undefined if there are no such lines.\n function visualLineContinued(line) {\n var merged, lines;\n while (merged = collapsedSpanAtEnd(line)) {\n line = merged.find(1, true).line\n ;(lines || (lines = [])).push(line);\n }\n return lines\n }\n\n // Get the line number of the start of the visual line that the\n // given line number is part of.\n function visualLineNo(doc, lineN) {\n var line = getLine(doc, lineN), vis = visualLine(line);\n if (line == vis) { return lineN }\n return lineNo(vis)\n }\n\n // Get the line number of the start of the next visual line after\n // the given line.\n function visualLineEndNo(doc, lineN) {\n if (lineN > doc.lastLine()) { return lineN }\n var line = getLine(doc, lineN), merged;\n if (!lineIsHidden(doc, line)) { return lineN }\n while (merged = collapsedSpanAtEnd(line))\n { line = merged.find(1, true).line; }\n return lineNo(line) + 1\n }\n\n // Compute whether a line is hidden. Lines count as hidden when they\n // are part of a visual line that starts with another line, or when\n // they are entirely covered by collapsed, non-widget span.\n function lineIsHidden(doc, line) {\n var sps = sawCollapsedSpans && line.markedSpans;\n if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {\n sp = sps[i];\n if (!sp.marker.collapsed) { continue }\n if (sp.from == null) { return true }\n if (sp.marker.widgetNode) { continue }\n if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))\n { return true }\n } }\n }\n function lineIsHiddenInner(doc, line, span) {\n if (span.to == null) {\n var end = span.marker.find(1, true);\n return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))\n }\n if (span.marker.inclusiveRight && span.to == line.text.length)\n { return true }\n for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {\n sp = line.markedSpans[i];\n if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&\n (sp.to == null || sp.to != span.from) &&\n (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&\n lineIsHiddenInner(doc, line, sp)) { return true }\n }\n }\n\n // Find the height above the given line.\n function heightAtLine(lineObj) {\n lineObj = visualLine(lineObj);\n\n var h = 0, chunk = lineObj.parent;\n for (var i = 0; i < chunk.lines.length; ++i) {\n var line = chunk.lines[i];\n if (line == lineObj) { break }\n else { h += line.height; }\n }\n for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n for (var i$1 = 0; i$1 < p.children.length; ++i$1) {\n var cur = p.children[i$1];\n if (cur == chunk) { break }\n else { h += cur.height; }\n }\n }\n return h\n }\n\n // Compute the character length of a line, taking into account\n // collapsed ranges (see markText) that might hide parts, and join\n // other lines onto it.\n function lineLength(line) {\n if (line.height == 0) { return 0 }\n var len = line.text.length, merged, cur = line;\n while (merged = collapsedSpanAtStart(cur)) {\n var found = merged.find(0, true);\n cur = found.from.line;\n len += found.from.ch - found.to.ch;\n }\n cur = line;\n while (merged = collapsedSpanAtEnd(cur)) {\n var found$1 = merged.find(0, true);\n len -= cur.text.length - found$1.from.ch;\n cur = found$1.to.line;\n len += cur.text.length - found$1.to.ch;\n }\n return len\n }\n\n // Find the longest line in the document.\n function findMaxLine(cm) {\n var d = cm.display, doc = cm.doc;\n d.maxLine = getLine(doc, doc.first);\n d.maxLineLength = lineLength(d.maxLine);\n d.maxLineChanged = true;\n doc.iter(function (line) {\n var len = lineLength(line);\n if (len > d.maxLineLength) {\n d.maxLineLength = len;\n d.maxLine = line;\n }\n });\n }\n\n // BIDI HELPERS\n\n function iterateBidiSections(order, from, to, f) {\n if (!order) { return f(from, to, \"ltr\", 0) }\n var found = false;\n for (var i = 0; i < order.length; ++i) {\n var part = order[i];\n if (part.from < to && part.to > from || from == to && part.to == from) {\n f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? \"rtl\" : \"ltr\", i);\n found = true;\n }\n }\n if (!found) { f(from, to, \"ltr\"); }\n }\n\n var bidiOther = null;\n function getBidiPartAt(order, ch, sticky) {\n var found;\n bidiOther = null;\n for (var i = 0; i < order.length; ++i) {\n var cur = order[i];\n if (cur.from < ch && cur.to > ch) { return i }\n if (cur.to == ch) {\n if (cur.from != cur.to && sticky == \"before\") { found = i; }\n else { bidiOther = i; }\n }\n if (cur.from == ch) {\n if (cur.from != cur.to && sticky != \"before\") { found = i; }\n else { bidiOther = i; }\n }\n }\n return found != null ? found : bidiOther\n }\n\n // Bidirectional ordering algorithm\n // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm\n // that this (partially) implements.\n\n // One-char codes used for character types:\n // L (L): Left-to-Right\n // R (R): Right-to-Left\n // r (AL): Right-to-Left Arabic\n // 1 (EN): European Number\n // + (ES): European Number Separator\n // % (ET): European Number Terminator\n // n (AN): Arabic Number\n // , (CS): Common Number Separator\n // m (NSM): Non-Spacing Mark\n // b (BN): Boundary Neutral\n // s (B): Paragraph Separator\n // t (S): Segment Separator\n // w (WS): Whitespace\n // N (ON): Other Neutrals\n\n // Returns null if characters are ordered as they appear\n // (left-to-right), or an array of sections ({from, to, level}\n // objects) in the order in which they occur visually.\n var bidiOrdering = (function() {\n // Character types for codepoints 0 to 0xff\n var lowTypes = \"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN\";\n // Character types for codepoints 0x600 to 0x6f9\n var arabicTypes = \"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111\";\n function charType(code) {\n if (code <= 0xf7) { return lowTypes.charAt(code) }\n else if (0x590 <= code && code <= 0x5f4) { return \"R\" }\n else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }\n else if (0x6ee <= code && code <= 0x8ac) { return \"r\" }\n else if (0x2000 <= code && code <= 0x200b) { return \"w\" }\n else if (code == 0x200c) { return \"b\" }\n else { return \"L\" }\n }\n\n var bidiRE = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;\n\n function BidiSpan(level, from, to) {\n this.level = level;\n this.from = from; this.to = to;\n }\n\n return function(str, direction) {\n var outerType = direction == \"ltr\" ? \"L\" : \"R\";\n\n if (str.length == 0 || direction == \"ltr\" && !bidiRE.test(str)) { return false }\n var len = str.length, types = [];\n for (var i = 0; i < len; ++i)\n { types.push(charType(str.charCodeAt(i))); }\n\n // W1. Examine each non-spacing mark (NSM) in the level run, and\n // change the type of the NSM to the type of the previous\n // character. If the NSM is at the start of the level run, it will\n // get the type of sor.\n for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {\n var type = types[i$1];\n if (type == \"m\") { types[i$1] = prev; }\n else { prev = type; }\n }\n\n // W2. Search backwards from each instance of a European number\n // until the first strong type (R, L, AL, or sor) is found. If an\n // AL is found, change the type of the European number to Arabic\n // number.\n // W3. Change all ALs to R.\n for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {\n var type$1 = types[i$2];\n if (type$1 == \"1\" && cur == \"r\") { types[i$2] = \"n\"; }\n else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == \"r\") { types[i$2] = \"R\"; } }\n }\n\n // W4. A single European separator between two European numbers\n // changes to a European number. A single common separator between\n // two numbers of the same type changes to that type.\n for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {\n var type$2 = types[i$3];\n if (type$2 == \"+\" && prev$1 == \"1\" && types[i$3+1] == \"1\") { types[i$3] = \"1\"; }\n else if (type$2 == \",\" && prev$1 == types[i$3+1] &&\n (prev$1 == \"1\" || prev$1 == \"n\")) { types[i$3] = prev$1; }\n prev$1 = type$2;\n }\n\n // W5. A sequence of European terminators adjacent to European\n // numbers changes to all European numbers.\n // W6. Otherwise, separators and terminators change to Other\n // Neutral.\n for (var i$4 = 0; i$4 < len; ++i$4) {\n var type$3 = types[i$4];\n if (type$3 == \",\") { types[i$4] = \"N\"; }\n else if (type$3 == \"%\") {\n var end = (void 0);\n for (end = i$4 + 1; end < len && types[end] == \"%\"; ++end) {}\n var replace = (i$4 && types[i$4-1] == \"!\") || (end < len && types[end] == \"1\") ? \"1\" : \"N\";\n for (var j = i$4; j < end; ++j) { types[j] = replace; }\n i$4 = end - 1;\n }\n }\n\n // W7. Search backwards from each instance of a European number\n // until the first strong type (R, L, or sor) is found. If an L is\n // found, then change the type of the European number to L.\n for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {\n var type$4 = types[i$5];\n if (cur$1 == \"L\" && type$4 == \"1\") { types[i$5] = \"L\"; }\n else if (isStrong.test(type$4)) { cur$1 = type$4; }\n }\n\n // N1. A sequence of neutrals takes the direction of the\n // surrounding strong text if the text on both sides has the same\n // direction. European and Arabic numbers act as if they were R in\n // terms of their influence on neutrals. Start-of-level-run (sor)\n // and end-of-level-run (eor) are used at level run boundaries.\n // N2. Any remaining neutrals take the embedding direction.\n for (var i$6 = 0; i$6 < len; ++i$6) {\n if (isNeutral.test(types[i$6])) {\n var end$1 = (void 0);\n for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}\n var before = (i$6 ? types[i$6-1] : outerType) == \"L\";\n var after = (end$1 < len ? types[end$1] : outerType) == \"L\";\n var replace$1 = before == after ? (before ? \"L\" : \"R\") : outerType;\n for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }\n i$6 = end$1 - 1;\n }\n }\n\n // Here we depart from the documented algorithm, in order to avoid\n // building up an actual levels array. Since there are only three\n // levels (0, 1, 2) in an implementation that doesn't take\n // explicit embedding into account, we can build up the order on\n // the fly, without following the level-based algorithm.\n var order = [], m;\n for (var i$7 = 0; i$7 < len;) {\n if (countsAsLeft.test(types[i$7])) {\n var start = i$7;\n for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}\n order.push(new BidiSpan(0, start, i$7));\n } else {\n var pos = i$7, at = order.length;\n for (++i$7; i$7 < len && types[i$7] != \"L\"; ++i$7) {}\n for (var j$2 = pos; j$2 < i$7;) {\n if (countsAsNum.test(types[j$2])) {\n if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }\n var nstart = j$2;\n for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}\n order.splice(at, 0, new BidiSpan(2, nstart, j$2));\n pos = j$2;\n } else { ++j$2; }\n }\n if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }\n }\n }\n if (direction == \"ltr\") {\n if (order[0].level == 1 && (m = str.match(/^\\s+/))) {\n order[0].from = m[0].length;\n order.unshift(new BidiSpan(0, 0, m[0].length));\n }\n if (lst(order).level == 1 && (m = str.match(/\\s+$/))) {\n lst(order).to -= m[0].length;\n order.push(new BidiSpan(0, len - m[0].length, len));\n }\n }\n\n return direction == \"rtl\" ? order.reverse() : order\n }\n })();\n\n // Get the bidi ordering for the given line (and cache it). Returns\n // false for lines that are fully left-to-right, and an array of\n // BidiSpan objects otherwise.\n function getOrder(line, direction) {\n var order = line.order;\n if (order == null) { order = line.order = bidiOrdering(line.text, direction); }\n return order\n }\n\n // EVENT HANDLING\n\n // Lightweight event framework. on/off also work on DOM nodes,\n // registering native DOM handlers.\n\n var noHandlers = [];\n\n var on = function(emitter, type, f) {\n if (emitter.addEventListener) {\n emitter.addEventListener(type, f, false);\n } else if (emitter.attachEvent) {\n emitter.attachEvent(\"on\" + type, f);\n } else {\n var map$$1 = emitter._handlers || (emitter._handlers = {});\n map$$1[type] = (map$$1[type] || noHandlers).concat(f);\n }\n };\n\n function getHandlers(emitter, type) {\n return emitter._handlers && emitter._handlers[type] || noHandlers\n }\n\n function off(emitter, type, f) {\n if (emitter.removeEventListener) {\n emitter.removeEventListener(type, f, false);\n } else if (emitter.detachEvent) {\n emitter.detachEvent(\"on\" + type, f);\n } else {\n var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];\n if (arr) {\n var index = indexOf(arr, f);\n if (index > -1)\n { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }\n }\n }\n }\n\n function signal(emitter, type /*, values...*/) {\n var handlers = getHandlers(emitter, type);\n if (!handlers.length) { return }\n var args = Array.prototype.slice.call(arguments, 2);\n for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }\n }\n\n // The DOM events that CodeMirror handles can be overridden by\n // registering a (non-DOM) handler on the editor for the event name,\n // and preventDefault-ing the event in that handler.\n function signalDOMEvent(cm, e, override) {\n if (typeof e == \"string\")\n { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }\n signal(cm, override || e.type, cm, e);\n return e_defaultPrevented(e) || e.codemirrorIgnore\n }\n\n function signalCursorActivity(cm) {\n var arr = cm._handlers && cm._handlers.cursorActivity;\n if (!arr) { return }\n var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);\n for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)\n { set.push(arr[i]); } }\n }\n\n function hasHandler(emitter, type) {\n return getHandlers(emitter, type).length > 0\n }\n\n // Add on and off methods to a constructor's prototype, to make\n // registering events on such objects more convenient.\n function eventMixin(ctor) {\n ctor.prototype.on = function(type, f) {on(this, type, f);};\n ctor.prototype.off = function(type, f) {off(this, type, f);};\n }\n\n // Due to the fact that we still support jurassic IE versions, some\n // compatibility wrappers are needed.\n\n function e_preventDefault(e) {\n if (e.preventDefault) { e.preventDefault(); }\n else { e.returnValue = false; }\n }\n function e_stopPropagation(e) {\n if (e.stopPropagation) { e.stopPropagation(); }\n else { e.cancelBubble = true; }\n }\n function e_defaultPrevented(e) {\n return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false\n }\n function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}\n\n function e_target(e) {return e.target || e.srcElement}\n function e_button(e) {\n var b = e.which;\n if (b == null) {\n if (e.button & 1) { b = 1; }\n else if (e.button & 2) { b = 3; }\n else if (e.button & 4) { b = 2; }\n }\n if (mac && e.ctrlKey && b == 1) { b = 3; }\n return b\n }\n\n // Detect drag-and-drop\n var dragAndDrop = function() {\n // There is *some* kind of drag-and-drop support in IE6-8, but I\n // couldn't get it to work yet.\n if (ie && ie_version < 9) { return false }\n var div = elt('div');\n return \"draggable\" in div || \"dragDrop\" in div\n }();\n\n var zwspSupported;\n function zeroWidthElement(measure) {\n if (zwspSupported == null) {\n var test = elt(\"span\", \"\\u200b\");\n removeChildrenAndAdd(measure, elt(\"span\", [test, document.createTextNode(\"x\")]));\n if (measure.firstChild.offsetHeight != 0)\n { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }\n }\n var node = zwspSupported ? elt(\"span\", \"\\u200b\") :\n elt(\"span\", \"\\u00a0\", null, \"display: inline-block; width: 1px; margin-right: -1px\");\n node.setAttribute(\"cm-text\", \"\");\n return node\n }\n\n // Feature-detect IE's crummy client rect reporting for bidi text\n var badBidiRects;\n function hasBadBidiRects(measure) {\n if (badBidiRects != null) { return badBidiRects }\n var txt = removeChildrenAndAdd(measure, document.createTextNode(\"A\\u062eA\"));\n var r0 = range(txt, 0, 1).getBoundingClientRect();\n var r1 = range(txt, 1, 2).getBoundingClientRect();\n removeChildren(measure);\n if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)\n return badBidiRects = (r1.right - r0.right < 3)\n }\n\n // See if \"\".split is the broken IE version, if so, provide an\n // alternative way to split lines.\n var splitLinesAuto = \"\\n\\nb\".split(/\\n/).length != 3 ? function (string) {\n var pos = 0, result = [], l = string.length;\n while (pos <= l) {\n var nl = string.indexOf(\"\\n\", pos);\n if (nl == -1) { nl = string.length; }\n var line = string.slice(pos, string.charAt(nl - 1) == \"\\r\" ? nl - 1 : nl);\n var rt = line.indexOf(\"\\r\");\n if (rt != -1) {\n result.push(line.slice(0, rt));\n pos += rt + 1;\n } else {\n result.push(line);\n pos = nl + 1;\n }\n }\n return result\n } : function (string) { return string.split(/\\r\\n?|\\n/); };\n\n var hasSelection = window.getSelection ? function (te) {\n try { return te.selectionStart != te.selectionEnd }\n catch(e) { return false }\n } : function (te) {\n var range$$1;\n try {range$$1 = te.ownerDocument.selection.createRange();}\n catch(e) {}\n if (!range$$1 || range$$1.parentElement() != te) { return false }\n return range$$1.compareEndPoints(\"StartToEnd\", range$$1) != 0\n };\n\n var hasCopyEvent = (function () {\n var e = elt(\"div\");\n if (\"oncopy\" in e) { return true }\n e.setAttribute(\"oncopy\", \"return;\");\n return typeof e.oncopy == \"function\"\n })();\n\n var badZoomedRects = null;\n function hasBadZoomedRects(measure) {\n if (badZoomedRects != null) { return badZoomedRects }\n var node = removeChildrenAndAdd(measure, elt(\"span\", \"x\"));\n var normal = node.getBoundingClientRect();\n var fromRange = range(node, 0, 1).getBoundingClientRect();\n return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1\n }\n\n // Known modes, by name and by MIME\n var modes = {}, mimeModes = {};\n\n // Extra arguments are stored as the mode's dependencies, which is\n // used by (legacy) mechanisms like loadmode.js to automatically\n // load a mode. (Preferred mechanism is the require/define calls.)\n function defineMode(name, mode) {\n if (arguments.length > 2)\n { mode.dependencies = Array.prototype.slice.call(arguments, 2); }\n modes[name] = mode;\n }\n\n function defineMIME(mime, spec) {\n mimeModes[mime] = spec;\n }\n\n // Given a MIME type, a {name, ...options} config object, or a name\n // string, return a mode config object.\n function resolveMode(spec) {\n if (typeof spec == \"string\" && mimeModes.hasOwnProperty(spec)) {\n spec = mimeModes[spec];\n } else if (spec && typeof spec.name == \"string\" && mimeModes.hasOwnProperty(spec.name)) {\n var found = mimeModes[spec.name];\n if (typeof found == \"string\") { found = {name: found}; }\n spec = createObj(found, spec);\n spec.name = found.name;\n } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+xml$/.test(spec)) {\n return resolveMode(\"application/xml\")\n } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+json$/.test(spec)) {\n return resolveMode(\"application/json\")\n }\n if (typeof spec == \"string\") { return {name: spec} }\n else { return spec || {name: \"null\"} }\n }\n\n // Given a mode spec (anything that resolveMode accepts), find and\n // initialize an actual mode object.\n function getMode(options, spec) {\n spec = resolveMode(spec);\n var mfactory = modes[spec.name];\n if (!mfactory) { return getMode(options, \"text/plain\") }\n var modeObj = mfactory(options, spec);\n if (modeExtensions.hasOwnProperty(spec.name)) {\n var exts = modeExtensions[spec.name];\n for (var prop in exts) {\n if (!exts.hasOwnProperty(prop)) { continue }\n if (modeObj.hasOwnProperty(prop)) { modeObj[\"_\" + prop] = modeObj[prop]; }\n modeObj[prop] = exts[prop];\n }\n }\n modeObj.name = spec.name;\n if (spec.helperType) { modeObj.helperType = spec.helperType; }\n if (spec.modeProps) { for (var prop$1 in spec.modeProps)\n { modeObj[prop$1] = spec.modeProps[prop$1]; } }\n\n return modeObj\n }\n\n // This can be used to attach properties to mode objects from\n // outside the actual mode definition.\n var modeExtensions = {};\n function extendMode(mode, properties) {\n var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});\n copyObj(properties, exts);\n }\n\n function copyState(mode, state) {\n if (state === true) { return state }\n if (mode.copyState) { return mode.copyState(state) }\n var nstate = {};\n for (var n in state) {\n var val = state[n];\n if (val instanceof Array) { val = val.concat([]); }\n nstate[n] = val;\n }\n return nstate\n }\n\n // Given a mode and a state (for that mode), find the inner mode and\n // state at the position that the state refers to.\n function innerMode(mode, state) {\n var info;\n while (mode.innerMode) {\n info = mode.innerMode(state);\n if (!info || info.mode == mode) { break }\n state = info.state;\n mode = info.mode;\n }\n return info || {mode: mode, state: state}\n }\n\n function startState(mode, a1, a2) {\n return mode.startState ? mode.startState(a1, a2) : true\n }\n\n // STRING STREAM\n\n // Fed to the mode parsers, provides helper functions to make\n // parsers more succinct.\n\n var StringStream = function(string, tabSize, lineOracle) {\n this.pos = this.start = 0;\n this.string = string;\n this.tabSize = tabSize || 8;\n this.lastColumnPos = this.lastColumnValue = 0;\n this.lineStart = 0;\n this.lineOracle = lineOracle;\n };\n\n StringStream.prototype.eol = function () {return this.pos >= this.string.length};\n StringStream.prototype.sol = function () {return this.pos == this.lineStart};\n StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};\n StringStream.prototype.next = function () {\n if (this.pos < this.string.length)\n { return this.string.charAt(this.pos++) }\n };\n StringStream.prototype.eat = function (match) {\n var ch = this.string.charAt(this.pos);\n var ok;\n if (typeof match == \"string\") { ok = ch == match; }\n else { ok = ch && (match.test ? match.test(ch) : match(ch)); }\n if (ok) {++this.pos; return ch}\n };\n StringStream.prototype.eatWhile = function (match) {\n var start = this.pos;\n while (this.eat(match)){}\n return this.pos > start\n };\n StringStream.prototype.eatSpace = function () {\n var this$1 = this;\n\n var start = this.pos;\n while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }\n return this.pos > start\n };\n StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};\n StringStream.prototype.skipTo = function (ch) {\n var found = this.string.indexOf(ch, this.pos);\n if (found > -1) {this.pos = found; return true}\n };\n StringStream.prototype.backUp = function (n) {this.pos -= n;};\n StringStream.prototype.column = function () {\n if (this.lastColumnPos < this.start) {\n this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);\n this.lastColumnPos = this.start;\n }\n return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n };\n StringStream.prototype.indentation = function () {\n return countColumn(this.string, null, this.tabSize) -\n (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n };\n StringStream.prototype.match = function (pattern, consume, caseInsensitive) {\n if (typeof pattern == \"string\") {\n var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };\n var substr = this.string.substr(this.pos, pattern.length);\n if (cased(substr) == cased(pattern)) {\n if (consume !== false) { this.pos += pattern.length; }\n return true\n }\n } else {\n var match = this.string.slice(this.pos).match(pattern);\n if (match && match.index > 0) { return null }\n if (match && consume !== false) { this.pos += match[0].length; }\n return match\n }\n };\n StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};\n StringStream.prototype.hideFirstChars = function (n, inner) {\n this.lineStart += n;\n try { return inner() }\n finally { this.lineStart -= n; }\n };\n StringStream.prototype.lookAhead = function (n) {\n var oracle = this.lineOracle;\n return oracle && oracle.lookAhead(n)\n };\n StringStream.prototype.baseToken = function () {\n var oracle = this.lineOracle;\n return oracle && oracle.baseToken(this.pos)\n };\n\n var SavedContext = function(state, lookAhead) {\n this.state = state;\n this.lookAhead = lookAhead;\n };\n\n var Context = function(doc, state, line, lookAhead) {\n this.state = state;\n this.doc = doc;\n this.line = line;\n this.maxLookAhead = lookAhead || 0;\n this.baseTokens = null;\n this.baseTokenPos = 1;\n };\n\n Context.prototype.lookAhead = function (n) {\n var line = this.doc.getLine(this.line + n);\n if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }\n return line\n };\n\n Context.prototype.baseToken = function (n) {\n var this$1 = this;\n\n if (!this.baseTokens) { return null }\n while (this.baseTokens[this.baseTokenPos] <= n)\n { this$1.baseTokenPos += 2; }\n var type = this.baseTokens[this.baseTokenPos + 1];\n return {type: type && type.replace(/( |^)overlay .*/, \"\"),\n size: this.baseTokens[this.baseTokenPos] - n}\n };\n\n Context.prototype.nextLine = function () {\n this.line++;\n if (this.maxLookAhead > 0) { this.maxLookAhead--; }\n };\n\n Context.fromSaved = function (doc, saved, line) {\n if (saved instanceof SavedContext)\n { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }\n else\n { return new Context(doc, copyState(doc.mode, saved), line) }\n };\n\n Context.prototype.save = function (copy) {\n var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;\n return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state\n };\n\n\n // Compute a style array (an array starting with a mode generation\n // -- for invalidation -- followed by pairs of end positions and\n // style strings), which is used to highlight the tokens on the\n // line.\n function highlightLine(cm, line, context, forceToEnd) {\n // A styles array always starts with a number identifying the\n // mode/overlays that it is based on (for easy invalidation).\n var st = [cm.state.modeGen], lineClasses = {};\n // Compute the base array of styles\n runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },\n lineClasses, forceToEnd);\n var state = context.state;\n\n // Run overlays, adjust style array.\n var loop = function ( o ) {\n context.baseTokens = st;\n var overlay = cm.state.overlays[o], i = 1, at = 0;\n context.state = true;\n runMode(cm, line.text, overlay.mode, context, function (end, style) {\n var start = i;\n // Ensure there's a token end at the current position, and that i points at it\n while (at < end) {\n var i_end = st[i];\n if (i_end > end)\n { st.splice(i, 1, end, st[i+1], i_end); }\n i += 2;\n at = Math.min(end, i_end);\n }\n if (!style) { return }\n if (overlay.opaque) {\n st.splice(start, i - start, end, \"overlay \" + style);\n i = start + 2;\n } else {\n for (; start < i; start += 2) {\n var cur = st[start+1];\n st[start+1] = (cur ? cur + \" \" : \"\") + \"overlay \" + style;\n }\n }\n }, lineClasses);\n context.state = state;\n context.baseTokens = null;\n context.baseTokenPos = 1;\n };\n\n for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );\n\n return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}\n }\n\n function getLineStyles(cm, line, updateFrontier) {\n if (!line.styles || line.styles[0] != cm.state.modeGen) {\n var context = getContextBefore(cm, lineNo(line));\n var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);\n var result = highlightLine(cm, line, context);\n if (resetState) { context.state = resetState; }\n line.stateAfter = context.save(!resetState);\n line.styles = result.styles;\n if (result.classes) { line.styleClasses = result.classes; }\n else if (line.styleClasses) { line.styleClasses = null; }\n if (updateFrontier === cm.doc.highlightFrontier)\n { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }\n }\n return line.styles\n }\n\n function getContextBefore(cm, n, precise) {\n var doc = cm.doc, display = cm.display;\n if (!doc.mode.startState) { return new Context(doc, true, n) }\n var start = findStartLine(cm, n, precise);\n var saved = start > doc.first && getLine(doc, start - 1).stateAfter;\n var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);\n\n doc.iter(start, n, function (line) {\n processLine(cm, line.text, context);\n var pos = context.line;\n line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;\n context.nextLine();\n });\n if (precise) { doc.modeFrontier = context.line; }\n return context\n }\n\n // Lightweight form of highlight -- proceed over this line and\n // update state, but don't save a style array. Used for lines that\n // aren't currently visible.\n function processLine(cm, text, context, startAt) {\n var mode = cm.doc.mode;\n var stream = new StringStream(text, cm.options.tabSize, context);\n stream.start = stream.pos = startAt || 0;\n if (text == \"\") { callBlankLine(mode, context.state); }\n while (!stream.eol()) {\n readToken(mode, stream, context.state);\n stream.start = stream.pos;\n }\n }\n\n function callBlankLine(mode, state) {\n if (mode.blankLine) { return mode.blankLine(state) }\n if (!mode.innerMode) { return }\n var inner = innerMode(mode, state);\n if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }\n }\n\n function readToken(mode, stream, state, inner) {\n for (var i = 0; i < 10; i++) {\n if (inner) { inner[0] = innerMode(mode, state).mode; }\n var style = mode.token(stream, state);\n if (stream.pos > stream.start) { return style }\n }\n throw new Error(\"Mode \" + mode.name + \" failed to advance stream.\")\n }\n\n var Token = function(stream, type, state) {\n this.start = stream.start; this.end = stream.pos;\n this.string = stream.current();\n this.type = type || null;\n this.state = state;\n };\n\n // Utility for getTokenAt and getLineTokens\n function takeToken(cm, pos, precise, asArray) {\n var doc = cm.doc, mode = doc.mode, style;\n pos = clipPos(doc, pos);\n var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);\n var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;\n if (asArray) { tokens = []; }\n while ((asArray || stream.pos < pos.ch) && !stream.eol()) {\n stream.start = stream.pos;\n style = readToken(mode, stream, context.state);\n if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }\n }\n return asArray ? tokens : new Token(stream, style, context.state)\n }\n\n function extractLineClasses(type, output) {\n if (type) { for (;;) {\n var lineClass = type.match(/(?:^|\\s+)line-(background-)?(\\S+)/);\n if (!lineClass) { break }\n type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);\n var prop = lineClass[1] ? \"bgClass\" : \"textClass\";\n if (output[prop] == null)\n { output[prop] = lineClass[2]; }\n else if (!(new RegExp(\"(?:^|\\s)\" + lineClass[2] + \"(?:$|\\s)\")).test(output[prop]))\n { output[prop] += \" \" + lineClass[2]; }\n } }\n return type\n }\n\n // Run the given mode's parser over a line, calling f for each token.\n function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {\n var flattenSpans = mode.flattenSpans;\n if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }\n var curStart = 0, curStyle = null;\n var stream = new StringStream(text, cm.options.tabSize, context), style;\n var inner = cm.options.addModeClass && [null];\n if (text == \"\") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }\n while (!stream.eol()) {\n if (stream.pos > cm.options.maxHighlightLength) {\n flattenSpans = false;\n if (forceToEnd) { processLine(cm, text, context, stream.pos); }\n stream.pos = text.length;\n style = null;\n } else {\n style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);\n }\n if (inner) {\n var mName = inner[0].name;\n if (mName) { style = \"m-\" + (style ? mName + \" \" + style : mName); }\n }\n if (!flattenSpans || curStyle != style) {\n while (curStart < stream.start) {\n curStart = Math.min(stream.start, curStart + 5000);\n f(curStart, curStyle);\n }\n curStyle = style;\n }\n stream.start = stream.pos;\n }\n while (curStart < stream.pos) {\n // Webkit seems to refuse to render text nodes longer than 57444\n // characters, and returns inaccurate measurements in nodes\n // starting around 5000 chars.\n var pos = Math.min(stream.pos, curStart + 5000);\n f(pos, curStyle);\n curStart = pos;\n }\n }\n\n // Finds the line to start with when starting a parse. Tries to\n // find a line with a stateAfter, so that it can start with a\n // valid state. If that fails, it returns the line with the\n // smallest indentation, which tends to need the least context to\n // parse correctly.\n function findStartLine(cm, n, precise) {\n var minindent, minline, doc = cm.doc;\n var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);\n for (var search = n; search > lim; --search) {\n if (search <= doc.first) { return doc.first }\n var line = getLine(doc, search - 1), after = line.stateAfter;\n if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))\n { return search }\n var indented = countColumn(line.text, null, cm.options.tabSize);\n if (minline == null || minindent > indented) {\n minline = search - 1;\n minindent = indented;\n }\n }\n return minline\n }\n\n function retreatFrontier(doc, n) {\n doc.modeFrontier = Math.min(doc.modeFrontier, n);\n if (doc.highlightFrontier < n - 10) { return }\n var start = doc.first;\n for (var line = n - 1; line > start; line--) {\n var saved = getLine(doc, line).stateAfter;\n // change is on 3\n // state on line 1 looked ahead 2 -- so saw 3\n // test 1 + 2 < 3 should cover this\n if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {\n start = line + 1;\n break\n }\n }\n doc.highlightFrontier = Math.min(doc.highlightFrontier, start);\n }\n\n // LINE DATA STRUCTURE\n\n // Line objects. These hold state related to a line, including\n // highlighting info (the styles array).\n var Line = function(text, markedSpans, estimateHeight) {\n this.text = text;\n attachMarkedSpans(this, markedSpans);\n this.height = estimateHeight ? estimateHeight(this) : 1;\n };\n\n Line.prototype.lineNo = function () { return lineNo(this) };\n eventMixin(Line);\n\n // Change the content (text, markers) of a line. Automatically\n // invalidates cached information and tries to re-estimate the\n // line's height.\n function updateLine(line, text, markedSpans, estimateHeight) {\n line.text = text;\n if (line.stateAfter) { line.stateAfter = null; }\n if (line.styles) { line.styles = null; }\n if (line.order != null) { line.order = null; }\n detachMarkedSpans(line);\n attachMarkedSpans(line, markedSpans);\n var estHeight = estimateHeight ? estimateHeight(line) : 1;\n if (estHeight != line.height) { updateLineHeight(line, estHeight); }\n }\n\n // Detach a line from the document tree and its markers.\n function cleanUpLine(line) {\n line.parent = null;\n detachMarkedSpans(line);\n }\n\n // Convert a style as returned by a mode (either null, or a string\n // containing one or more styles) to a CSS style. This is cached,\n // and also looks for line-wide styles.\n var styleToClassCache = {}, styleToClassCacheWithMode = {};\n function interpretTokenStyle(style, options) {\n if (!style || /^\\s*$/.test(style)) { return null }\n var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;\n return cache[style] ||\n (cache[style] = style.replace(/\\S+/g, \"cm-$&\"))\n }\n\n // Render the DOM representation of the text of a line. Also builds\n // up a 'line map', which points at the DOM nodes that represent\n // specific stretches of text, and is used by the measuring code.\n // The returned object contains the DOM node, this map, and\n // information about line-wide styles that were set by the mode.\n function buildLineContent(cm, lineView) {\n // The padding-right forces the element to have a 'border', which\n // is needed on Webkit to be able to get line-level bounding\n // rectangles for it (in measureChar).\n var content = eltP(\"span\", null, null, webkit ? \"padding-right: .1px\" : null);\n var builder = {pre: eltP(\"pre\", [content], \"CodeMirror-line\"), content: content,\n col: 0, pos: 0, cm: cm,\n trailingSpace: false,\n splitSpaces: cm.getOption(\"lineWrapping\")};\n lineView.measure = {};\n\n // Iterate over the logical lines that make up this visual line.\n for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {\n var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);\n builder.pos = 0;\n builder.addToken = buildToken;\n // Optionally wire in some hacks into the token-rendering\n // algorithm, to deal with browser quirks.\n if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))\n { builder.addToken = buildTokenBadBidi(builder.addToken, order); }\n builder.map = [];\n var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);\n insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));\n if (line.styleClasses) {\n if (line.styleClasses.bgClass)\n { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || \"\"); }\n if (line.styleClasses.textClass)\n { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || \"\"); }\n }\n\n // Ensure at least a single node is present, for measuring.\n if (builder.map.length == 0)\n { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }\n\n // Store the map and a cache object for the current logical line\n if (i == 0) {\n lineView.measure.map = builder.map;\n lineView.measure.cache = {};\n } else {\n (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)\n ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});\n }\n }\n\n // See issue #2901\n if (webkit) {\n var last = builder.content.lastChild;\n if (/\\bcm-tab\\b/.test(last.className) || (last.querySelector && last.querySelector(\".cm-tab\")))\n { builder.content.className = \"cm-tab-wrap-hack\"; }\n }\n\n signal(cm, \"renderLine\", cm, lineView.line, builder.pre);\n if (builder.pre.className)\n { builder.textClass = joinClasses(builder.pre.className, builder.textClass || \"\"); }\n\n return builder\n }\n\n function defaultSpecialCharPlaceholder(ch) {\n var token = elt(\"span\", \"\\u2022\", \"cm-invalidchar\");\n token.title = \"\\\\u\" + ch.charCodeAt(0).toString(16);\n token.setAttribute(\"aria-label\", token.title);\n return token\n }\n\n // Build up the DOM representation for a single token, and add it to\n // the line map. Takes care to render special characters separately.\n function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {\n if (!text) { return }\n var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;\n var special = builder.cm.state.specialChars, mustWrap = false;\n var content;\n if (!special.test(text)) {\n builder.col += text.length;\n content = document.createTextNode(displayText);\n builder.map.push(builder.pos, builder.pos + text.length, content);\n if (ie && ie_version < 9) { mustWrap = true; }\n builder.pos += text.length;\n } else {\n content = document.createDocumentFragment();\n var pos = 0;\n while (true) {\n special.lastIndex = pos;\n var m = special.exec(text);\n var skipped = m ? m.index - pos : text.length - pos;\n if (skipped) {\n var txt = document.createTextNode(displayText.slice(pos, pos + skipped));\n if (ie && ie_version < 9) { content.appendChild(elt(\"span\", [txt])); }\n else { content.appendChild(txt); }\n builder.map.push(builder.pos, builder.pos + skipped, txt);\n builder.col += skipped;\n builder.pos += skipped;\n }\n if (!m) { break }\n pos += skipped + 1;\n var txt$1 = (void 0);\n if (m[0] == \"\\t\") {\n var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;\n txt$1 = content.appendChild(elt(\"span\", spaceStr(tabWidth), \"cm-tab\"));\n txt$1.setAttribute(\"role\", \"presentation\");\n txt$1.setAttribute(\"cm-text\", \"\\t\");\n builder.col += tabWidth;\n } else if (m[0] == \"\\r\" || m[0] == \"\\n\") {\n txt$1 = content.appendChild(elt(\"span\", m[0] == \"\\r\" ? \"\\u240d\" : \"\\u2424\", \"cm-invalidchar\"));\n txt$1.setAttribute(\"cm-text\", m[0]);\n builder.col += 1;\n } else {\n txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);\n txt$1.setAttribute(\"cm-text\", m[0]);\n if (ie && ie_version < 9) { content.appendChild(elt(\"span\", [txt$1])); }\n else { content.appendChild(txt$1); }\n builder.col += 1;\n }\n builder.map.push(builder.pos, builder.pos + 1, txt$1);\n builder.pos++;\n }\n }\n builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;\n if (style || startStyle || endStyle || mustWrap || css) {\n var fullStyle = style || \"\";\n if (startStyle) { fullStyle += startStyle; }\n if (endStyle) { fullStyle += endStyle; }\n var token = elt(\"span\", [content], fullStyle, css);\n if (attributes) {\n for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != \"style\" && attr != \"class\")\n { token.setAttribute(attr, attributes[attr]); } }\n }\n return builder.content.appendChild(token)\n }\n builder.content.appendChild(content);\n }\n\n // Change some spaces to NBSP to prevent the browser from collapsing\n // trailing spaces at the end of a line when rendering text (issue #1362).\n function splitSpaces(text, trailingBefore) {\n if (text.length > 1 && !/ /.test(text)) { return text }\n var spaceBefore = trailingBefore, result = \"\";\n for (var i = 0; i < text.length; i++) {\n var ch = text.charAt(i);\n if (ch == \" \" && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))\n { ch = \"\\u00a0\"; }\n result += ch;\n spaceBefore = ch == \" \";\n }\n return result\n }\n\n // Work around nonsense dimensions being reported for stretches of\n // right-to-left text.\n function buildTokenBadBidi(inner, order) {\n return function (builder, text, style, startStyle, endStyle, css, attributes) {\n style = style ? style + \" cm-force-border\" : \"cm-force-border\";\n var start = builder.pos, end = start + text.length;\n for (;;) {\n // Find the part that overlaps with the start of this text\n var part = (void 0);\n for (var i = 0; i < order.length; i++) {\n part = order[i];\n if (part.to > start && part.from <= start) { break }\n }\n if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }\n inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);\n startStyle = null;\n text = text.slice(part.to - start);\n start = part.to;\n }\n }\n }\n\n function buildCollapsedSpan(builder, size, marker, ignoreWidget) {\n var widget = !ignoreWidget && marker.widgetNode;\n if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }\n if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {\n if (!widget)\n { widget = builder.content.appendChild(document.createElement(\"span\")); }\n widget.setAttribute(\"cm-marker\", marker.id);\n }\n if (widget) {\n builder.cm.display.input.setUneditable(widget);\n builder.content.appendChild(widget);\n }\n builder.pos += size;\n builder.trailingSpace = false;\n }\n\n // Outputs a number of spans to make up a line, taking highlighting\n // and marked text into account.\n function insertLineContent(line, builder, styles) {\n var spans = line.markedSpans, allText = line.text, at = 0;\n if (!spans) {\n for (var i$1 = 1; i$1 < styles.length; i$1+=2)\n { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }\n return\n }\n\n var len = allText.length, pos = 0, i = 1, text = \"\", style, css;\n var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;\n for (;;) {\n if (nextChange == pos) { // Update current marker set\n spanStyle = spanEndStyle = spanStartStyle = css = \"\";\n attributes = null;\n collapsed = null; nextChange = Infinity;\n var foundBookmarks = [], endStyles = (void 0);\n for (var j = 0; j < spans.length; ++j) {\n var sp = spans[j], m = sp.marker;\n if (m.type == \"bookmark\" && sp.from == pos && m.widgetNode) {\n foundBookmarks.push(m);\n } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {\n if (sp.to != null && sp.to != pos && nextChange > sp.to) {\n nextChange = sp.to;\n spanEndStyle = \"\";\n }\n if (m.className) { spanStyle += \" \" + m.className; }\n if (m.css) { css = (css ? css + \";\" : \"\") + m.css; }\n if (m.startStyle && sp.from == pos) { spanStartStyle += \" \" + m.startStyle; }\n if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }\n // support for the old title property\n // https://github.com/codemirror/CodeMirror/pull/5673\n if (m.title) { (attributes || (attributes = {})).title = m.title; }\n if (m.attributes) {\n for (var attr in m.attributes)\n { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }\n }\n if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))\n { collapsed = sp; }\n } else if (sp.from > pos && nextChange > sp.from) {\n nextChange = sp.from;\n }\n }\n if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)\n { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += \" \" + endStyles[j$1]; } } }\n\n if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)\n { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }\n if (collapsed && (collapsed.from || 0) == pos) {\n buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,\n collapsed.marker, collapsed.from == null);\n if (collapsed.to == null) { return }\n if (collapsed.to == pos) { collapsed = false; }\n }\n }\n if (pos >= len) { break }\n\n var upto = Math.min(len, nextChange);\n while (true) {\n if (text) {\n var end = pos + text.length;\n if (!collapsed) {\n var tokenText = end > upto ? text.slice(0, upto - pos) : text;\n builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,\n spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : \"\", css, attributes);\n }\n if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}\n pos = end;\n spanStartStyle = \"\";\n }\n text = allText.slice(at, at = styles[i++]);\n style = interpretTokenStyle(styles[i++], builder.cm.options);\n }\n }\n }\n\n\n // These objects are used to represent the visible (currently drawn)\n // part of the document. A LineView may correspond to multiple\n // logical lines, if those are connected by collapsed ranges.\n function LineView(doc, line, lineN) {\n // The starting line\n this.line = line;\n // Continuing lines, if any\n this.rest = visualLineContinued(line);\n // Number of logical lines in this visual line\n this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;\n this.node = this.text = null;\n this.hidden = lineIsHidden(doc, line);\n }\n\n // Create a range of LineView objects for the given lines.\n function buildViewArray(cm, from, to) {\n var array = [], nextPos;\n for (var pos = from; pos < to; pos = nextPos) {\n var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);\n nextPos = pos + view.size;\n array.push(view);\n }\n return array\n }\n\n var operationGroup = null;\n\n function pushOperation(op) {\n if (operationGroup) {\n operationGroup.ops.push(op);\n } else {\n op.ownsGroup = operationGroup = {\n ops: [op],\n delayedCallbacks: []\n };\n }\n }\n\n function fireCallbacksForOps(group) {\n // Calls delayed callbacks and cursorActivity handlers until no\n // new ones appear\n var callbacks = group.delayedCallbacks, i = 0;\n do {\n for (; i < callbacks.length; i++)\n { callbacks[i].call(null); }\n for (var j = 0; j < group.ops.length; j++) {\n var op = group.ops[j];\n if (op.cursorActivityHandlers)\n { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)\n { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }\n }\n } while (i < callbacks.length)\n }\n\n function finishOperation(op, endCb) {\n var group = op.ownsGroup;\n if (!group) { return }\n\n try { fireCallbacksForOps(group); }\n finally {\n operationGroup = null;\n endCb(group);\n }\n }\n\n var orphanDelayedCallbacks = null;\n\n // Often, we want to signal events at a point where we are in the\n // middle of some work, but don't want the handler to start calling\n // other methods on the editor, which might be in an inconsistent\n // state or simply not expect any other events to happen.\n // signalLater looks whether there are any handlers, and schedules\n // them to be executed when the last operation ends, or, if no\n // operation is active, when a timeout fires.\n function signalLater(emitter, type /*, values...*/) {\n var arr = getHandlers(emitter, type);\n if (!arr.length) { return }\n var args = Array.prototype.slice.call(arguments, 2), list;\n if (operationGroup) {\n list = operationGroup.delayedCallbacks;\n } else if (orphanDelayedCallbacks) {\n list = orphanDelayedCallbacks;\n } else {\n list = orphanDelayedCallbacks = [];\n setTimeout(fireOrphanDelayed, 0);\n }\n var loop = function ( i ) {\n list.push(function () { return arr[i].apply(null, args); });\n };\n\n for (var i = 0; i < arr.length; ++i)\n loop( i );\n }\n\n function fireOrphanDelayed() {\n var delayed = orphanDelayedCallbacks;\n orphanDelayedCallbacks = null;\n for (var i = 0; i < delayed.length; ++i) { delayed[i](); }\n }\n\n // When an aspect of a line changes, a string is added to\n // lineView.changes. This updates the relevant part of the line's\n // DOM structure.\n function updateLineForChanges(cm, lineView, lineN, dims) {\n for (var j = 0; j < lineView.changes.length; j++) {\n var type = lineView.changes[j];\n if (type == \"text\") { updateLineText(cm, lineView); }\n else if (type == \"gutter\") { updateLineGutter(cm, lineView, lineN, dims); }\n else if (type == \"class\") { updateLineClasses(cm, lineView); }\n else if (type == \"widget\") { updateLineWidgets(cm, lineView, dims); }\n }\n lineView.changes = null;\n }\n\n // Lines with gutter elements, widgets or a background class need to\n // be wrapped, and have the extra elements added to the wrapper div\n function ensureLineWrapped(lineView) {\n if (lineView.node == lineView.text) {\n lineView.node = elt(\"div\", null, null, \"position: relative\");\n if (lineView.text.parentNode)\n { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }\n lineView.node.appendChild(lineView.text);\n if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }\n }\n return lineView.node\n }\n\n function updateLineBackground(cm, lineView) {\n var cls = lineView.bgClass ? lineView.bgClass + \" \" + (lineView.line.bgClass || \"\") : lineView.line.bgClass;\n if (cls) { cls += \" CodeMirror-linebackground\"; }\n if (lineView.background) {\n if (cls) { lineView.background.className = cls; }\n else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }\n } else if (cls) {\n var wrap = ensureLineWrapped(lineView);\n lineView.background = wrap.insertBefore(elt(\"div\", null, cls), wrap.firstChild);\n cm.display.input.setUneditable(lineView.background);\n }\n }\n\n // Wrapper around buildLineContent which will reuse the structure\n // in display.externalMeasured when possible.\n function getLineContent(cm, lineView) {\n var ext = cm.display.externalMeasured;\n if (ext && ext.line == lineView.line) {\n cm.display.externalMeasured = null;\n lineView.measure = ext.measure;\n return ext.built\n }\n return buildLineContent(cm, lineView)\n }\n\n // Redraw the line's text. Interacts with the background and text\n // classes because the mode may output tokens that influence these\n // classes.\n function updateLineText(cm, lineView) {\n var cls = lineView.text.className;\n var built = getLineContent(cm, lineView);\n if (lineView.text == lineView.node) { lineView.node = built.pre; }\n lineView.text.parentNode.replaceChild(built.pre, lineView.text);\n lineView.text = built.pre;\n if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {\n lineView.bgClass = built.bgClass;\n lineView.textClass = built.textClass;\n updateLineClasses(cm, lineView);\n } else if (cls) {\n lineView.text.className = cls;\n }\n }\n\n function updateLineClasses(cm, lineView) {\n updateLineBackground(cm, lineView);\n if (lineView.line.wrapClass)\n { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }\n else if (lineView.node != lineView.text)\n { lineView.node.className = \"\"; }\n var textClass = lineView.textClass ? lineView.textClass + \" \" + (lineView.line.textClass || \"\") : lineView.line.textClass;\n lineView.text.className = textClass || \"\";\n }\n\n function updateLineGutter(cm, lineView, lineN, dims) {\n if (lineView.gutter) {\n lineView.node.removeChild(lineView.gutter);\n lineView.gutter = null;\n }\n if (lineView.gutterBackground) {\n lineView.node.removeChild(lineView.gutterBackground);\n lineView.gutterBackground = null;\n }\n if (lineView.line.gutterClass) {\n var wrap = ensureLineWrapped(lineView);\n lineView.gutterBackground = elt(\"div\", null, \"CodeMirror-gutter-background \" + lineView.line.gutterClass,\n (\"left: \" + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + \"px; width: \" + (dims.gutterTotalWidth) + \"px\"));\n cm.display.input.setUneditable(lineView.gutterBackground);\n wrap.insertBefore(lineView.gutterBackground, lineView.text);\n }\n var markers = lineView.line.gutterMarkers;\n if (cm.options.lineNumbers || markers) {\n var wrap$1 = ensureLineWrapped(lineView);\n var gutterWrap = lineView.gutter = elt(\"div\", null, \"CodeMirror-gutter-wrapper\", (\"left: \" + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + \"px\"));\n cm.display.input.setUneditable(gutterWrap);\n wrap$1.insertBefore(gutterWrap, lineView.text);\n if (lineView.line.gutterClass)\n { gutterWrap.className += \" \" + lineView.line.gutterClass; }\n if (cm.options.lineNumbers && (!markers || !markers[\"CodeMirror-linenumbers\"]))\n { lineView.lineNumber = gutterWrap.appendChild(\n elt(\"div\", lineNumberFor(cm.options, lineN),\n \"CodeMirror-linenumber CodeMirror-gutter-elt\",\n (\"left: \" + (dims.gutterLeft[\"CodeMirror-linenumbers\"]) + \"px; width: \" + (cm.display.lineNumInnerWidth) + \"px\"))); }\n if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {\n var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];\n if (found)\n { gutterWrap.appendChild(elt(\"div\", [found], \"CodeMirror-gutter-elt\",\n (\"left: \" + (dims.gutterLeft[id]) + \"px; width: \" + (dims.gutterWidth[id]) + \"px\"))); }\n } }\n }\n }\n\n function updateLineWidgets(cm, lineView, dims) {\n if (lineView.alignable) { lineView.alignable = null; }\n for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {\n next = node.nextSibling;\n if (node.className == \"CodeMirror-linewidget\")\n { lineView.node.removeChild(node); }\n }\n insertLineWidgets(cm, lineView, dims);\n }\n\n // Build a line's DOM representation from scratch\n function buildLineElement(cm, lineView, lineN, dims) {\n var built = getLineContent(cm, lineView);\n lineView.text = lineView.node = built.pre;\n if (built.bgClass) { lineView.bgClass = built.bgClass; }\n if (built.textClass) { lineView.textClass = built.textClass; }\n\n updateLineClasses(cm, lineView);\n updateLineGutter(cm, lineView, lineN, dims);\n insertLineWidgets(cm, lineView, dims);\n return lineView.node\n }\n\n // A lineView may contain multiple logical lines (when merged by\n // collapsed spans). The widgets for all of them need to be drawn.\n function insertLineWidgets(cm, lineView, dims) {\n insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);\n if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)\n { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }\n }\n\n function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {\n if (!line.widgets) { return }\n var wrap = ensureLineWrapped(lineView);\n for (var i = 0, ws = line.widgets; i < ws.length; ++i) {\n var widget = ws[i], node = elt(\"div\", [widget.node], \"CodeMirror-linewidget\");\n if (!widget.handleMouseEvents) { node.setAttribute(\"cm-ignore-events\", \"true\"); }\n positionLineWidget(widget, node, lineView, dims);\n cm.display.input.setUneditable(node);\n if (allowAbove && widget.above)\n { wrap.insertBefore(node, lineView.gutter || lineView.text); }\n else\n { wrap.appendChild(node); }\n signalLater(widget, \"redraw\");\n }\n }\n\n function positionLineWidget(widget, node, lineView, dims) {\n if (widget.noHScroll) {\n (lineView.alignable || (lineView.alignable = [])).push(node);\n var width = dims.wrapperWidth;\n node.style.left = dims.fixedPos + \"px\";\n if (!widget.coverGutter) {\n width -= dims.gutterTotalWidth;\n node.style.paddingLeft = dims.gutterTotalWidth + \"px\";\n }\n node.style.width = width + \"px\";\n }\n if (widget.coverGutter) {\n node.style.zIndex = 5;\n node.style.position = \"relative\";\n if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + \"px\"; }\n }\n }\n\n function widgetHeight(widget) {\n if (widget.height != null) { return widget.height }\n var cm = widget.doc.cm;\n if (!cm) { return 0 }\n if (!contains(document.body, widget.node)) {\n var parentStyle = \"position: relative;\";\n if (widget.coverGutter)\n { parentStyle += \"margin-left: -\" + cm.display.gutters.offsetWidth + \"px;\"; }\n if (widget.noHScroll)\n { parentStyle += \"width: \" + cm.display.wrapper.clientWidth + \"px;\"; }\n removeChildrenAndAdd(cm.display.measure, elt(\"div\", [widget.node], null, parentStyle));\n }\n return widget.height = widget.node.parentNode.offsetHeight\n }\n\n // Return true when the given mouse event happened in a widget\n function eventInWidget(display, e) {\n for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {\n if (!n || (n.nodeType == 1 && n.getAttribute(\"cm-ignore-events\") == \"true\") ||\n (n.parentNode == display.sizer && n != display.mover))\n { return true }\n }\n }\n\n // POSITION MEASUREMENT\n\n function paddingTop(display) {return display.lineSpace.offsetTop}\n function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}\n function paddingH(display) {\n if (display.cachedPaddingH) { return display.cachedPaddingH }\n var e = removeChildrenAndAdd(display.measure, elt(\"pre\", \"x\"));\n var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;\n var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};\n if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }\n return data\n }\n\n function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }\n function displayWidth(cm) {\n return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth\n }\n function displayHeight(cm) {\n return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight\n }\n\n // Ensure the lineView.wrapping.heights array is populated. This is\n // an array of bottom offsets for the lines that make up a drawn\n // line. When lineWrapping is on, there might be more than one\n // height.\n function ensureLineHeights(cm, lineView, rect) {\n var wrapping = cm.options.lineWrapping;\n var curWidth = wrapping && displayWidth(cm);\n if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {\n var heights = lineView.measure.heights = [];\n if (wrapping) {\n lineView.measure.width = curWidth;\n var rects = lineView.text.firstChild.getClientRects();\n for (var i = 0; i < rects.length - 1; i++) {\n var cur = rects[i], next = rects[i + 1];\n if (Math.abs(cur.bottom - next.bottom) > 2)\n { heights.push((cur.bottom + next.top) / 2 - rect.top); }\n }\n }\n heights.push(rect.bottom - rect.top);\n }\n }\n\n // Find a line map (mapping character offsets to text nodes) and a\n // measurement cache for the given line number. (A line view might\n // contain multiple lines when collapsed ranges are present.)\n function mapFromLineView(lineView, line, lineN) {\n if (lineView.line == line)\n { return {map: lineView.measure.map, cache: lineView.measure.cache} }\n for (var i = 0; i < lineView.rest.length; i++)\n { if (lineView.rest[i] == line)\n { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }\n for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)\n { if (lineNo(lineView.rest[i$1]) > lineN)\n { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }\n }\n\n // Render a line into the hidden node display.externalMeasured. Used\n // when measurement is needed for a line that's not in the viewport.\n function updateExternalMeasurement(cm, line) {\n line = visualLine(line);\n var lineN = lineNo(line);\n var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);\n view.lineN = lineN;\n var built = view.built = buildLineContent(cm, view);\n view.text = built.pre;\n removeChildrenAndAdd(cm.display.lineMeasure, built.pre);\n return view\n }\n\n // Get a {top, bottom, left, right} box (in line-local coordinates)\n // for a given character.\n function measureChar(cm, line, ch, bias) {\n return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)\n }\n\n // Find a line view that corresponds to the given line number.\n function findViewForLine(cm, lineN) {\n if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)\n { return cm.display.view[findViewIndex(cm, lineN)] }\n var ext = cm.display.externalMeasured;\n if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)\n { return ext }\n }\n\n // Measurement can be split in two steps, the set-up work that\n // applies to the whole line, and the measurement of the actual\n // character. Functions like coordsChar, that need to do a lot of\n // measurements in a row, can thus ensure that the set-up work is\n // only done once.\n function prepareMeasureForLine(cm, line) {\n var lineN = lineNo(line);\n var view = findViewForLine(cm, lineN);\n if (view && !view.text) {\n view = null;\n } else if (view && view.changes) {\n updateLineForChanges(cm, view, lineN, getDimensions(cm));\n cm.curOp.forceUpdate = true;\n }\n if (!view)\n { view = updateExternalMeasurement(cm, line); }\n\n var info = mapFromLineView(view, line, lineN);\n return {\n line: line, view: view, rect: null,\n map: info.map, cache: info.cache, before: info.before,\n hasHeights: false\n }\n }\n\n // Given a prepared measurement object, measures the position of an\n // actual character (or fetches it from the cache).\n function measureCharPrepared(cm, prepared, ch, bias, varHeight) {\n if (prepared.before) { ch = -1; }\n var key = ch + (bias || \"\"), found;\n if (prepared.cache.hasOwnProperty(key)) {\n found = prepared.cache[key];\n } else {\n if (!prepared.rect)\n { prepared.rect = prepared.view.text.getBoundingClientRect(); }\n if (!prepared.hasHeights) {\n ensureLineHeights(cm, prepared.view, prepared.rect);\n prepared.hasHeights = true;\n }\n found = measureCharInner(cm, prepared, ch, bias);\n if (!found.bogus) { prepared.cache[key] = found; }\n }\n return {left: found.left, right: found.right,\n top: varHeight ? found.rtop : found.top,\n bottom: varHeight ? found.rbottom : found.bottom}\n }\n\n var nullRect = {left: 0, right: 0, top: 0, bottom: 0};\n\n function nodeAndOffsetInLineMap(map$$1, ch, bias) {\n var node, start, end, collapse, mStart, mEnd;\n // First, search the line map for the text node corresponding to,\n // or closest to, the target character.\n for (var i = 0; i < map$$1.length; i += 3) {\n mStart = map$$1[i];\n mEnd = map$$1[i + 1];\n if (ch < mStart) {\n start = 0; end = 1;\n collapse = \"left\";\n } else if (ch < mEnd) {\n start = ch - mStart;\n end = start + 1;\n } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {\n end = mEnd - mStart;\n start = end - 1;\n if (ch >= mEnd) { collapse = \"right\"; }\n }\n if (start != null) {\n node = map$$1[i + 2];\n if (mStart == mEnd && bias == (node.insertLeft ? \"left\" : \"right\"))\n { collapse = bias; }\n if (bias == \"left\" && start == 0)\n { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {\n node = map$$1[(i -= 3) + 2];\n collapse = \"left\";\n } }\n if (bias == \"right\" && start == mEnd - mStart)\n { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {\n node = map$$1[(i += 3) + 2];\n collapse = \"right\";\n } }\n break\n }\n }\n return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}\n }\n\n function getUsefulRect(rects, bias) {\n var rect = nullRect;\n if (bias == \"left\") { for (var i = 0; i < rects.length; i++) {\n if ((rect = rects[i]).left != rect.right) { break }\n } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {\n if ((rect = rects[i$1]).left != rect.right) { break }\n } }\n return rect\n }\n\n function measureCharInner(cm, prepared, ch, bias) {\n var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);\n var node = place.node, start = place.start, end = place.end, collapse = place.collapse;\n\n var rect;\n if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.\n for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned\n while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }\n while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }\n if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)\n { rect = node.parentNode.getBoundingClientRect(); }\n else\n { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }\n if (rect.left || rect.right || start == 0) { break }\n end = start;\n start = start - 1;\n collapse = \"right\";\n }\n if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }\n } else { // If it is a widget, simply get the box for the whole widget.\n if (start > 0) { collapse = bias = \"right\"; }\n var rects;\n if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)\n { rect = rects[bias == \"right\" ? rects.length - 1 : 0]; }\n else\n { rect = node.getBoundingClientRect(); }\n }\n if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {\n var rSpan = node.parentNode.getClientRects()[0];\n if (rSpan)\n { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }\n else\n { rect = nullRect; }\n }\n\n var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;\n var mid = (rtop + rbot) / 2;\n var heights = prepared.view.measure.heights;\n var i = 0;\n for (; i < heights.length - 1; i++)\n { if (mid < heights[i]) { break } }\n var top = i ? heights[i - 1] : 0, bot = heights[i];\n var result = {left: (collapse == \"right\" ? rect.right : rect.left) - prepared.rect.left,\n right: (collapse == \"left\" ? rect.left : rect.right) - prepared.rect.left,\n top: top, bottom: bot};\n if (!rect.left && !rect.right) { result.bogus = true; }\n if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }\n\n return result\n }\n\n // Work around problem with bounding client rects on ranges being\n // returned incorrectly when zoomed on IE10 and below.\n function maybeUpdateRectForZooming(measure, rect) {\n if (!window.screen || screen.logicalXDPI == null ||\n screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))\n { return rect }\n var scaleX = screen.logicalXDPI / screen.deviceXDPI;\n var scaleY = screen.logicalYDPI / screen.deviceYDPI;\n return {left: rect.left * scaleX, right: rect.right * scaleX,\n top: rect.top * scaleY, bottom: rect.bottom * scaleY}\n }\n\n function clearLineMeasurementCacheFor(lineView) {\n if (lineView.measure) {\n lineView.measure.cache = {};\n lineView.measure.heights = null;\n if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)\n { lineView.measure.caches[i] = {}; } }\n }\n }\n\n function clearLineMeasurementCache(cm) {\n cm.display.externalMeasure = null;\n removeChildren(cm.display.lineMeasure);\n for (var i = 0; i < cm.display.view.length; i++)\n { clearLineMeasurementCacheFor(cm.display.view[i]); }\n }\n\n function clearCaches(cm) {\n clearLineMeasurementCache(cm);\n cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;\n if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }\n cm.display.lineNumChars = null;\n }\n\n function pageScrollX() {\n // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206\n // which causes page_Offset and bounding client rects to use\n // different reference viewports and invalidate our calculations.\n if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }\n return window.pageXOffset || (document.documentElement || document.body).scrollLeft\n }\n function pageScrollY() {\n if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }\n return window.pageYOffset || (document.documentElement || document.body).scrollTop\n }\n\n function widgetTopHeight(lineObj) {\n var height = 0;\n if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)\n { height += widgetHeight(lineObj.widgets[i]); } } }\n return height\n }\n\n // Converts a {top, bottom, left, right} box from line-local\n // coordinates into another coordinate system. Context may be one of\n // \"line\", \"div\" (display.lineDiv), \"local\"./null (editor), \"window\",\n // or \"page\".\n function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {\n if (!includeWidgets) {\n var height = widgetTopHeight(lineObj);\n rect.top += height; rect.bottom += height;\n }\n if (context == \"line\") { return rect }\n if (!context) { context = \"local\"; }\n var yOff = heightAtLine(lineObj);\n if (context == \"local\") { yOff += paddingTop(cm.display); }\n else { yOff -= cm.display.viewOffset; }\n if (context == \"page\" || context == \"window\") {\n var lOff = cm.display.lineSpace.getBoundingClientRect();\n yOff += lOff.top + (context == \"window\" ? 0 : pageScrollY());\n var xOff = lOff.left + (context == \"window\" ? 0 : pageScrollX());\n rect.left += xOff; rect.right += xOff;\n }\n rect.top += yOff; rect.bottom += yOff;\n return rect\n }\n\n // Coverts a box from \"div\" coords to another coordinate system.\n // Context may be \"window\", \"page\", \"div\", or \"local\"./null.\n function fromCoordSystem(cm, coords, context) {\n if (context == \"div\") { return coords }\n var left = coords.left, top = coords.top;\n // First move into \"page\" coordinate system\n if (context == \"page\") {\n left -= pageScrollX();\n top -= pageScrollY();\n } else if (context == \"local\" || !context) {\n var localBox = cm.display.sizer.getBoundingClientRect();\n left += localBox.left;\n top += localBox.top;\n }\n\n var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();\n return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}\n }\n\n function charCoords(cm, pos, context, lineObj, bias) {\n if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }\n return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)\n }\n\n // Returns a box for a given cursor position, which may have an\n // 'other' property containing the position of the secondary cursor\n // on a bidi boundary.\n // A cursor Pos(line, char, \"before\") is on the same visual line as `char - 1`\n // and after `char - 1` in writing order of `char - 1`\n // A cursor Pos(line, char, \"after\") is on the same visual line as `char`\n // and before `char` in writing order of `char`\n // Examples (upper-case letters are RTL, lower-case are LTR):\n // Pos(0, 1, ...)\n // before after\n // ab a|b a|b\n // aB a|B aB|\n // Ab |Ab A|b\n // AB B|A B|A\n // Every position after the last character on a line is considered to stick\n // to the last character on the line.\n function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {\n lineObj = lineObj || getLine(cm.doc, pos.line);\n if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }\n function get(ch, right) {\n var m = measureCharPrepared(cm, preparedMeasure, ch, right ? \"right\" : \"left\", varHeight);\n if (right) { m.left = m.right; } else { m.right = m.left; }\n return intoCoordSystem(cm, lineObj, m, context)\n }\n var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;\n if (ch >= lineObj.text.length) {\n ch = lineObj.text.length;\n sticky = \"before\";\n } else if (ch <= 0) {\n ch = 0;\n sticky = \"after\";\n }\n if (!order) { return get(sticky == \"before\" ? ch - 1 : ch, sticky == \"before\") }\n\n function getBidi(ch, partPos, invert) {\n var part = order[partPos], right = part.level == 1;\n return get(invert ? ch - 1 : ch, right != invert)\n }\n var partPos = getBidiPartAt(order, ch, sticky);\n var other = bidiOther;\n var val = getBidi(ch, partPos, sticky == \"before\");\n if (other != null) { val.other = getBidi(ch, other, sticky != \"before\"); }\n return val\n }\n\n // Used to cheaply estimate the coordinates for a position. Used for\n // intermediate scroll updates.\n function estimateCoords(cm, pos) {\n var left = 0;\n pos = clipPos(cm.doc, pos);\n if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }\n var lineObj = getLine(cm.doc, pos.line);\n var top = heightAtLine(lineObj) + paddingTop(cm.display);\n return {left: left, right: left, top: top, bottom: top + lineObj.height}\n }\n\n // Positions returned by coordsChar contain some extra information.\n // xRel is the relative x position of the input coordinates compared\n // to the found position (so xRel > 0 means the coordinates are to\n // the right of the character position, for example). When outside\n // is true, that means the coordinates lie outside the line's\n // vertical range.\n function PosWithInfo(line, ch, sticky, outside, xRel) {\n var pos = Pos(line, ch, sticky);\n pos.xRel = xRel;\n if (outside) { pos.outside = true; }\n return pos\n }\n\n // Compute the character position closest to the given coordinates.\n // Input must be lineSpace-local (\"div\" coordinate system).\n function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }\n\n function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {\n y -= widgetTopHeight(lineObj);\n var end = lineObj.text.length;\n var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);\n end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);\n return {begin: begin, end: end}\n }\n\n function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {\n if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }\n var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), \"line\").top;\n return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)\n }\n\n // Returns true if the given side of a box is after the given\n // coordinates, in top-to-bottom, left-to-right order.\n function boxIsAfter(box, x, y, left) {\n return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x\n }\n\n function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {\n // Move y into line-local coordinate space\n y -= heightAtLine(lineObj);\n var preparedMeasure = prepareMeasureForLine(cm, lineObj);\n // When directly calling `measureCharPrepared`, we have to adjust\n // for the widgets at this line.\n var widgetHeight$$1 = widgetTopHeight(lineObj);\n var begin = 0, end = lineObj.text.length, ltr = true;\n\n var order = getOrder(lineObj, cm.doc.direction);\n // If the line isn't plain left-to-right text, first figure out\n // which bidi section the coordinates fall into.\n if (order) {\n var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)\n (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);\n ltr = part.level != 1;\n // The awkward -1 offsets are needed because findFirst (called\n // on these below) will treat its first bound as inclusive,\n // second as exclusive, but we want to actually address the\n // characters in the part's range\n begin = ltr ? part.from : part.to - 1;\n end = ltr ? part.to : part.from - 1;\n }\n\n // A binary search to find the first character whose bounding box\n // starts after the coordinates. If we run across any whose box wrap\n // the coordinates, store that.\n var chAround = null, boxAround = null;\n var ch = findFirst(function (ch) {\n var box = measureCharPrepared(cm, preparedMeasure, ch);\n box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;\n if (!boxIsAfter(box, x, y, false)) { return false }\n if (box.top <= y && box.left <= x) {\n chAround = ch;\n boxAround = box;\n }\n return true\n }, begin, end);\n\n var baseX, sticky, outside = false;\n // If a box around the coordinates was found, use that\n if (boxAround) {\n // Distinguish coordinates nearer to the left or right side of the box\n var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;\n ch = chAround + (atStart ? 0 : 1);\n sticky = atStart ? \"after\" : \"before\";\n baseX = atLeft ? boxAround.left : boxAround.right;\n } else {\n // (Adjust for extended bound, if necessary.)\n if (!ltr && (ch == end || ch == begin)) { ch++; }\n // To determine which side to associate with, get the box to the\n // left of the character and compare it's vertical position to the\n // coordinates\n sticky = ch == 0 ? \"after\" : ch == lineObj.text.length ? \"before\" :\n (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?\n \"after\" : \"before\";\n // Now get accurate coordinates for this place, in order to get a\n // base X position\n var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), \"line\", lineObj, preparedMeasure);\n baseX = coords.left;\n outside = y < coords.top || y >= coords.bottom;\n }\n\n ch = skipExtendingChars(lineObj.text, ch, 1);\n return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)\n }\n\n function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {\n // Bidi parts are sorted left-to-right, and in a non-line-wrapping\n // situation, we can take this ordering to correspond to the visual\n // ordering. This finds the first part whose end is after the given\n // coordinates.\n var index = findFirst(function (i) {\n var part = order[i], ltr = part.level != 1;\n return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? \"before\" : \"after\"),\n \"line\", lineObj, preparedMeasure), x, y, true)\n }, 0, order.length - 1);\n var part = order[index];\n // If this isn't the first part, the part's start is also after\n // the coordinates, and the coordinates aren't on the same line as\n // that start, move one part back.\n if (index > 0) {\n var ltr = part.level != 1;\n var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? \"after\" : \"before\"),\n \"line\", lineObj, preparedMeasure);\n if (boxIsAfter(start, x, y, true) && start.top > y)\n { part = order[index - 1]; }\n }\n return part\n }\n\n function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {\n // In a wrapped line, rtl text on wrapping boundaries can do things\n // that don't correspond to the ordering in our `order` array at\n // all, so a binary search doesn't work, and we want to return a\n // part that only spans one line so that the binary search in\n // coordsCharInner is safe. As such, we first find the extent of the\n // wrapped line, and then do a flat search in which we discard any\n // spans that aren't on the line.\n var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);\n var begin = ref.begin;\n var end = ref.end;\n if (/\\s/.test(lineObj.text.charAt(end - 1))) { end--; }\n var part = null, closestDist = null;\n for (var i = 0; i < order.length; i++) {\n var p = order[i];\n if (p.from >= end || p.to <= begin) { continue }\n var ltr = p.level != 1;\n var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;\n // Weigh against spans ending before this, so that they are only\n // picked if nothing ends after\n var dist = endX < x ? x - endX + 1e9 : endX - x;\n if (!part || closestDist > dist) {\n part = p;\n closestDist = dist;\n }\n }\n if (!part) { part = order[order.length - 1]; }\n // Clip the part to the wrapped line.\n if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }\n if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }\n return part\n }\n\n var measureText;\n // Compute the default text height.\n function textHeight(display) {\n if (display.cachedTextHeight != null) { return display.cachedTextHeight }\n if (measureText == null) {\n measureText = elt(\"pre\");\n // Measure a bunch of lines, for browsers that compute\n // fractional heights.\n for (var i = 0; i < 49; ++i) {\n measureText.appendChild(document.createTextNode(\"x\"));\n measureText.appendChild(elt(\"br\"));\n }\n measureText.appendChild(document.createTextNode(\"x\"));\n }\n removeChildrenAndAdd(display.measure, measureText);\n var height = measureText.offsetHeight / 50;\n if (height > 3) { display.cachedTextHeight = height; }\n removeChildren(display.measure);\n return height || 1\n }\n\n // Compute the default character width.\n function charWidth(display) {\n if (display.cachedCharWidth != null) { return display.cachedCharWidth }\n var anchor = elt(\"span\", \"xxxxxxxxxx\");\n var pre = elt(\"pre\", [anchor]);\n removeChildrenAndAdd(display.measure, pre);\n var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;\n if (width > 2) { display.cachedCharWidth = width; }\n return width || 10\n }\n\n // Do a bulk-read of the DOM positions and sizes needed to draw the\n // view, so that we don't interleave reading and writing to the DOM.\n function getDimensions(cm) {\n var d = cm.display, left = {}, width = {};\n var gutterLeft = d.gutters.clientLeft;\n for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {\n left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;\n width[cm.options.gutters[i]] = n.clientWidth;\n }\n return {fixedPos: compensateForHScroll(d),\n gutterTotalWidth: d.gutters.offsetWidth,\n gutterLeft: left,\n gutterWidth: width,\n wrapperWidth: d.wrapper.clientWidth}\n }\n\n // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,\n // but using getBoundingClientRect to get a sub-pixel-accurate\n // result.\n function compensateForHScroll(display) {\n return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left\n }\n\n // Returns a function that estimates the height of a line, to use as\n // first approximation until the line becomes visible (and is thus\n // properly measurable).\n function estimateHeight(cm) {\n var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;\n var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);\n return function (line) {\n if (lineIsHidden(cm.doc, line)) { return 0 }\n\n var widgetsHeight = 0;\n if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {\n if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }\n } }\n\n if (wrapping)\n { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }\n else\n { return widgetsHeight + th }\n }\n }\n\n function estimateLineHeights(cm) {\n var doc = cm.doc, est = estimateHeight(cm);\n doc.iter(function (line) {\n var estHeight = est(line);\n if (estHeight != line.height) { updateLineHeight(line, estHeight); }\n });\n }\n\n // Given a mouse event, find the corresponding position. If liberal\n // is false, it checks whether a gutter or scrollbar was clicked,\n // and returns null if it was. forRect is used by rectangular\n // selections, and tries to estimate a character position even for\n // coordinates beyond the right of the text.\n function posFromMouse(cm, e, liberal, forRect) {\n var display = cm.display;\n if (!liberal && e_target(e).getAttribute(\"cm-not-content\") == \"true\") { return null }\n\n var x, y, space = display.lineSpace.getBoundingClientRect();\n // Fails unpredictably on IE[67] when mouse is dragged around quickly.\n try { x = e.clientX - space.left; y = e.clientY - space.top; }\n catch (e) { return null }\n var coords = coordsChar(cm, x, y), line;\n if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {\n var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;\n coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));\n }\n return coords\n }\n\n // Find the view element corresponding to a given line. Return null\n // when the line isn't visible.\n function findViewIndex(cm, n) {\n if (n >= cm.display.viewTo) { return null }\n n -= cm.display.viewFrom;\n if (n < 0) { return null }\n var view = cm.display.view;\n for (var i = 0; i < view.length; i++) {\n n -= view[i].size;\n if (n < 0) { return i }\n }\n }\n\n function updateSelection(cm) {\n cm.display.input.showSelection(cm.display.input.prepareSelection());\n }\n\n function prepareSelection(cm, primary) {\n if ( primary === void 0 ) primary = true;\n\n var doc = cm.doc, result = {};\n var curFragment = result.cursors = document.createDocumentFragment();\n var selFragment = result.selection = document.createDocumentFragment();\n\n for (var i = 0; i < doc.sel.ranges.length; i++) {\n if (!primary && i == doc.sel.primIndex) { continue }\n var range$$1 = doc.sel.ranges[i];\n if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }\n var collapsed = range$$1.empty();\n if (collapsed || cm.options.showCursorWhenSelecting)\n { drawSelectionCursor(cm, range$$1.head, curFragment); }\n if (!collapsed)\n { drawSelectionRange(cm, range$$1, selFragment); }\n }\n return result\n }\n\n // Draws a cursor for the given range\n function drawSelectionCursor(cm, head, output) {\n var pos = cursorCoords(cm, head, \"div\", null, null, !cm.options.singleCursorHeightPerLine);\n\n var cursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor\"));\n cursor.style.left = pos.left + \"px\";\n cursor.style.top = pos.top + \"px\";\n cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + \"px\";\n\n if (pos.other) {\n // Secondary cursor, shown when on a 'jump' in bi-directional text\n var otherCursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor CodeMirror-secondarycursor\"));\n otherCursor.style.display = \"\";\n otherCursor.style.left = pos.other.left + \"px\";\n otherCursor.style.top = pos.other.top + \"px\";\n otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + \"px\";\n }\n }\n\n function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }\n\n // Draws the given range as a highlighted selection\n function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }\n\n // Cursor-blinking\n function restartBlink(cm) {\n if (!cm.state.focused) { return }\n var display = cm.display;\n clearInterval(display.blinker);\n var on = true;\n display.cursorDiv.style.visibility = \"\";\n if (cm.options.cursorBlinkRate > 0)\n { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? \"\" : \"hidden\"; },\n cm.options.cursorBlinkRate); }\n else if (cm.options.cursorBlinkRate < 0)\n { display.cursorDiv.style.visibility = \"hidden\"; }\n }\n\n function ensureFocus(cm) {\n if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }\n }\n\n function delayBlurEvent(cm) {\n cm.state.delayingBlurEvent = true;\n setTimeout(function () { if (cm.state.delayingBlurEvent) {\n cm.state.delayingBlurEvent = false;\n onBlur(cm);\n } }, 100);\n }\n\n function onFocus(cm, e) {\n if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }\n\n if (cm.options.readOnly == \"nocursor\") { return }\n if (!cm.state.focused) {\n signal(cm, \"focus\", cm, e);\n cm.state.focused = true;\n addClass(cm.display.wrapper, \"CodeMirror-focused\");\n // This test prevents this from firing when a context\n // menu is closed (since the input reset would kill the\n // select-all detection hack)\n if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {\n cm.display.input.reset();\n if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730\n }\n cm.display.input.receivedFocus();\n }\n restartBlink(cm);\n }\n function onBlur(cm, e) {\n if (cm.state.delayingBlurEvent) { return }\n\n if (cm.state.focused) {\n signal(cm, \"blur\", cm, e);\n cm.state.focused = false;\n rmClass(cm.display.wrapper, \"CodeMirror-focused\");\n }\n clearInterval(cm.display.blinker);\n setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);\n }\n\n // Read the actual heights of the rendered lines, and update their\n // stored heights to match.\n function updateHeightsInViewport(cm) {\n var display = cm.display;\n var prevBottom = display.lineDiv.offsetTop;\n for (var i = 0; i < display.view.length; i++) {\n var cur = display.view[i], wrapping = cm.options.lineWrapping;\n var height = (void 0), width = 0;\n if (cur.hidden) { continue }\n if (ie && ie_version < 8) {\n var bot = cur.node.offsetTop + cur.node.offsetHeight;\n height = bot - prevBottom;\n prevBottom = bot;\n } else {\n var box = cur.node.getBoundingClientRect();\n height = box.bottom - box.top;\n // Check that lines don't extend past the right of the current\n // editor width\n if (!wrapping && cur.text.firstChild)\n { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }\n }\n var diff = cur.line.height - height;\n if (height < 2) { height = textHeight(display); }\n if (diff > .005 || diff < -.005) {\n updateLineHeight(cur.line, height);\n updateWidgetHeight(cur.line);\n if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)\n { updateWidgetHeight(cur.rest[j]); } }\n }\n if (width > cm.display.sizerWidth) {\n var chWidth = Math.ceil(width / charWidth(cm.display));\n if (chWidth > cm.display.maxLineLength) {\n cm.display.maxLineLength = chWidth;\n cm.display.maxLine = cur.line;\n cm.display.maxLineChanged = true;\n }\n }\n }\n }\n\n // Read and store the height of line widgets associated with the\n // given line.\n function updateWidgetHeight(line) {\n if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {\n var w = line.widgets[i], parent = w.node.parentNode;\n if (parent) { w.height = parent.offsetHeight; }\n } }\n }\n\n // Compute the lines that are visible in a given viewport (defaults\n // the the current scroll position). viewport may contain top,\n // height, and ensure (see op.scrollToPos) properties.\n function visibleLines(display, doc, viewport) {\n var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;\n top = Math.floor(top - paddingTop(display));\n var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;\n\n var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);\n // Ensure is a {from: {line, ch}, to: {line, ch}} object, and\n // forces those lines into the viewport (if possible).\n if (viewport && viewport.ensure) {\n var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;\n if (ensureFrom < from) {\n from = ensureFrom;\n to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);\n } else if (Math.min(ensureTo, doc.lastLine()) >= to) {\n from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);\n to = ensureTo;\n }\n }\n return {from: from, to: Math.max(to, from + 1)}\n }\n\n // Re-align line numbers and gutter marks to compensate for\n // horizontal scrolling.\n function alignHorizontally(cm) {\n var display = cm.display, view = display.view;\n if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }\n var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;\n var gutterW = display.gutters.offsetWidth, left = comp + \"px\";\n for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {\n if (cm.options.fixedGutter) {\n if (view[i].gutter)\n { view[i].gutter.style.left = left; }\n if (view[i].gutterBackground)\n { view[i].gutterBackground.style.left = left; }\n }\n var align = view[i].alignable;\n if (align) { for (var j = 0; j < align.length; j++)\n { align[j].style.left = left; } }\n } }\n if (cm.options.fixedGutter)\n { display.gutters.style.left = (comp + gutterW) + \"px\"; }\n }\n\n // Used to ensure that the line number gutter is still the right\n // size for the current document size. Returns true when an update\n // is needed.\n function maybeUpdateLineNumberWidth(cm) {\n if (!cm.options.lineNumbers) { return false }\n var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;\n if (last.length != display.lineNumChars) {\n var test = display.measure.appendChild(elt(\"div\", [elt(\"div\", last)],\n \"CodeMirror-linenumber CodeMirror-gutter-elt\"));\n var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;\n display.lineGutter.style.width = \"\";\n display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;\n display.lineNumWidth = display.lineNumInnerWidth + padding;\n display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;\n display.lineGutter.style.width = display.lineNumWidth + \"px\";\n updateGutterSpace(cm);\n return true\n }\n return false\n }\n\n // SCROLLING THINGS INTO VIEW\n\n // If an editor sits on the top or bottom of the window, partially\n // scrolled out of view, this ensures that the cursor is visible.\n function maybeScrollWindow(cm, rect) {\n if (signalDOMEvent(cm, \"scrollCursorIntoView\")) { return }\n\n var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;\n if (rect.top + box.top < 0) { doScroll = true; }\n else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }\n if (doScroll != null && !phantom) {\n var scrollNode = elt(\"div\", \"\\u200b\", null, (\"position: absolute;\\n top: \" + (rect.top - display.viewOffset - paddingTop(cm.display)) + \"px;\\n height: \" + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + \"px;\\n left: \" + (rect.left) + \"px; width: \" + (Math.max(2, rect.right - rect.left)) + \"px;\"));\n cm.display.lineSpace.appendChild(scrollNode);\n scrollNode.scrollIntoView(doScroll);\n cm.display.lineSpace.removeChild(scrollNode);\n }\n }\n\n // Scroll a given position into view (immediately), verifying that\n // it actually became visible (as line heights are accurately\n // measured, the position of something may 'drift' during drawing).\n function scrollPosIntoView(cm, pos, end, margin) {\n if (margin == null) { margin = 0; }\n var rect;\n if (!cm.options.lineWrapping && pos == end) {\n // Set pos and end to the cursor positions around the character pos sticks to\n // If pos.sticky == \"before\", that is around pos.ch - 1, otherwise around pos.ch\n // If pos == Pos(_, 0, \"before\"), pos and end are unchanged\n pos = pos.ch ? Pos(pos.line, pos.sticky == \"before\" ? pos.ch - 1 : pos.ch, \"after\") : pos;\n end = pos.sticky == \"before\" ? Pos(pos.line, pos.ch + 1, \"before\") : pos;\n }\n for (var limit = 0; limit < 5; limit++) {\n var changed = false;\n var coords = cursorCoords(cm, pos);\n var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);\n rect = {left: Math.min(coords.left, endCoords.left),\n top: Math.min(coords.top, endCoords.top) - margin,\n right: Math.max(coords.left, endCoords.left),\n bottom: Math.max(coords.bottom, endCoords.bottom) + margin};\n var scrollPos = calculateScrollPos(cm, rect);\n var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;\n if (scrollPos.scrollTop != null) {\n updateScrollTop(cm, scrollPos.scrollTop);\n if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }\n }\n if (scrollPos.scrollLeft != null) {\n setScrollLeft(cm, scrollPos.scrollLeft);\n if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }\n }\n if (!changed) { break }\n }\n return rect\n }\n\n // Scroll a given set of coordinates into view (immediately).\n function scrollIntoView(cm, rect) {\n var scrollPos = calculateScrollPos(cm, rect);\n if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }\n if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }\n }\n\n // Calculate a new scroll position needed to scroll the given\n // rectangle into view. Returns an object with scrollTop and\n // scrollLeft properties. When these are undefined, the\n // vertical/horizontal position does not need to be adjusted.\n function calculateScrollPos(cm, rect) {\n var display = cm.display, snapMargin = textHeight(cm.display);\n if (rect.top < 0) { rect.top = 0; }\n var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;\n var screen = displayHeight(cm), result = {};\n if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }\n var docBottom = cm.doc.height + paddingVert(display);\n var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;\n if (rect.top < screentop) {\n result.scrollTop = atTop ? 0 : rect.top;\n } else if (rect.bottom > screentop + screen) {\n var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);\n if (newTop != screentop) { result.scrollTop = newTop; }\n }\n\n var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;\n var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);\n var tooWide = rect.right - rect.left > screenw;\n if (tooWide) { rect.right = rect.left + screenw; }\n if (rect.left < 10)\n { result.scrollLeft = 0; }\n else if (rect.left < screenleft)\n { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }\n else if (rect.right > screenw + screenleft - 3)\n { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }\n return result\n }\n\n // Store a relative adjustment to the scroll position in the current\n // operation (to be applied when the operation finishes).\n function addToScrollTop(cm, top) {\n if (top == null) { return }\n resolveScrollToPos(cm);\n cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;\n }\n\n // Make sure that at the end of the operation the current cursor is\n // shown.\n function ensureCursorVisible(cm) {\n resolveScrollToPos(cm);\n var cur = cm.getCursor();\n cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};\n }\n\n function scrollToCoords(cm, x, y) {\n if (x != null || y != null) { resolveScrollToPos(cm); }\n if (x != null) { cm.curOp.scrollLeft = x; }\n if (y != null) { cm.curOp.scrollTop = y; }\n }\n\n function scrollToRange(cm, range$$1) {\n resolveScrollToPos(cm);\n cm.curOp.scrollToPos = range$$1;\n }\n\n // When an operation has its scrollToPos property set, and another\n // scroll action is applied before the end of the operation, this\n // 'simulates' scrolling that position into view in a cheap way, so\n // that the effect of intermediate scroll commands is not ignored.\n function resolveScrollToPos(cm) {\n var range$$1 = cm.curOp.scrollToPos;\n if (range$$1) {\n cm.curOp.scrollToPos = null;\n var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);\n scrollToCoordsRange(cm, from, to, range$$1.margin);\n }\n }\n\n function scrollToCoordsRange(cm, from, to, margin) {\n var sPos = calculateScrollPos(cm, {\n left: Math.min(from.left, to.left),\n top: Math.min(from.top, to.top) - margin,\n right: Math.max(from.right, to.right),\n bottom: Math.max(from.bottom, to.bottom) + margin\n });\n scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);\n }\n\n // Sync the scrollable area and scrollbars, ensure the viewport\n // covers the visible area.\n function updateScrollTop(cm, val) {\n if (Math.abs(cm.doc.scrollTop - val) < 2) { return }\n if (!gecko) { updateDisplaySimple(cm, {top: val}); }\n setScrollTop(cm, val, true);\n if (gecko) { updateDisplaySimple(cm); }\n startWorker(cm, 100);\n }\n\n function setScrollTop(cm, val, forceScroll) {\n val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);\n if (cm.display.scroller.scrollTop == val && !forceScroll) { return }\n cm.doc.scrollTop = val;\n cm.display.scrollbars.setScrollTop(val);\n if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }\n }\n\n // Sync scroller and scrollbar, ensure the gutter elements are\n // aligned.\n function setScrollLeft(cm, val, isScroller, forceScroll) {\n val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);\n if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }\n cm.doc.scrollLeft = val;\n alignHorizontally(cm);\n if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }\n cm.display.scrollbars.setScrollLeft(val);\n }\n\n // SCROLLBARS\n\n // Prepare DOM reads needed to update the scrollbars. Done in one\n // shot to minimize update/measure roundtrips.\n function measureForScrollbars(cm) {\n var d = cm.display, gutterW = d.gutters.offsetWidth;\n var docH = Math.round(cm.doc.height + paddingVert(cm.display));\n return {\n clientHeight: d.scroller.clientHeight,\n viewHeight: d.wrapper.clientHeight,\n scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,\n viewWidth: d.wrapper.clientWidth,\n barLeft: cm.options.fixedGutter ? gutterW : 0,\n docHeight: docH,\n scrollHeight: docH + scrollGap(cm) + d.barHeight,\n nativeBarWidth: d.nativeBarWidth,\n gutterWidth: gutterW\n }\n }\n\n var NativeScrollbars = function(place, scroll, cm) {\n this.cm = cm;\n var vert = this.vert = elt(\"div\", [elt(\"div\", null, null, \"min-width: 1px\")], \"CodeMirror-vscrollbar\");\n var horiz = this.horiz = elt(\"div\", [elt(\"div\", null, null, \"height: 100%; min-height: 1px\")], \"CodeMirror-hscrollbar\");\n vert.tabIndex = horiz.tabIndex = -1;\n place(vert); place(horiz);\n\n on(vert, \"scroll\", function () {\n if (vert.clientHeight) { scroll(vert.scrollTop, \"vertical\"); }\n });\n on(horiz, \"scroll\", function () {\n if (horiz.clientWidth) { scroll(horiz.scrollLeft, \"horizontal\"); }\n });\n\n this.checkedZeroWidth = false;\n // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).\n if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = \"18px\"; }\n };\n\n NativeScrollbars.prototype.update = function (measure) {\n var needsH = measure.scrollWidth > measure.clientWidth + 1;\n var needsV = measure.scrollHeight > measure.clientHeight + 1;\n var sWidth = measure.nativeBarWidth;\n\n if (needsV) {\n this.vert.style.display = \"block\";\n this.vert.style.bottom = needsH ? sWidth + \"px\" : \"0\";\n var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);\n // A bug in IE8 can cause this value to be negative, so guard it.\n this.vert.firstChild.style.height =\n Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + \"px\";\n } else {\n this.vert.style.display = \"\";\n this.vert.firstChild.style.height = \"0\";\n }\n\n if (needsH) {\n this.horiz.style.display = \"block\";\n this.horiz.style.right = needsV ? sWidth + \"px\" : \"0\";\n this.horiz.style.left = measure.barLeft + \"px\";\n var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);\n this.horiz.firstChild.style.width =\n Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + \"px\";\n } else {\n this.horiz.style.display = \"\";\n this.horiz.firstChild.style.width = \"0\";\n }\n\n if (!this.checkedZeroWidth && measure.clientHeight > 0) {\n if (sWidth == 0) { this.zeroWidthHack(); }\n this.checkedZeroWidth = true;\n }\n\n return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}\n };\n\n NativeScrollbars.prototype.setScrollLeft = function (pos) {\n if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }\n if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, \"horiz\"); }\n };\n\n NativeScrollbars.prototype.setScrollTop = function (pos) {\n if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }\n if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, \"vert\"); }\n };\n\n NativeScrollbars.prototype.zeroWidthHack = function () {\n var w = mac && !mac_geMountainLion ? \"12px\" : \"18px\";\n this.horiz.style.height = this.vert.style.width = w;\n this.horiz.style.pointerEvents = this.vert.style.pointerEvents = \"none\";\n this.disableHoriz = new Delayed;\n this.disableVert = new Delayed;\n };\n\n NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {\n bar.style.pointerEvents = \"auto\";\n function maybeDisable() {\n // To find out whether the scrollbar is still visible, we\n // check whether the element under the pixel in the bottom\n // right corner of the scrollbar box is the scrollbar box\n // itself (when the bar is still visible) or its filler child\n // (when the bar is hidden). If it is still visible, we keep\n // it enabled, if it's hidden, we disable pointer events.\n var box = bar.getBoundingClientRect();\n var elt$$1 = type == \"vert\" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)\n : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);\n if (elt$$1 != bar) { bar.style.pointerEvents = \"none\"; }\n else { delay.set(1000, maybeDisable); }\n }\n delay.set(1000, maybeDisable);\n };\n\n NativeScrollbars.prototype.clear = function () {\n var parent = this.horiz.parentNode;\n parent.removeChild(this.horiz);\n parent.removeChild(this.vert);\n };\n\n var NullScrollbars = function () {};\n\n NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };\n NullScrollbars.prototype.setScrollLeft = function () {};\n NullScrollbars.prototype.setScrollTop = function () {};\n NullScrollbars.prototype.clear = function () {};\n\n function updateScrollbars(cm, measure) {\n if (!measure) { measure = measureForScrollbars(cm); }\n var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;\n updateScrollbarsInner(cm, measure);\n for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {\n if (startWidth != cm.display.barWidth && cm.options.lineWrapping)\n { updateHeightsInViewport(cm); }\n updateScrollbarsInner(cm, measureForScrollbars(cm));\n startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;\n }\n }\n\n // Re-synchronize the fake scrollbars with the actual size of the\n // content.\n function updateScrollbarsInner(cm, measure) {\n var d = cm.display;\n var sizes = d.scrollbars.update(measure);\n\n d.sizer.style.paddingRight = (d.barWidth = sizes.right) + \"px\";\n d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + \"px\";\n d.heightForcer.style.borderBottom = sizes.bottom + \"px solid transparent\";\n\n if (sizes.right && sizes.bottom) {\n d.scrollbarFiller.style.display = \"block\";\n d.scrollbarFiller.style.height = sizes.bottom + \"px\";\n d.scrollbarFiller.style.width = sizes.right + \"px\";\n } else { d.scrollbarFiller.style.display = \"\"; }\n if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {\n d.gutterFiller.style.display = \"block\";\n d.gutterFiller.style.height = sizes.bottom + \"px\";\n d.gutterFiller.style.width = measure.gutterWidth + \"px\";\n } else { d.gutterFiller.style.display = \"\"; }\n }\n\n var scrollbarModel = {\"native\": NativeScrollbars, \"null\": NullScrollbars};\n\n function initScrollbars(cm) {\n if (cm.display.scrollbars) {\n cm.display.scrollbars.clear();\n if (cm.display.scrollbars.addClass)\n { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }\n }\n\n cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {\n cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);\n // Prevent clicks in the scrollbars from killing focus\n on(node, \"mousedown\", function () {\n if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }\n });\n node.setAttribute(\"cm-not-content\", \"true\");\n }, function (pos, axis) {\n if (axis == \"horizontal\") { setScrollLeft(cm, pos); }\n else { updateScrollTop(cm, pos); }\n }, cm);\n if (cm.display.scrollbars.addClass)\n { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }\n }\n\n // Operations are used to wrap a series of changes to the editor\n // state in such a way that each change won't have to update the\n // cursor and display (which would be awkward, slow, and\n // error-prone). Instead, display updates are batched and then all\n // combined and executed at once.\n\n var nextOpId = 0;\n // Start a new operation.\n function startOperation(cm) {\n cm.curOp = {\n cm: cm,\n viewChanged: false, // Flag that indicates that lines might need to be redrawn\n startHeight: cm.doc.height, // Used to detect need to update scrollbar\n forceUpdate: false, // Used to force a redraw\n updateInput: null, // Whether to reset the input textarea\n typing: false, // Whether this reset should be careful to leave existing text (for compositing)\n changeObjs: null, // Accumulated changes, for firing change events\n cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on\n cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already\n selectionChanged: false, // Whether the selection needs to be redrawn\n updateMaxLine: false, // Set when the widest line needs to be determined anew\n scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet\n scrollToPos: null, // Used to scroll to a specific position\n focus: false,\n id: ++nextOpId // Unique ID\n };\n pushOperation(cm.curOp);\n }\n\n // Finish an operation, updating the display and signalling delayed events\n function endOperation(cm) {\n var op = cm.curOp;\n if (op) { finishOperation(op, function (group) {\n for (var i = 0; i < group.ops.length; i++)\n { group.ops[i].cm.curOp = null; }\n endOperations(group);\n }); }\n }\n\n // The DOM updates done when an operation finishes are batched so\n // that the minimum number of relayouts are required.\n function endOperations(group) {\n var ops = group.ops;\n for (var i = 0; i < ops.length; i++) // Read DOM\n { endOperation_R1(ops[i]); }\n for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)\n { endOperation_W1(ops[i$1]); }\n for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM\n { endOperation_R2(ops[i$2]); }\n for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)\n { endOperation_W2(ops[i$3]); }\n for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM\n { endOperation_finish(ops[i$4]); }\n }\n\n function endOperation_R1(op) {\n var cm = op.cm, display = cm.display;\n maybeClipScrollbars(cm);\n if (op.updateMaxLine) { findMaxLine(cm); }\n\n op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||\n op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||\n op.scrollToPos.to.line >= display.viewTo) ||\n display.maxLineChanged && cm.options.lineWrapping;\n op.update = op.mustUpdate &&\n new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);\n }\n\n function endOperation_W1(op) {\n op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);\n }\n\n function endOperation_R2(op) {\n var cm = op.cm, display = cm.display;\n if (op.updatedDisplay) { updateHeightsInViewport(cm); }\n\n op.barMeasure = measureForScrollbars(cm);\n\n // If the max line changed since it was last measured, measure it,\n // and ensure the document's width matches it.\n // updateDisplay_W2 will use these properties to do the actual resizing\n if (display.maxLineChanged && !cm.options.lineWrapping) {\n op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;\n cm.display.sizerWidth = op.adjustWidthTo;\n op.barMeasure.scrollWidth =\n Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);\n op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));\n }\n\n if (op.updatedDisplay || op.selectionChanged)\n { op.preparedSelection = display.input.prepareSelection(); }\n }\n\n function endOperation_W2(op) {\n var cm = op.cm;\n\n if (op.adjustWidthTo != null) {\n cm.display.sizer.style.minWidth = op.adjustWidthTo + \"px\";\n if (op.maxScrollLeft < cm.doc.scrollLeft)\n { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }\n cm.display.maxLineChanged = false;\n }\n\n var takeFocus = op.focus && op.focus == activeElt();\n if (op.preparedSelection)\n { cm.display.input.showSelection(op.preparedSelection, takeFocus); }\n if (op.updatedDisplay || op.startHeight != cm.doc.height)\n { updateScrollbars(cm, op.barMeasure); }\n if (op.updatedDisplay)\n { setDocumentHeight(cm, op.barMeasure); }\n\n if (op.selectionChanged) { restartBlink(cm); }\n\n if (cm.state.focused && op.updateInput)\n { cm.display.input.reset(op.typing); }\n if (takeFocus) { ensureFocus(op.cm); }\n }\n\n function endOperation_finish(op) {\n var cm = op.cm, display = cm.display, doc = cm.doc;\n\n if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }\n\n // Abort mouse wheel delta measurement, when scrolling explicitly\n if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))\n { display.wheelStartX = display.wheelStartY = null; }\n\n // Propagate the scroll position to the actual DOM scroller\n if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }\n\n if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }\n // If we need to scroll a specific position into view, do so.\n if (op.scrollToPos) {\n var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),\n clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);\n maybeScrollWindow(cm, rect);\n }\n\n // Fire events for markers that are hidden/unidden by editing or\n // undoing\n var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;\n if (hidden) { for (var i = 0; i < hidden.length; ++i)\n { if (!hidden[i].lines.length) { signal(hidden[i], \"hide\"); } } }\n if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)\n { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], \"unhide\"); } } }\n\n if (display.wrapper.offsetHeight)\n { doc.scrollTop = cm.display.scroller.scrollTop; }\n\n // Fire change events, and delayed event handlers\n if (op.changeObjs)\n { signal(cm, \"changes\", cm, op.changeObjs); }\n if (op.update)\n { op.update.finish(); }\n }\n\n // Run the given function in an operation\n function runInOp(cm, f) {\n if (cm.curOp) { return f() }\n startOperation(cm);\n try { return f() }\n finally { endOperation(cm); }\n }\n // Wraps a function in an operation. Returns the wrapped function.\n function operation(cm, f) {\n return function() {\n if (cm.curOp) { return f.apply(cm, arguments) }\n startOperation(cm);\n try { return f.apply(cm, arguments) }\n finally { endOperation(cm); }\n }\n }\n // Used to add methods to editor and doc instances, wrapping them in\n // operations.\n function methodOp(f) {\n return function() {\n if (this.curOp) { return f.apply(this, arguments) }\n startOperation(this);\n try { return f.apply(this, arguments) }\n finally { endOperation(this); }\n }\n }\n function docMethodOp(f) {\n return function() {\n var cm = this.cm;\n if (!cm || cm.curOp) { return f.apply(this, arguments) }\n startOperation(cm);\n try { return f.apply(this, arguments) }\n finally { endOperation(cm); }\n }\n }\n\n // Updates the display.view data structure for a given change to the\n // document. From and to are in pre-change coordinates. Lendiff is\n // the amount of lines added or subtracted by the change. This is\n // used for changes that span multiple lines, or change the way\n // lines are divided into visual lines. regLineChange (below)\n // registers single-line changes.\n function regChange(cm, from, to, lendiff) {\n if (from == null) { from = cm.doc.first; }\n if (to == null) { to = cm.doc.first + cm.doc.size; }\n if (!lendiff) { lendiff = 0; }\n\n var display = cm.display;\n if (lendiff && to < display.viewTo &&\n (display.updateLineNumbers == null || display.updateLineNumbers > from))\n { display.updateLineNumbers = from; }\n\n cm.curOp.viewChanged = true;\n\n if (from >= display.viewTo) { // Change after\n if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)\n { resetView(cm); }\n } else if (to <= display.viewFrom) { // Change before\n if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {\n resetView(cm);\n } else {\n display.viewFrom += lendiff;\n display.viewTo += lendiff;\n }\n } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap\n resetView(cm);\n } else if (from <= display.viewFrom) { // Top overlap\n var cut = viewCuttingPoint(cm, to, to + lendiff, 1);\n if (cut) {\n display.view = display.view.slice(cut.index);\n display.viewFrom = cut.lineN;\n display.viewTo += lendiff;\n } else {\n resetView(cm);\n }\n } else if (to >= display.viewTo) { // Bottom overlap\n var cut$1 = viewCuttingPoint(cm, from, from, -1);\n if (cut$1) {\n display.view = display.view.slice(0, cut$1.index);\n display.viewTo = cut$1.lineN;\n } else {\n resetView(cm);\n }\n } else { // Gap in the middle\n var cutTop = viewCuttingPoint(cm, from, from, -1);\n var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);\n if (cutTop && cutBot) {\n display.view = display.view.slice(0, cutTop.index)\n .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))\n .concat(display.view.slice(cutBot.index));\n display.viewTo += lendiff;\n } else {\n resetView(cm);\n }\n }\n\n var ext = display.externalMeasured;\n if (ext) {\n if (to < ext.lineN)\n { ext.lineN += lendiff; }\n else if (from < ext.lineN + ext.size)\n { display.externalMeasured = null; }\n }\n }\n\n // Register a change to a single line. Type must be one of \"text\",\n // \"gutter\", \"class\", \"widget\"\n function regLineChange(cm, line, type) {\n cm.curOp.viewChanged = true;\n var display = cm.display, ext = cm.display.externalMeasured;\n if (ext && line >= ext.lineN && line < ext.lineN + ext.size)\n { display.externalMeasured = null; }\n\n if (line < display.viewFrom || line >= display.viewTo) { return }\n var lineView = display.view[findViewIndex(cm, line)];\n if (lineView.node == null) { return }\n var arr = lineView.changes || (lineView.changes = []);\n if (indexOf(arr, type) == -1) { arr.push(type); }\n }\n\n // Clear the view.\n function resetView(cm) {\n cm.display.viewFrom = cm.display.viewTo = cm.doc.first;\n cm.display.view = [];\n cm.display.viewOffset = 0;\n }\n\n function viewCuttingPoint(cm, oldN, newN, dir) {\n var index = findViewIndex(cm, oldN), diff, view = cm.display.view;\n if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)\n { return {index: index, lineN: newN} }\n var n = cm.display.viewFrom;\n for (var i = 0; i < index; i++)\n { n += view[i].size; }\n if (n != oldN) {\n if (dir > 0) {\n if (index == view.length - 1) { return null }\n diff = (n + view[index].size) - oldN;\n index++;\n } else {\n diff = n - oldN;\n }\n oldN += diff; newN += diff;\n }\n while (visualLineNo(cm.doc, newN) != newN) {\n if (index == (dir < 0 ? 0 : view.length - 1)) { return null }\n newN += dir * view[index - (dir < 0 ? 1 : 0)].size;\n index += dir;\n }\n return {index: index, lineN: newN}\n }\n\n // Force the view to cover a given range, adding empty view element\n // or clipping off existing ones as needed.\n function adjustView(cm, from, to) {\n var display = cm.display, view = display.view;\n if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {\n display.view = buildViewArray(cm, from, to);\n display.viewFrom = from;\n } else {\n if (display.viewFrom > from)\n { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }\n else if (display.viewFrom < from)\n { display.view = display.view.slice(findViewIndex(cm, from)); }\n display.viewFrom = from;\n if (display.viewTo < to)\n { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }\n else if (display.viewTo > to)\n { display.view = display.view.slice(0, findViewIndex(cm, to)); }\n }\n display.viewTo = to;\n }\n\n // Count the number of lines in the view whose DOM representation is\n // out of date (or nonexistent).\n function countDirtyView(cm) {\n var view = cm.display.view, dirty = 0;\n for (var i = 0; i < view.length; i++) {\n var lineView = view[i];\n if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }\n }\n return dirty\n }\n\n // HIGHLIGHT WORKER\n\n function startWorker(cm, time) {\n if (cm.doc.highlightFrontier < cm.display.viewTo)\n { cm.state.highlight.set(time, bind(highlightWorker, cm)); }\n }\n\n function highlightWorker(cm) {\n var doc = cm.doc;\n if (doc.highlightFrontier >= cm.display.viewTo) { return }\n var end = +new Date + cm.options.workTime;\n var context = getContextBefore(cm, doc.highlightFrontier);\n var changedLines = [];\n\n doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {\n if (context.line >= cm.display.viewFrom) { // Visible\n var oldStyles = line.styles;\n var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;\n var highlighted = highlightLine(cm, line, context, true);\n if (resetState) { context.state = resetState; }\n line.styles = highlighted.styles;\n var oldCls = line.styleClasses, newCls = highlighted.classes;\n if (newCls) { line.styleClasses = newCls; }\n else if (oldCls) { line.styleClasses = null; }\n var ischange = !oldStyles || oldStyles.length != line.styles.length ||\n oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);\n for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }\n if (ischange) { changedLines.push(context.line); }\n line.stateAfter = context.save();\n context.nextLine();\n } else {\n if (line.text.length <= cm.options.maxHighlightLength)\n { processLine(cm, line.text, context); }\n line.stateAfter = context.line % 5 == 0 ? context.save() : null;\n context.nextLine();\n }\n if (+new Date > end) {\n startWorker(cm, cm.options.workDelay);\n return true\n }\n });\n doc.highlightFrontier = context.line;\n doc.modeFrontier = Math.max(doc.modeFrontier, context.line);\n if (changedLines.length) { runInOp(cm, function () {\n for (var i = 0; i < changedLines.length; i++)\n { regLineChange(cm, changedLines[i], \"text\"); }\n }); }\n }\n\n // DISPLAY DRAWING\n\n var DisplayUpdate = function(cm, viewport, force) {\n var display = cm.display;\n\n this.viewport = viewport;\n // Store some values that we'll need later (but don't want to force a relayout for)\n this.visible = visibleLines(display, cm.doc, viewport);\n this.editorIsHidden = !display.wrapper.offsetWidth;\n this.wrapperHeight = display.wrapper.clientHeight;\n this.wrapperWidth = display.wrapper.clientWidth;\n this.oldDisplayWidth = displayWidth(cm);\n this.force = force;\n this.dims = getDimensions(cm);\n this.events = [];\n };\n\n DisplayUpdate.prototype.signal = function (emitter, type) {\n if (hasHandler(emitter, type))\n { this.events.push(arguments); }\n };\n DisplayUpdate.prototype.finish = function () {\n var this$1 = this;\n\n for (var i = 0; i < this.events.length; i++)\n { signal.apply(null, this$1.events[i]); }\n };\n\n function maybeClipScrollbars(cm) {\n var display = cm.display;\n if (!display.scrollbarsClipped && display.scroller.offsetWidth) {\n display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;\n display.heightForcer.style.height = scrollGap(cm) + \"px\";\n display.sizer.style.marginBottom = -display.nativeBarWidth + \"px\";\n display.sizer.style.borderRightWidth = scrollGap(cm) + \"px\";\n display.scrollbarsClipped = true;\n }\n }\n\n function selectionSnapshot(cm) {\n if (cm.hasFocus()) { return null }\n var active = activeElt();\n if (!active || !contains(cm.display.lineDiv, active)) { return null }\n var result = {activeElt: active};\n if (window.getSelection) {\n var sel = window.getSelection();\n if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {\n result.anchorNode = sel.anchorNode;\n result.anchorOffset = sel.anchorOffset;\n result.focusNode = sel.focusNode;\n result.focusOffset = sel.focusOffset;\n }\n }\n return result\n }\n\n function restoreSelection(snapshot) {\n if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }\n snapshot.activeElt.focus();\n if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {\n var sel = window.getSelection(), range$$1 = document.createRange();\n range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);\n range$$1.collapse(false);\n sel.removeAllRanges();\n sel.addRange(range$$1);\n sel.extend(snapshot.focusNode, snapshot.focusOffset);\n }\n }\n\n // Does the actual updating of the line display. Bails out\n // (returning false) when there is nothing to be done and forced is\n // false.\n function updateDisplayIfNeeded(cm, update) {\n var display = cm.display, doc = cm.doc;\n\n if (update.editorIsHidden) {\n resetView(cm);\n return false\n }\n\n // Bail out if the visible area is already rendered and nothing changed.\n if (!update.force &&\n update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&\n (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&\n display.renderedView == display.view && countDirtyView(cm) == 0)\n { return false }\n\n if (maybeUpdateLineNumberWidth(cm)) {\n resetView(cm);\n update.dims = getDimensions(cm);\n }\n\n // Compute a suitable new viewport (from & to)\n var end = doc.first + doc.size;\n var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);\n var to = Math.min(end, update.visible.to + cm.options.viewportMargin);\n if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }\n if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }\n if (sawCollapsedSpans) {\n from = visualLineNo(cm.doc, from);\n to = visualLineEndNo(cm.doc, to);\n }\n\n var different = from != display.viewFrom || to != display.viewTo ||\n display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;\n adjustView(cm, from, to);\n\n display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));\n // Position the mover div to align with the current scroll position\n cm.display.mover.style.top = display.viewOffset + \"px\";\n\n var toUpdate = countDirtyView(cm);\n if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&\n (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))\n { return false }\n\n // For big changes, we hide the enclosing element during the\n // update, since that speeds up the operations on most browsers.\n var selSnapshot = selectionSnapshot(cm);\n if (toUpdate > 4) { display.lineDiv.style.display = \"none\"; }\n patchDisplay(cm, display.updateLineNumbers, update.dims);\n if (toUpdate > 4) { display.lineDiv.style.display = \"\"; }\n display.renderedView = display.view;\n // There might have been a widget with a focused element that got\n // hidden or updated, if so re-focus it.\n restoreSelection(selSnapshot);\n\n // Prevent selection and cursors from interfering with the scroll\n // width and height.\n removeChildren(display.cursorDiv);\n removeChildren(display.selectionDiv);\n display.gutters.style.height = display.sizer.style.minHeight = 0;\n\n if (different) {\n display.lastWrapHeight = update.wrapperHeight;\n display.lastWrapWidth = update.wrapperWidth;\n startWorker(cm, 400);\n }\n\n display.updateLineNumbers = null;\n\n return true\n }\n\n function postUpdateDisplay(cm, update) {\n var viewport = update.viewport;\n\n for (var first = true;; first = false) {\n if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {\n // Clip forced viewport to actual scrollable area.\n if (viewport && viewport.top != null)\n { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }\n // Updated line heights might result in the drawn area not\n // actually covering the viewport. Keep looping until it does.\n update.visible = visibleLines(cm.display, cm.doc, viewport);\n if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)\n { break }\n }\n if (!updateDisplayIfNeeded(cm, update)) { break }\n updateHeightsInViewport(cm);\n var barMeasure = measureForScrollbars(cm);\n updateSelection(cm);\n updateScrollbars(cm, barMeasure);\n setDocumentHeight(cm, barMeasure);\n update.force = false;\n }\n\n update.signal(cm, \"update\", cm);\n if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {\n update.signal(cm, \"viewportChange\", cm, cm.display.viewFrom, cm.display.viewTo);\n cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;\n }\n }\n\n function updateDisplaySimple(cm, viewport) {\n var update = new DisplayUpdate(cm, viewport);\n if (updateDisplayIfNeeded(cm, update)) {\n updateHeightsInViewport(cm);\n postUpdateDisplay(cm, update);\n var barMeasure = measureForScrollbars(cm);\n updateSelection(cm);\n updateScrollbars(cm, barMeasure);\n setDocumentHeight(cm, barMeasure);\n update.finish();\n }\n }\n\n // Sync the actual display DOM structure with display.view, removing\n // nodes for lines that are no longer in view, and creating the ones\n // that are not there yet, and updating the ones that are out of\n // date.\n function patchDisplay(cm, updateNumbersFrom, dims) {\n var display = cm.display, lineNumbers = cm.options.lineNumbers;\n var container = display.lineDiv, cur = container.firstChild;\n\n function rm(node) {\n var next = node.nextSibling;\n // Works around a throw-scroll bug in OS X Webkit\n if (webkit && mac && cm.display.currentWheelTarget == node)\n { node.style.display = \"none\"; }\n else\n { node.parentNode.removeChild(node); }\n return next\n }\n\n var view = display.view, lineN = display.viewFrom;\n // Loop over the elements in the view, syncing cur (the DOM nodes\n // in display.lineDiv) with the view as we go.\n for (var i = 0; i < view.length; i++) {\n var lineView = view[i];\n if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet\n var node = buildLineElement(cm, lineView, lineN, dims);\n container.insertBefore(node, cur);\n } else { // Already drawn\n while (cur != lineView.node) { cur = rm(cur); }\n var updateNumber = lineNumbers && updateNumbersFrom != null &&\n updateNumbersFrom <= lineN && lineView.lineNumber;\n if (lineView.changes) {\n if (indexOf(lineView.changes, \"gutter\") > -1) { updateNumber = false; }\n updateLineForChanges(cm, lineView, lineN, dims);\n }\n if (updateNumber) {\n removeChildren(lineView.lineNumber);\n lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));\n }\n cur = lineView.node.nextSibling;\n }\n lineN += lineView.size;\n }\n while (cur) { cur = rm(cur); }\n }\n\n function updateGutterSpace(cm) {\n var width = cm.display.gutters.offsetWidth;\n cm.display.sizer.style.marginLeft = width + \"px\";\n }\n\n function setDocumentHeight(cm, measure) {\n cm.display.sizer.style.minHeight = measure.docHeight + \"px\";\n cm.display.heightForcer.style.top = measure.docHeight + \"px\";\n cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + \"px\";\n }\n\n // Rebuild the gutter elements, ensure the margin to the left of the\n // code matches their width.\n function updateGutters(cm) {\n var gutters = cm.display.gutters, specs = cm.options.gutters;\n removeChildren(gutters);\n var i = 0;\n for (; i < specs.length; ++i) {\n var gutterClass = specs[i];\n var gElt = gutters.appendChild(elt(\"div\", null, \"CodeMirror-gutter \" + gutterClass));\n if (gutterClass == \"CodeMirror-linenumbers\") {\n cm.display.lineGutter = gElt;\n gElt.style.width = (cm.display.lineNumWidth || 1) + \"px\";\n }\n }\n gutters.style.display = i ? \"\" : \"none\";\n updateGutterSpace(cm);\n }\n\n // Make sure the gutters options contains the element\n // \"CodeMirror-linenumbers\" when the lineNumbers option is true.\n function setGuttersForLineNumbers(options) {\n var found = indexOf(options.gutters, \"CodeMirror-linenumbers\");\n if (found == -1 && options.lineNumbers) {\n options.gutters = options.gutters.concat([\"CodeMirror-linenumbers\"]);\n } else if (found > -1 && !options.lineNumbers) {\n options.gutters = options.gutters.slice(0);\n options.gutters.splice(found, 1);\n }\n }\n\n // Since the delta values reported on mouse wheel events are\n // unstandardized between browsers and even browser versions, and\n // generally horribly unpredictable, this code starts by measuring\n // the scroll effect that the first few mouse wheel events have,\n // and, from that, detects the way it can convert deltas to pixel\n // offsets afterwards.\n //\n // The reason we want to know the amount a wheel event will scroll\n // is that it gives us a chance to update the display before the\n // actual scrolling happens, reducing flickering.\n\n var wheelSamples = 0, wheelPixelsPerUnit = null;\n // Fill in a browser-detected starting value on browsers where we\n // know one. These don't have to be accurate -- the result of them\n // being wrong would just be a slight flicker on the first wheel\n // scroll (if it is large enough).\n if (ie) { wheelPixelsPerUnit = -.53; }\n else if (gecko) { wheelPixelsPerUnit = 15; }\n else if (chrome) { wheelPixelsPerUnit = -.7; }\n else if (safari) { wheelPixelsPerUnit = -1/3; }\n\n function wheelEventDelta(e) {\n var dx = e.wheelDeltaX, dy = e.wheelDeltaY;\n if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }\n if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }\n else if (dy == null) { dy = e.wheelDelta; }\n return {x: dx, y: dy}\n }\n function wheelEventPixels(e) {\n var delta = wheelEventDelta(e);\n delta.x *= wheelPixelsPerUnit;\n delta.y *= wheelPixelsPerUnit;\n return delta\n }\n\n function onScrollWheel(cm, e) {\n var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;\n\n var display = cm.display, scroll = display.scroller;\n // Quit if there's nothing to scroll here\n var canScrollX = scroll.scrollWidth > scroll.clientWidth;\n var canScrollY = scroll.scrollHeight > scroll.clientHeight;\n if (!(dx && canScrollX || dy && canScrollY)) { return }\n\n // Webkit browsers on OS X abort momentum scrolls when the target\n // of the scroll event is removed from the scrollable element.\n // This hack (see related code in patchDisplay) makes sure the\n // element is kept around.\n if (dy && mac && webkit) {\n outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {\n for (var i = 0; i < view.length; i++) {\n if (view[i].node == cur) {\n cm.display.currentWheelTarget = cur;\n break outer\n }\n }\n }\n }\n\n // On some browsers, horizontal scrolling will cause redraws to\n // happen before the gutter has been realigned, causing it to\n // wriggle around in a most unseemly way. When we have an\n // estimated pixels/delta value, we just handle horizontal\n // scrolling entirely here. It'll be slightly off from native, but\n // better than glitching out.\n if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {\n if (dy && canScrollY)\n { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }\n setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));\n // Only prevent default scrolling if vertical scrolling is\n // actually possible. Otherwise, it causes vertical scroll\n // jitter on OSX trackpads when deltaX is small and deltaY\n // is large (issue #3579)\n if (!dy || (dy && canScrollY))\n { e_preventDefault(e); }\n display.wheelStartX = null; // Abort measurement, if in progress\n return\n }\n\n // 'Project' the visible viewport to cover the area that is being\n // scrolled into view (if we know enough to estimate it).\n if (dy && wheelPixelsPerUnit != null) {\n var pixels = dy * wheelPixelsPerUnit;\n var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;\n if (pixels < 0) { top = Math.max(0, top + pixels - 50); }\n else { bot = Math.min(cm.doc.height, bot + pixels + 50); }\n updateDisplaySimple(cm, {top: top, bottom: bot});\n }\n\n if (wheelSamples < 20) {\n if (display.wheelStartX == null) {\n display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;\n display.wheelDX = dx; display.wheelDY = dy;\n setTimeout(function () {\n if (display.wheelStartX == null) { return }\n var movedX = scroll.scrollLeft - display.wheelStartX;\n var movedY = scroll.scrollTop - display.wheelStartY;\n var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||\n (movedX && display.wheelDX && movedX / display.wheelDX);\n display.wheelStartX = display.wheelStartY = null;\n if (!sample) { return }\n wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);\n ++wheelSamples;\n }, 200);\n } else {\n display.wheelDX += dx; display.wheelDY += dy;\n }\n }\n }\n\n // Selection objects are immutable. A new one is created every time\n // the selection changes. A selection is one or more non-overlapping\n // (and non-touching) ranges, sorted, and an integer that indicates\n // which one is the primary selection (the one that's scrolled into\n // view, that getCursor returns, etc).\n var Selection = function(ranges, primIndex) {\n this.ranges = ranges;\n this.primIndex = primIndex;\n };\n\n Selection.prototype.primary = function () { return this.ranges[this.primIndex] };\n\n Selection.prototype.equals = function (other) {\n var this$1 = this;\n\n if (other == this) { return true }\n if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }\n for (var i = 0; i < this.ranges.length; i++) {\n var here = this$1.ranges[i], there = other.ranges[i];\n if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }\n }\n return true\n };\n\n Selection.prototype.deepCopy = function () {\n var this$1 = this;\n\n var out = [];\n for (var i = 0; i < this.ranges.length; i++)\n { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }\n return new Selection(out, this.primIndex)\n };\n\n Selection.prototype.somethingSelected = function () {\n var this$1 = this;\n\n for (var i = 0; i < this.ranges.length; i++)\n { if (!this$1.ranges[i].empty()) { return true } }\n return false\n };\n\n Selection.prototype.contains = function (pos, end) {\n var this$1 = this;\n\n if (!end) { end = pos; }\n for (var i = 0; i < this.ranges.length; i++) {\n var range = this$1.ranges[i];\n if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)\n { return i }\n }\n return -1\n };\n\n var Range = function(anchor, head) {\n this.anchor = anchor; this.head = head;\n };\n\n Range.prototype.from = function () { return minPos(this.anchor, this.head) };\n Range.prototype.to = function () { return maxPos(this.anchor, this.head) };\n Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };\n\n // Take an unsorted, potentially overlapping set of ranges, and\n // build a selection out of it. 'Consumes' ranges array (modifying\n // it).\n function normalizeSelection(cm, ranges, primIndex) {\n var mayTouch = cm && cm.options.selectionsMayTouch;\n var prim = ranges[primIndex];\n ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });\n primIndex = indexOf(ranges, prim);\n for (var i = 1; i < ranges.length; i++) {\n var cur = ranges[i], prev = ranges[i - 1];\n var diff = cmp(prev.to(), cur.from());\n if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {\n var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());\n var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;\n if (i <= primIndex) { --primIndex; }\n ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));\n }\n }\n return new Selection(ranges, primIndex)\n }\n\n function simpleSelection(anchor, head) {\n return new Selection([new Range(anchor, head || anchor)], 0)\n }\n\n // Compute the position of the end of a change (its 'to' property\n // refers to the pre-change end).\n function changeEnd(change) {\n if (!change.text) { return change.to }\n return Pos(change.from.line + change.text.length - 1,\n lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))\n }\n\n // Adjust a position to refer to the post-change position of the\n // same text, or the end of the change if the change covers it.\n function adjustForChange(pos, change) {\n if (cmp(pos, change.from) < 0) { return pos }\n if (cmp(pos, change.to) <= 0) { return changeEnd(change) }\n\n var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;\n if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }\n return Pos(line, ch)\n }\n\n function computeSelAfterChange(doc, change) {\n var out = [];\n for (var i = 0; i < doc.sel.ranges.length; i++) {\n var range = doc.sel.ranges[i];\n out.push(new Range(adjustForChange(range.anchor, change),\n adjustForChange(range.head, change)));\n }\n return normalizeSelection(doc.cm, out, doc.sel.primIndex)\n }\n\n function offsetPos(pos, old, nw) {\n if (pos.line == old.line)\n { return Pos(nw.line, pos.ch - old.ch + nw.ch) }\n else\n { return Pos(nw.line + (pos.line - old.line), pos.ch) }\n }\n\n // Used by replaceSelections to allow moving the selection to the\n // start or around the replaced test. Hint may be \"start\" or \"around\".\n function computeReplacedSel(doc, changes, hint) {\n var out = [];\n var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;\n for (var i = 0; i < changes.length; i++) {\n var change = changes[i];\n var from = offsetPos(change.from, oldPrev, newPrev);\n var to = offsetPos(changeEnd(change), oldPrev, newPrev);\n oldPrev = change.to;\n newPrev = to;\n if (hint == \"around\") {\n var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;\n out[i] = new Range(inv ? to : from, inv ? from : to);\n } else {\n out[i] = new Range(from, from);\n }\n }\n return new Selection(out, doc.sel.primIndex)\n }\n\n // Used to get the editor into a consistent state again when options change.\n\n function loadMode(cm) {\n cm.doc.mode = getMode(cm.options, cm.doc.modeOption);\n resetModeState(cm);\n }\n\n function resetModeState(cm) {\n cm.doc.iter(function (line) {\n if (line.stateAfter) { line.stateAfter = null; }\n if (line.styles) { line.styles = null; }\n });\n cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;\n startWorker(cm, 100);\n cm.state.modeGen++;\n if (cm.curOp) { regChange(cm); }\n }\n\n // DOCUMENT DATA STRUCTURE\n\n // By default, updates that start and end at the beginning of a line\n // are treated specially, in order to make the association of line\n // widgets and marker elements with the text behave more intuitive.\n function isWholeLineUpdate(doc, change) {\n return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == \"\" &&\n (!doc.cm || doc.cm.options.wholeLineUpdateBefore)\n }\n\n // Perform a change on the document data structure.\n function updateDoc(doc, change, markedSpans, estimateHeight$$1) {\n function spansFor(n) {return markedSpans ? markedSpans[n] : null}\n function update(line, text, spans) {\n updateLine(line, text, spans, estimateHeight$$1);\n signalLater(line, \"change\", line, change);\n }\n function linesFor(start, end) {\n var result = [];\n for (var i = start; i < end; ++i)\n { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }\n return result\n }\n\n var from = change.from, to = change.to, text = change.text;\n var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);\n var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;\n\n // Adjust the line structure\n if (change.full) {\n doc.insert(0, linesFor(0, text.length));\n doc.remove(text.length, doc.size - text.length);\n } else if (isWholeLineUpdate(doc, change)) {\n // This is a whole-line replace. Treated specially to make\n // sure line objects move the way they are supposed to.\n var added = linesFor(0, text.length - 1);\n update(lastLine, lastLine.text, lastSpans);\n if (nlines) { doc.remove(from.line, nlines); }\n if (added.length) { doc.insert(from.line, added); }\n } else if (firstLine == lastLine) {\n if (text.length == 1) {\n update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);\n } else {\n var added$1 = linesFor(1, text.length - 1);\n added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));\n update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n doc.insert(from.line + 1, added$1);\n }\n } else if (text.length == 1) {\n update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));\n doc.remove(from.line + 1, nlines);\n } else {\n update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);\n var added$2 = linesFor(1, text.length - 1);\n if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }\n doc.insert(from.line + 1, added$2);\n }\n\n signalLater(doc, \"change\", doc, change);\n }\n\n // Call f for all linked documents.\n function linkedDocs(doc, f, sharedHistOnly) {\n function propagate(doc, skip, sharedHist) {\n if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {\n var rel = doc.linked[i];\n if (rel.doc == skip) { continue }\n var shared = sharedHist && rel.sharedHist;\n if (sharedHistOnly && !shared) { continue }\n f(rel.doc, shared);\n propagate(rel.doc, doc, shared);\n } }\n }\n propagate(doc, null, true);\n }\n\n // Attach a document to an editor.\n function attachDoc(cm, doc) {\n if (doc.cm) { throw new Error(\"This document is already in use.\") }\n cm.doc = doc;\n doc.cm = cm;\n estimateLineHeights(cm);\n loadMode(cm);\n setDirectionClass(cm);\n if (!cm.options.lineWrapping) { findMaxLine(cm); }\n cm.options.mode = doc.modeOption;\n regChange(cm);\n }\n\n function setDirectionClass(cm) {\n (cm.doc.direction == \"rtl\" ? addClass : rmClass)(cm.display.lineDiv, \"CodeMirror-rtl\");\n }\n\n function directionChanged(cm) {\n runInOp(cm, function () {\n setDirectionClass(cm);\n regChange(cm);\n });\n }\n\n function History(startGen) {\n // Arrays of change events and selections. Doing something adds an\n // event to done and clears undo. Undoing moves events from done\n // to undone, redoing moves them in the other direction.\n this.done = []; this.undone = [];\n this.undoDepth = Infinity;\n // Used to track when changes can be merged into a single undo\n // event\n this.lastModTime = this.lastSelTime = 0;\n this.lastOp = this.lastSelOp = null;\n this.lastOrigin = this.lastSelOrigin = null;\n // Used by the isClean() method\n this.generation = this.maxGeneration = startGen || 1;\n }\n\n // Create a history change event from an updateDoc-style change\n // object.\n function historyChangeFromChange(doc, change) {\n var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};\n attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);\n linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);\n return histChange\n }\n\n // Pop all selection events off the end of a history array. Stop at\n // a change event.\n function clearSelectionEvents(array) {\n while (array.length) {\n var last = lst(array);\n if (last.ranges) { array.pop(); }\n else { break }\n }\n }\n\n // Find the top change event in the history. Pop off selection\n // events that are in the way.\n function lastChangeEvent(hist, force) {\n if (force) {\n clearSelectionEvents(hist.done);\n return lst(hist.done)\n } else if (hist.done.length && !lst(hist.done).ranges) {\n return lst(hist.done)\n } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {\n hist.done.pop();\n return lst(hist.done)\n }\n }\n\n // Register a change in the history. Merges changes that are within\n // a single operation, or are close together with an origin that\n // allows merging (starting with \"+\") into a single event.\n function addChangeToHistory(doc, change, selAfter, opId) {\n var hist = doc.history;\n hist.undone.length = 0;\n var time = +new Date, cur;\n var last;\n\n if ((hist.lastOp == opId ||\n hist.lastOrigin == change.origin && change.origin &&\n ((change.origin.charAt(0) == \"+\" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||\n change.origin.charAt(0) == \"*\")) &&\n (cur = lastChangeEvent(hist, hist.lastOp == opId))) {\n // Merge this change into the last event\n last = lst(cur.changes);\n if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {\n // Optimized case for simple insertion -- don't want to add\n // new changesets for every character typed\n last.to = changeEnd(change);\n } else {\n // Add new sub-event\n cur.changes.push(historyChangeFromChange(doc, change));\n }\n } else {\n // Can not be merged, start a new event.\n var before = lst(hist.done);\n if (!before || !before.ranges)\n { pushSelectionToHistory(doc.sel, hist.done); }\n cur = {changes: [historyChangeFromChange(doc, change)],\n generation: hist.generation};\n hist.done.push(cur);\n while (hist.done.length > hist.undoDepth) {\n hist.done.shift();\n if (!hist.done[0].ranges) { hist.done.shift(); }\n }\n }\n hist.done.push(selAfter);\n hist.generation = ++hist.maxGeneration;\n hist.lastModTime = hist.lastSelTime = time;\n hist.lastOp = hist.lastSelOp = opId;\n hist.lastOrigin = hist.lastSelOrigin = change.origin;\n\n if (!last) { signal(doc, \"historyAdded\"); }\n }\n\n function selectionEventCanBeMerged(doc, origin, prev, sel) {\n var ch = origin.charAt(0);\n return ch == \"*\" ||\n ch == \"+\" &&\n prev.ranges.length == sel.ranges.length &&\n prev.somethingSelected() == sel.somethingSelected() &&\n new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)\n }\n\n // Called whenever the selection changes, sets the new selection as\n // the pending selection in the history, and pushes the old pending\n // selection into the 'done' array when it was significantly\n // different (in number of selected ranges, emptiness, or time).\n function addSelectionToHistory(doc, sel, opId, options) {\n var hist = doc.history, origin = options && options.origin;\n\n // A new event is started when the previous origin does not match\n // the current, or the origins don't allow matching. Origins\n // starting with * are always merged, those starting with + are\n // merged when similar and close together in time.\n if (opId == hist.lastSelOp ||\n (origin && hist.lastSelOrigin == origin &&\n (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||\n selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))\n { hist.done[hist.done.length - 1] = sel; }\n else\n { pushSelectionToHistory(sel, hist.done); }\n\n hist.lastSelTime = +new Date;\n hist.lastSelOrigin = origin;\n hist.lastSelOp = opId;\n if (options && options.clearRedo !== false)\n { clearSelectionEvents(hist.undone); }\n }\n\n function pushSelectionToHistory(sel, dest) {\n var top = lst(dest);\n if (!(top && top.ranges && top.equals(sel)))\n { dest.push(sel); }\n }\n\n // Used to store marked span information in the history.\n function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n }\n\n // When un/re-doing restores text containing marked spans, those\n // that have been explicitly cleared should not be restored.\n function removeClearedSpans(spans) {\n if (!spans) { return null }\n var out;\n for (var i = 0; i < spans.length; ++i) {\n if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }\n else if (out) { out.push(spans[i]); }\n }\n return !out ? spans : out.length ? out : null\n }\n\n // Retrieve and filter the old marked spans stored in a change event.\n function getOldSpans(doc, change) {\n var found = change[\"spans_\" + doc.id];\n if (!found) { return null }\n var nw = [];\n for (var i = 0; i < change.text.length; ++i)\n { nw.push(removeClearedSpans(found[i])); }\n return nw\n }\n\n // Used for un/re-doing changes from the history. Combines the\n // result of computing the existing spans with the set of spans that\n // existed in the history (so that deleting around a span and then\n // undoing brings back the span).\n function mergeOldSpans(doc, change) {\n var old = getOldSpans(doc, change);\n var stretched = stretchSpansOverChange(doc, change);\n if (!old) { return stretched }\n if (!stretched) { return old }\n\n for (var i = 0; i < old.length; ++i) {\n var oldCur = old[i], stretchCur = stretched[i];\n if (oldCur && stretchCur) {\n spans: for (var j = 0; j < stretchCur.length; ++j) {\n var span = stretchCur[j];\n for (var k = 0; k < oldCur.length; ++k)\n { if (oldCur[k].marker == span.marker) { continue spans } }\n oldCur.push(span);\n }\n } else if (stretchCur) {\n old[i] = stretchCur;\n }\n }\n return old\n }\n\n // Used both to provide a JSON-safe object in .getHistory, and, when\n // detaching a document, to split the history in two\n function copyHistoryArray(events, newGroup, instantiateSel) {\n var copy = [];\n for (var i = 0; i < events.length; ++i) {\n var event = events[i];\n if (event.ranges) {\n copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);\n continue\n }\n var changes = event.changes, newChanges = [];\n copy.push({changes: newChanges});\n for (var j = 0; j < changes.length; ++j) {\n var change = changes[j], m = (void 0);\n newChanges.push({from: change.from, to: change.to, text: change.text});\n if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\\d+)$/)) {\n if (indexOf(newGroup, Number(m[1])) > -1) {\n lst(newChanges)[prop] = change[prop];\n delete change[prop];\n }\n } } }\n }\n }\n return copy\n }\n\n // The 'scroll' parameter given to many of these indicated whether\n // the new cursor position should be scrolled into view after\n // modifying the selection.\n\n // If shift is held or the extend flag is set, extends a range to\n // include a given position (and optionally a second position).\n // Otherwise, simply returns the range between the given positions.\n // Used for cursor motion and such.\n function extendRange(range, head, other, extend) {\n if (extend) {\n var anchor = range.anchor;\n if (other) {\n var posBefore = cmp(head, anchor) < 0;\n if (posBefore != (cmp(other, anchor) < 0)) {\n anchor = head;\n head = other;\n } else if (posBefore != (cmp(head, other) < 0)) {\n head = other;\n }\n }\n return new Range(anchor, head)\n } else {\n return new Range(other || head, head)\n }\n }\n\n // Extend the primary selection range, discard the rest.\n function extendSelection(doc, head, other, options, extend) {\n if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }\n setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);\n }\n\n // Extend all selections (pos is an array of selections with length\n // equal the number of selections)\n function extendSelections(doc, heads, options) {\n var out = [];\n var extend = doc.cm && (doc.cm.display.shift || doc.extend);\n for (var i = 0; i < doc.sel.ranges.length; i++)\n { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }\n var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);\n setSelection(doc, newSel, options);\n }\n\n // Updates a single range in the selection.\n function replaceOneSelection(doc, i, range, options) {\n var ranges = doc.sel.ranges.slice(0);\n ranges[i] = range;\n setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);\n }\n\n // Reset the selection to a single range.\n function setSimpleSelection(doc, anchor, head, options) {\n setSelection(doc, simpleSelection(anchor, head), options);\n }\n\n // Give beforeSelectionChange handlers a change to influence a\n // selection update.\n function filterSelectionChange(doc, sel, options) {\n var obj = {\n ranges: sel.ranges,\n update: function(ranges) {\n var this$1 = this;\n\n this.ranges = [];\n for (var i = 0; i < ranges.length; i++)\n { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),\n clipPos(doc, ranges[i].head)); }\n },\n origin: options && options.origin\n };\n signal(doc, \"beforeSelectionChange\", doc, obj);\n if (doc.cm) { signal(doc.cm, \"beforeSelectionChange\", doc.cm, obj); }\n if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }\n else { return sel }\n }\n\n function setSelectionReplaceHistory(doc, sel, options) {\n var done = doc.history.done, last = lst(done);\n if (last && last.ranges) {\n done[done.length - 1] = sel;\n setSelectionNoUndo(doc, sel, options);\n } else {\n setSelection(doc, sel, options);\n }\n }\n\n // Set a new selection.\n function setSelection(doc, sel, options) {\n setSelectionNoUndo(doc, sel, options);\n addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);\n }\n\n function setSelectionNoUndo(doc, sel, options) {\n if (hasHandler(doc, \"beforeSelectionChange\") || doc.cm && hasHandler(doc.cm, \"beforeSelectionChange\"))\n { sel = filterSelectionChange(doc, sel, options); }\n\n var bias = options && options.bias ||\n (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);\n setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));\n\n if (!(options && options.scroll === false) && doc.cm)\n { ensureCursorVisible(doc.cm); }\n }\n\n function setSelectionInner(doc, sel) {\n if (sel.equals(doc.sel)) { return }\n\n doc.sel = sel;\n\n if (doc.cm) {\n doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;\n signalCursorActivity(doc.cm);\n }\n signalLater(doc, \"cursorActivity\", doc);\n }\n\n // Verify that the selection does not partially select any atomic\n // marked ranges.\n function reCheckSelection(doc) {\n setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));\n }\n\n // Return a selection that does not partially select any atomic\n // ranges.\n function skipAtomicInSelection(doc, sel, bias, mayClear) {\n var out;\n for (var i = 0; i < sel.ranges.length; i++) {\n var range = sel.ranges[i];\n var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];\n var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);\n var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);\n if (out || newAnchor != range.anchor || newHead != range.head) {\n if (!out) { out = sel.ranges.slice(0, i); }\n out[i] = new Range(newAnchor, newHead);\n }\n }\n return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel\n }\n\n function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {\n var line = getLine(doc, pos.line);\n if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {\n var sp = line.markedSpans[i], m = sp.marker;\n if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&\n (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {\n if (mayClear) {\n signal(m, \"beforeCursorEnter\");\n if (m.explicitlyCleared) {\n if (!line.markedSpans) { break }\n else {--i; continue}\n }\n }\n if (!m.atomic) { continue }\n\n if (oldPos) {\n var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);\n if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)\n { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }\n if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))\n { return skipAtomicInner(doc, near, pos, dir, mayClear) }\n }\n\n var far = m.find(dir < 0 ? -1 : 1);\n if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)\n { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }\n return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null\n }\n } }\n return pos\n }\n\n // Ensure a given position is not inside an atomic range.\n function skipAtomic(doc, pos, oldPos, bias, mayClear) {\n var dir = bias || 1;\n var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||\n (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||\n skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||\n (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));\n if (!found) {\n doc.cantEdit = true;\n return Pos(doc.first, 0)\n }\n return found\n }\n\n function movePos(doc, pos, dir, line) {\n if (dir < 0 && pos.ch == 0) {\n if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }\n else { return null }\n } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {\n if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }\n else { return null }\n } else {\n return new Pos(pos.line, pos.ch + dir)\n }\n }\n\n function selectAll(cm) {\n cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);\n }\n\n // UPDATING\n\n // Allow \"beforeChange\" event handlers to influence a change\n function filterChange(doc, change, update) {\n var obj = {\n canceled: false,\n from: change.from,\n to: change.to,\n text: change.text,\n origin: change.origin,\n cancel: function () { return obj.canceled = true; }\n };\n if (update) { obj.update = function (from, to, text, origin) {\n if (from) { obj.from = clipPos(doc, from); }\n if (to) { obj.to = clipPos(doc, to); }\n if (text) { obj.text = text; }\n if (origin !== undefined) { obj.origin = origin; }\n }; }\n signal(doc, \"beforeChange\", doc, obj);\n if (doc.cm) { signal(doc.cm, \"beforeChange\", doc.cm, obj); }\n\n if (obj.canceled) { return null }\n return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}\n }\n\n // Apply a change to a document, and add it to the document's\n // history, and propagating it to all linked documents.\n function makeChange(doc, change, ignoreReadOnly) {\n if (doc.cm) {\n if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }\n if (doc.cm.state.suppressEdits) { return }\n }\n\n if (hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\")) {\n change = filterChange(doc, change, true);\n if (!change) { return }\n }\n\n // Possibly split or suppress the update based on the presence\n // of read-only spans in its range.\n var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);\n if (split) {\n for (var i = split.length - 1; i >= 0; --i)\n { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [\"\"] : change.text, origin: change.origin}); }\n } else {\n makeChangeInner(doc, change);\n }\n }\n\n function makeChangeInner(doc, change) {\n if (change.text.length == 1 && change.text[0] == \"\" && cmp(change.from, change.to) == 0) { return }\n var selAfter = computeSelAfterChange(doc, change);\n addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);\n\n makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));\n var rebased = [];\n\n linkedDocs(doc, function (doc, sharedHist) {\n if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n rebaseHist(doc.history, change);\n rebased.push(doc.history);\n }\n makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));\n });\n }\n\n // Revert a change stored in a document's history.\n function makeChangeFromHistory(doc, type, allowSelectionOnly) {\n var suppress = doc.cm && doc.cm.state.suppressEdits;\n if (suppress && !allowSelectionOnly) { return }\n\n var hist = doc.history, event, selAfter = doc.sel;\n var source = type == \"undo\" ? hist.done : hist.undone, dest = type == \"undo\" ? hist.undone : hist.done;\n\n // Verify that there is a useable event (so that ctrl-z won't\n // needlessly clear selection events)\n var i = 0;\n for (; i < source.length; i++) {\n event = source[i];\n if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)\n { break }\n }\n if (i == source.length) { return }\n hist.lastOrigin = hist.lastSelOrigin = null;\n\n for (;;) {\n event = source.pop();\n if (event.ranges) {\n pushSelectionToHistory(event, dest);\n if (allowSelectionOnly && !event.equals(doc.sel)) {\n setSelection(doc, event, {clearRedo: false});\n return\n }\n selAfter = event;\n } else if (suppress) {\n source.push(event);\n return\n } else { break }\n }\n\n // Build up a reverse change object to add to the opposite history\n // stack (redo when undoing, and vice versa).\n var antiChanges = [];\n pushSelectionToHistory(selAfter, dest);\n dest.push({changes: antiChanges, generation: hist.generation});\n hist.generation = event.generation || ++hist.maxGeneration;\n\n var filter = hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\");\n\n var loop = function ( i ) {\n var change = event.changes[i];\n change.origin = type;\n if (filter && !filterChange(doc, change, false)) {\n source.length = 0;\n return {}\n }\n\n antiChanges.push(historyChangeFromChange(doc, change));\n\n var after = i ? computeSelAfterChange(doc, change) : lst(source);\n makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));\n if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }\n var rebased = [];\n\n // Propagate to the linked documents\n linkedDocs(doc, function (doc, sharedHist) {\n if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n rebaseHist(doc.history, change);\n rebased.push(doc.history);\n }\n makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));\n });\n };\n\n for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {\n var returned = loop( i$1 );\n\n if ( returned ) return returned.v;\n }\n }\n\n // Sub-views need their line numbers shifted when text is added\n // above or below them in the parent document.\n function shiftDoc(doc, distance) {\n if (distance == 0) { return }\n doc.first += distance;\n doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(\n Pos(range.anchor.line + distance, range.anchor.ch),\n Pos(range.head.line + distance, range.head.ch)\n ); }), doc.sel.primIndex);\n if (doc.cm) {\n regChange(doc.cm, doc.first, doc.first - distance, distance);\n for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)\n { regLineChange(doc.cm, l, \"gutter\"); }\n }\n }\n\n // More lower-level change function, handling only a single document\n // (not linked ones).\n function makeChangeSingleDoc(doc, change, selAfter, spans) {\n if (doc.cm && !doc.cm.curOp)\n { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }\n\n if (change.to.line < doc.first) {\n shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));\n return\n }\n if (change.from.line > doc.lastLine()) { return }\n\n // Clip the change to the size of this doc\n if (change.from.line < doc.first) {\n var shift = change.text.length - 1 - (doc.first - change.from.line);\n shiftDoc(doc, shift);\n change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),\n text: [lst(change.text)], origin: change.origin};\n }\n var last = doc.lastLine();\n if (change.to.line > last) {\n change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),\n text: [change.text[0]], origin: change.origin};\n }\n\n change.removed = getBetween(doc, change.from, change.to);\n\n if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }\n if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }\n else { updateDoc(doc, change, spans); }\n setSelectionNoUndo(doc, selAfter, sel_dontScroll);\n }\n\n // Handle the interaction of a change to a document with the editor\n // that this document is part of.\n function makeChangeSingleDocInEditor(cm, change, spans) {\n var doc = cm.doc, display = cm.display, from = change.from, to = change.to;\n\n var recomputeMaxLength = false, checkWidthStart = from.line;\n if (!cm.options.lineWrapping) {\n checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));\n doc.iter(checkWidthStart, to.line + 1, function (line) {\n if (line == display.maxLine) {\n recomputeMaxLength = true;\n return true\n }\n });\n }\n\n if (doc.sel.contains(change.from, change.to) > -1)\n { signalCursorActivity(cm); }\n\n updateDoc(doc, change, spans, estimateHeight(cm));\n\n if (!cm.options.lineWrapping) {\n doc.iter(checkWidthStart, from.line + change.text.length, function (line) {\n var len = lineLength(line);\n if (len > display.maxLineLength) {\n display.maxLine = line;\n display.maxLineLength = len;\n display.maxLineChanged = true;\n recomputeMaxLength = false;\n }\n });\n if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }\n }\n\n retreatFrontier(doc, from.line);\n startWorker(cm, 400);\n\n var lendiff = change.text.length - (to.line - from.line) - 1;\n // Remember that these lines changed, for updating the display\n if (change.full)\n { regChange(cm); }\n else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))\n { regLineChange(cm, from.line, \"text\"); }\n else\n { regChange(cm, from.line, to.line + 1, lendiff); }\n\n var changesHandler = hasHandler(cm, \"changes\"), changeHandler = hasHandler(cm, \"change\");\n if (changeHandler || changesHandler) {\n var obj = {\n from: from, to: to,\n text: change.text,\n removed: change.removed,\n origin: change.origin\n };\n if (changeHandler) { signalLater(cm, \"change\", cm, obj); }\n if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }\n }\n cm.display.selForContextMenu = null;\n }\n\n function replaceRange(doc, code, from, to, origin) {\n var assign;\n\n if (!to) { to = from; }\n if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }\n if (typeof code == \"string\") { code = doc.splitLines(code); }\n makeChange(doc, {from: from, to: to, text: code, origin: origin});\n }\n\n // Rebasing/resetting history to deal with externally-sourced changes\n\n function rebaseHistSelSingle(pos, from, to, diff) {\n if (to < pos.line) {\n pos.line += diff;\n } else if (from < pos.line) {\n pos.line = from;\n pos.ch = 0;\n }\n }\n\n // Tries to rebase an array of history events given a change in the\n // document. If the change touches the same lines as the event, the\n // event, and everything 'behind' it, is discarded. If the change is\n // before the event, the event's positions are updated. Uses a\n // copy-on-write scheme for the positions, to avoid having to\n // reallocate them all on every rebase, but also avoid problems with\n // shared position objects being unsafely updated.\n function rebaseHistArray(array, from, to, diff) {\n for (var i = 0; i < array.length; ++i) {\n var sub = array[i], ok = true;\n if (sub.ranges) {\n if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }\n for (var j = 0; j < sub.ranges.length; j++) {\n rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);\n rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);\n }\n continue\n }\n for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {\n var cur = sub.changes[j$1];\n if (to < cur.from.line) {\n cur.from = Pos(cur.from.line + diff, cur.from.ch);\n cur.to = Pos(cur.to.line + diff, cur.to.ch);\n } else if (from <= cur.to.line) {\n ok = false;\n break\n }\n }\n if (!ok) {\n array.splice(0, i + 1);\n i = 0;\n }\n }\n }\n\n function rebaseHist(hist, change) {\n var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;\n rebaseHistArray(hist.done, from, to, diff);\n rebaseHistArray(hist.undone, from, to, diff);\n }\n\n // Utility for applying a change to a line by handle or number,\n // returning the number and optionally registering the line as\n // changed.\n function changeLine(doc, handle, changeType, op) {\n var no = handle, line = handle;\n if (typeof handle == \"number\") { line = getLine(doc, clipLine(doc, handle)); }\n else { no = lineNo(handle); }\n if (no == null) { return null }\n if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }\n return line\n }\n\n // The document is represented as a BTree consisting of leaves, with\n // chunk of lines in them, and branches, with up to ten leaves or\n // other branch nodes below them. The top node is always a branch\n // node, and is the document object itself (meaning it has\n // additional methods and properties).\n //\n // All nodes have parent links. The tree is used both to go from\n // line numbers to line objects, and to go from objects to numbers.\n // It also indexes by height, and is used to convert between height\n // and line object, and to find the total height of the document.\n //\n // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html\n\n function LeafChunk(lines) {\n var this$1 = this;\n\n this.lines = lines;\n this.parent = null;\n var height = 0;\n for (var i = 0; i < lines.length; ++i) {\n lines[i].parent = this$1;\n height += lines[i].height;\n }\n this.height = height;\n }\n\n LeafChunk.prototype = {\n chunkSize: function() { return this.lines.length },\n\n // Remove the n lines at offset 'at'.\n removeInner: function(at, n) {\n var this$1 = this;\n\n for (var i = at, e = at + n; i < e; ++i) {\n var line = this$1.lines[i];\n this$1.height -= line.height;\n cleanUpLine(line);\n signalLater(line, \"delete\");\n }\n this.lines.splice(at, n);\n },\n\n // Helper used to collapse a small branch into a single leaf.\n collapse: function(lines) {\n lines.push.apply(lines, this.lines);\n },\n\n // Insert the given array of lines at offset 'at', count them as\n // having the given height.\n insertInner: function(at, lines, height) {\n var this$1 = this;\n\n this.height += height;\n this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));\n for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }\n },\n\n // Used to iterate over a part of the tree.\n iterN: function(at, n, op) {\n var this$1 = this;\n\n for (var e = at + n; at < e; ++at)\n { if (op(this$1.lines[at])) { return true } }\n }\n };\n\n function BranchChunk(children) {\n var this$1 = this;\n\n this.children = children;\n var size = 0, height = 0;\n for (var i = 0; i < children.length; ++i) {\n var ch = children[i];\n size += ch.chunkSize(); height += ch.height;\n ch.parent = this$1;\n }\n this.size = size;\n this.height = height;\n this.parent = null;\n }\n\n BranchChunk.prototype = {\n chunkSize: function() { return this.size },\n\n removeInner: function(at, n) {\n var this$1 = this;\n\n this.size -= n;\n for (var i = 0; i < this.children.length; ++i) {\n var child = this$1.children[i], sz = child.chunkSize();\n if (at < sz) {\n var rm = Math.min(n, sz - at), oldHeight = child.height;\n child.removeInner(at, rm);\n this$1.height -= oldHeight - child.height;\n if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }\n if ((n -= rm) == 0) { break }\n at = 0;\n } else { at -= sz; }\n }\n // If the result is smaller than 25 lines, ensure that it is a\n // single leaf node.\n if (this.size - n < 25 &&\n (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {\n var lines = [];\n this.collapse(lines);\n this.children = [new LeafChunk(lines)];\n this.children[0].parent = this;\n }\n },\n\n collapse: function(lines) {\n var this$1 = this;\n\n for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }\n },\n\n insertInner: function(at, lines, height) {\n var this$1 = this;\n\n this.size += lines.length;\n this.height += height;\n for (var i = 0; i < this.children.length; ++i) {\n var child = this$1.children[i], sz = child.chunkSize();\n if (at <= sz) {\n child.insertInner(at, lines, height);\n if (child.lines && child.lines.length > 50) {\n // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.\n // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.\n var remaining = child.lines.length % 25 + 25;\n for (var pos = remaining; pos < child.lines.length;) {\n var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));\n child.height -= leaf.height;\n this$1.children.splice(++i, 0, leaf);\n leaf.parent = this$1;\n }\n child.lines = child.lines.slice(0, remaining);\n this$1.maybeSpill();\n }\n break\n }\n at -= sz;\n }\n },\n\n // When a node has grown, check whether it should be split.\n maybeSpill: function() {\n if (this.children.length <= 10) { return }\n var me = this;\n do {\n var spilled = me.children.splice(me.children.length - 5, 5);\n var sibling = new BranchChunk(spilled);\n if (!me.parent) { // Become the parent node\n var copy = new BranchChunk(me.children);\n copy.parent = me;\n me.children = [copy, sibling];\n me = copy;\n } else {\n me.size -= sibling.size;\n me.height -= sibling.height;\n var myIndex = indexOf(me.parent.children, me);\n me.parent.children.splice(myIndex + 1, 0, sibling);\n }\n sibling.parent = me.parent;\n } while (me.children.length > 10)\n me.parent.maybeSpill();\n },\n\n iterN: function(at, n, op) {\n var this$1 = this;\n\n for (var i = 0; i < this.children.length; ++i) {\n var child = this$1.children[i], sz = child.chunkSize();\n if (at < sz) {\n var used = Math.min(n, sz - at);\n if (child.iterN(at, used, op)) { return true }\n if ((n -= used) == 0) { break }\n at = 0;\n } else { at -= sz; }\n }\n }\n };\n\n // Line widgets are block elements displayed above or below a line.\n\n var LineWidget = function(doc, node, options) {\n var this$1 = this;\n\n if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))\n { this$1[opt] = options[opt]; } } }\n this.doc = doc;\n this.node = node;\n };\n\n LineWidget.prototype.clear = function () {\n var this$1 = this;\n\n var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);\n if (no == null || !ws) { return }\n for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }\n if (!ws.length) { line.widgets = null; }\n var height = widgetHeight(this);\n updateLineHeight(line, Math.max(0, line.height - height));\n if (cm) {\n runInOp(cm, function () {\n adjustScrollWhenAboveVisible(cm, line, -height);\n regLineChange(cm, no, \"widget\");\n });\n signalLater(cm, \"lineWidgetCleared\", cm, this, no);\n }\n };\n\n LineWidget.prototype.changed = function () {\n var this$1 = this;\n\n var oldH = this.height, cm = this.doc.cm, line = this.line;\n this.height = null;\n var diff = widgetHeight(this) - oldH;\n if (!diff) { return }\n if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }\n if (cm) {\n runInOp(cm, function () {\n cm.curOp.forceUpdate = true;\n adjustScrollWhenAboveVisible(cm, line, diff);\n signalLater(cm, \"lineWidgetChanged\", cm, this$1, lineNo(line));\n });\n }\n };\n eventMixin(LineWidget);\n\n function adjustScrollWhenAboveVisible(cm, line, diff) {\n if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))\n { addToScrollTop(cm, diff); }\n }\n\n function addLineWidget(doc, handle, node, options) {\n var widget = new LineWidget(doc, node, options);\n var cm = doc.cm;\n if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }\n changeLine(doc, handle, \"widget\", function (line) {\n var widgets = line.widgets || (line.widgets = []);\n if (widget.insertAt == null) { widgets.push(widget); }\n else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }\n widget.line = line;\n if (cm && !lineIsHidden(doc, line)) {\n var aboveVisible = heightAtLine(line) < doc.scrollTop;\n updateLineHeight(line, line.height + widgetHeight(widget));\n if (aboveVisible) { addToScrollTop(cm, widget.height); }\n cm.curOp.forceUpdate = true;\n }\n return true\n });\n if (cm) { signalLater(cm, \"lineWidgetAdded\", cm, widget, typeof handle == \"number\" ? handle : lineNo(handle)); }\n return widget\n }\n\n // TEXTMARKERS\n\n // Created with markText and setBookmark methods. A TextMarker is a\n // handle that can be used to clear or find a marked position in the\n // document. Line objects hold arrays (markedSpans) containing\n // {from, to, marker} object pointing to such marker objects, and\n // indicating that such a marker is present on that line. Multiple\n // lines may point to the same marker when it spans across lines.\n // The spans will have null for their from/to properties when the\n // marker continues beyond the start/end of the line. Markers have\n // links back to the lines they currently touch.\n\n // Collapsed markers have unique ids, in order to be able to order\n // them, which is needed for uniquely determining an outer marker\n // when they overlap (they may nest, but not partially overlap).\n var nextMarkerId = 0;\n\n var TextMarker = function(doc, type) {\n this.lines = [];\n this.type = type;\n this.doc = doc;\n this.id = ++nextMarkerId;\n };\n\n // Clear the marker.\n TextMarker.prototype.clear = function () {\n var this$1 = this;\n\n if (this.explicitlyCleared) { return }\n var cm = this.doc.cm, withOp = cm && !cm.curOp;\n if (withOp) { startOperation(cm); }\n if (hasHandler(this, \"clear\")) {\n var found = this.find();\n if (found) { signalLater(this, \"clear\", found.from, found.to); }\n }\n var min = null, max = null;\n for (var i = 0; i < this.lines.length; ++i) {\n var line = this$1.lines[i];\n var span = getMarkedSpanFor(line.markedSpans, this$1);\n if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), \"text\"); }\n else if (cm) {\n if (span.to != null) { max = lineNo(line); }\n if (span.from != null) { min = lineNo(line); }\n }\n line.markedSpans = removeMarkedSpan(line.markedSpans, span);\n if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)\n { updateLineHeight(line, textHeight(cm.display)); }\n }\n if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {\n var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);\n if (len > cm.display.maxLineLength) {\n cm.display.maxLine = visual;\n cm.display.maxLineLength = len;\n cm.display.maxLineChanged = true;\n }\n } }\n\n if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }\n this.lines.length = 0;\n this.explicitlyCleared = true;\n if (this.atomic && this.doc.cantEdit) {\n this.doc.cantEdit = false;\n if (cm) { reCheckSelection(cm.doc); }\n }\n if (cm) { signalLater(cm, \"markerCleared\", cm, this, min, max); }\n if (withOp) { endOperation(cm); }\n if (this.parent) { this.parent.clear(); }\n };\n\n // Find the position of the marker in the document. Returns a {from,\n // to} object by default. Side can be passed to get a specific side\n // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the\n // Pos objects returned contain a line object, rather than a line\n // number (used to prevent looking up the same line twice).\n TextMarker.prototype.find = function (side, lineObj) {\n var this$1 = this;\n\n if (side == null && this.type == \"bookmark\") { side = 1; }\n var from, to;\n for (var i = 0; i < this.lines.length; ++i) {\n var line = this$1.lines[i];\n var span = getMarkedSpanFor(line.markedSpans, this$1);\n if (span.from != null) {\n from = Pos(lineObj ? line : lineNo(line), span.from);\n if (side == -1) { return from }\n }\n if (span.to != null) {\n to = Pos(lineObj ? line : lineNo(line), span.to);\n if (side == 1) { return to }\n }\n }\n return from && {from: from, to: to}\n };\n\n // Signals that the marker's widget changed, and surrounding layout\n // should be recomputed.\n TextMarker.prototype.changed = function () {\n var this$1 = this;\n\n var pos = this.find(-1, true), widget = this, cm = this.doc.cm;\n if (!pos || !cm) { return }\n runInOp(cm, function () {\n var line = pos.line, lineN = lineNo(pos.line);\n var view = findViewForLine(cm, lineN);\n if (view) {\n clearLineMeasurementCacheFor(view);\n cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;\n }\n cm.curOp.updateMaxLine = true;\n if (!lineIsHidden(widget.doc, line) && widget.height != null) {\n var oldHeight = widget.height;\n widget.height = null;\n var dHeight = widgetHeight(widget) - oldHeight;\n if (dHeight)\n { updateLineHeight(line, line.height + dHeight); }\n }\n signalLater(cm, \"markerChanged\", cm, this$1);\n });\n };\n\n TextMarker.prototype.attachLine = function (line) {\n if (!this.lines.length && this.doc.cm) {\n var op = this.doc.cm.curOp;\n if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)\n { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }\n }\n this.lines.push(line);\n };\n\n TextMarker.prototype.detachLine = function (line) {\n this.lines.splice(indexOf(this.lines, line), 1);\n if (!this.lines.length && this.doc.cm) {\n var op = this.doc.cm.curOp\n ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);\n }\n };\n eventMixin(TextMarker);\n\n // Create a marker, wire it up to the right lines, and\n function markText(doc, from, to, options, type) {\n // Shared markers (across linked documents) are handled separately\n // (markTextShared will call out to this again, once per\n // document).\n if (options && options.shared) { return markTextShared(doc, from, to, options, type) }\n // Ensure we are in an operation.\n if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }\n\n var marker = new TextMarker(doc, type), diff = cmp(from, to);\n if (options) { copyObj(options, marker, false); }\n // Don't connect empty markers unless clearWhenEmpty is false\n if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)\n { return marker }\n if (marker.replacedWith) {\n // Showing up as a widget implies collapsed (widget replaces text)\n marker.collapsed = true;\n marker.widgetNode = eltP(\"span\", [marker.replacedWith], \"CodeMirror-widget\");\n if (!options.handleMouseEvents) { marker.widgetNode.setAttribute(\"cm-ignore-events\", \"true\"); }\n if (options.insertLeft) { marker.widgetNode.insertLeft = true; }\n }\n if (marker.collapsed) {\n if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||\n from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))\n { throw new Error(\"Inserting collapsed marker partially overlapping an existing one\") }\n seeCollapsedSpans();\n }\n\n if (marker.addToHistory)\n { addChangeToHistory(doc, {from: from, to: to, origin: \"markText\"}, doc.sel, NaN); }\n\n var curLine = from.line, cm = doc.cm, updateMaxLine;\n doc.iter(curLine, to.line + 1, function (line) {\n if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)\n { updateMaxLine = true; }\n if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }\n addMarkedSpan(line, new MarkedSpan(marker,\n curLine == from.line ? from.ch : null,\n curLine == to.line ? to.ch : null));\n ++curLine;\n });\n // lineIsHidden depends on the presence of the spans, so needs a second pass\n if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {\n if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }\n }); }\n\n if (marker.clearOnEnter) { on(marker, \"beforeCursorEnter\", function () { return marker.clear(); }); }\n\n if (marker.readOnly) {\n seeReadOnlySpans();\n if (doc.history.done.length || doc.history.undone.length)\n { doc.clearHistory(); }\n }\n if (marker.collapsed) {\n marker.id = ++nextMarkerId;\n marker.atomic = true;\n }\n if (cm) {\n // Sync editor state\n if (updateMaxLine) { cm.curOp.updateMaxLine = true; }\n if (marker.collapsed)\n { regChange(cm, from.line, to.line + 1); }\n else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||\n marker.attributes || marker.title)\n { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, \"text\"); } }\n if (marker.atomic) { reCheckSelection(cm.doc); }\n signalLater(cm, \"markerAdded\", cm, marker);\n }\n return marker\n }\n\n // SHARED TEXTMARKERS\n\n // A shared marker spans multiple linked documents. It is\n // implemented as a meta-marker-object controlling multiple normal\n // markers.\n var SharedTextMarker = function(markers, primary) {\n var this$1 = this;\n\n this.markers = markers;\n this.primary = primary;\n for (var i = 0; i < markers.length; ++i)\n { markers[i].parent = this$1; }\n };\n\n SharedTextMarker.prototype.clear = function () {\n var this$1 = this;\n\n if (this.explicitlyCleared) { return }\n this.explicitlyCleared = true;\n for (var i = 0; i < this.markers.length; ++i)\n { this$1.markers[i].clear(); }\n signalLater(this, \"clear\");\n };\n\n SharedTextMarker.prototype.find = function (side, lineObj) {\n return this.primary.find(side, lineObj)\n };\n eventMixin(SharedTextMarker);\n\n function markTextShared(doc, from, to, options, type) {\n options = copyObj(options);\n options.shared = false;\n var markers = [markText(doc, from, to, options, type)], primary = markers[0];\n var widget = options.widgetNode;\n linkedDocs(doc, function (doc) {\n if (widget) { options.widgetNode = widget.cloneNode(true); }\n markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));\n for (var i = 0; i < doc.linked.length; ++i)\n { if (doc.linked[i].isParent) { return } }\n primary = lst(markers);\n });\n return new SharedTextMarker(markers, primary)\n }\n\n function findSharedMarkers(doc) {\n return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })\n }\n\n function copySharedMarkers(doc, markers) {\n for (var i = 0; i < markers.length; i++) {\n var marker = markers[i], pos = marker.find();\n var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);\n if (cmp(mFrom, mTo)) {\n var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);\n marker.markers.push(subMark);\n subMark.parent = marker;\n }\n }\n }\n\n function detachSharedMarkers(markers) {\n var loop = function ( i ) {\n var marker = markers[i], linked = [marker.primary.doc];\n linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });\n for (var j = 0; j < marker.markers.length; j++) {\n var subMarker = marker.markers[j];\n if (indexOf(linked, subMarker.doc) == -1) {\n subMarker.parent = null;\n marker.markers.splice(j--, 1);\n }\n }\n };\n\n for (var i = 0; i < markers.length; i++) loop( i );\n }\n\n var nextDocId = 0;\n var Doc = function(text, mode, firstLine, lineSep, direction) {\n if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }\n if (firstLine == null) { firstLine = 0; }\n\n BranchChunk.call(this, [new LeafChunk([new Line(\"\", null)])]);\n this.first = firstLine;\n this.scrollTop = this.scrollLeft = 0;\n this.cantEdit = false;\n this.cleanGeneration = 1;\n this.modeFrontier = this.highlightFrontier = firstLine;\n var start = Pos(firstLine, 0);\n this.sel = simpleSelection(start);\n this.history = new History(null);\n this.id = ++nextDocId;\n this.modeOption = mode;\n this.lineSep = lineSep;\n this.direction = (direction == \"rtl\") ? \"rtl\" : \"ltr\";\n this.extend = false;\n\n if (typeof text == \"string\") { text = this.splitLines(text); }\n updateDoc(this, {from: start, to: start, text: text});\n setSelection(this, simpleSelection(start), sel_dontScroll);\n };\n\n Doc.prototype = createObj(BranchChunk.prototype, {\n constructor: Doc,\n // Iterate over the document. Supports two forms -- with only one\n // argument, it calls that for each line in the document. With\n // three, it iterates over the range given by the first two (with\n // the second being non-inclusive).\n iter: function(from, to, op) {\n if (op) { this.iterN(from - this.first, to - from, op); }\n else { this.iterN(this.first, this.first + this.size, from); }\n },\n\n // Non-public interface for adding and removing lines.\n insert: function(at, lines) {\n var height = 0;\n for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }\n this.insertInner(at - this.first, lines, height);\n },\n remove: function(at, n) { this.removeInner(at - this.first, n); },\n\n // From here, the methods are part of the public interface. Most\n // are also available from CodeMirror (editor) instances.\n\n getValue: function(lineSep) {\n var lines = getLines(this, this.first, this.first + this.size);\n if (lineSep === false) { return lines }\n return lines.join(lineSep || this.lineSeparator())\n },\n setValue: docMethodOp(function(code) {\n var top = Pos(this.first, 0), last = this.first + this.size - 1;\n makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),\n text: this.splitLines(code), origin: \"setValue\", full: true}, true);\n if (this.cm) { scrollToCoords(this.cm, 0, 0); }\n setSelection(this, simpleSelection(top), sel_dontScroll);\n }),\n replaceRange: function(code, from, to, origin) {\n from = clipPos(this, from);\n to = to ? clipPos(this, to) : from;\n replaceRange(this, code, from, to, origin);\n },\n getRange: function(from, to, lineSep) {\n var lines = getBetween(this, clipPos(this, from), clipPos(this, to));\n if (lineSep === false) { return lines }\n return lines.join(lineSep || this.lineSeparator())\n },\n\n getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},\n\n getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},\n getLineNumber: function(line) {return lineNo(line)},\n\n getLineHandleVisualStart: function(line) {\n if (typeof line == \"number\") { line = getLine(this, line); }\n return visualLine(line)\n },\n\n lineCount: function() {return this.size},\n firstLine: function() {return this.first},\n lastLine: function() {return this.first + this.size - 1},\n\n clipPos: function(pos) {return clipPos(this, pos)},\n\n getCursor: function(start) {\n var range$$1 = this.sel.primary(), pos;\n if (start == null || start == \"head\") { pos = range$$1.head; }\n else if (start == \"anchor\") { pos = range$$1.anchor; }\n else if (start == \"end\" || start == \"to\" || start === false) { pos = range$$1.to(); }\n else { pos = range$$1.from(); }\n return pos\n },\n listSelections: function() { return this.sel.ranges },\n somethingSelected: function() {return this.sel.somethingSelected()},\n\n setCursor: docMethodOp(function(line, ch, options) {\n setSimpleSelection(this, clipPos(this, typeof line == \"number\" ? Pos(line, ch || 0) : line), null, options);\n }),\n setSelection: docMethodOp(function(anchor, head, options) {\n setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);\n }),\n extendSelection: docMethodOp(function(head, other, options) {\n extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);\n }),\n extendSelections: docMethodOp(function(heads, options) {\n extendSelections(this, clipPosArray(this, heads), options);\n }),\n extendSelectionsBy: docMethodOp(function(f, options) {\n var heads = map(this.sel.ranges, f);\n extendSelections(this, clipPosArray(this, heads), options);\n }),\n setSelections: docMethodOp(function(ranges, primary, options) {\n var this$1 = this;\n\n if (!ranges.length) { return }\n var out = [];\n for (var i = 0; i < ranges.length; i++)\n { out[i] = new Range(clipPos(this$1, ranges[i].anchor),\n clipPos(this$1, ranges[i].head)); }\n if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }\n setSelection(this, normalizeSelection(this.cm, out, primary), options);\n }),\n addSelection: docMethodOp(function(anchor, head, options) {\n var ranges = this.sel.ranges.slice(0);\n ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));\n setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);\n }),\n\n getSelection: function(lineSep) {\n var this$1 = this;\n\n var ranges = this.sel.ranges, lines;\n for (var i = 0; i < ranges.length; i++) {\n var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());\n lines = lines ? lines.concat(sel) : sel;\n }\n if (lineSep === false) { return lines }\n else { return lines.join(lineSep || this.lineSeparator()) }\n },\n getSelections: function(lineSep) {\n var this$1 = this;\n\n var parts = [], ranges = this.sel.ranges;\n for (var i = 0; i < ranges.length; i++) {\n var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());\n if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }\n parts[i] = sel;\n }\n return parts\n },\n replaceSelection: function(code, collapse, origin) {\n var dup = [];\n for (var i = 0; i < this.sel.ranges.length; i++)\n { dup[i] = code; }\n this.replaceSelections(dup, collapse, origin || \"+input\");\n },\n replaceSelections: docMethodOp(function(code, collapse, origin) {\n var this$1 = this;\n\n var changes = [], sel = this.sel;\n for (var i = 0; i < sel.ranges.length; i++) {\n var range$$1 = sel.ranges[i];\n changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};\n }\n var newSel = collapse && collapse != \"end\" && computeReplacedSel(this, changes, collapse);\n for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)\n { makeChange(this$1, changes[i$1]); }\n if (newSel) { setSelectionReplaceHistory(this, newSel); }\n else if (this.cm) { ensureCursorVisible(this.cm); }\n }),\n undo: docMethodOp(function() {makeChangeFromHistory(this, \"undo\");}),\n redo: docMethodOp(function() {makeChangeFromHistory(this, \"redo\");}),\n undoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"undo\", true);}),\n redoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"redo\", true);}),\n\n setExtending: function(val) {this.extend = val;},\n getExtending: function() {return this.extend},\n\n historySize: function() {\n var hist = this.history, done = 0, undone = 0;\n for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }\n for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }\n return {undo: done, redo: undone}\n },\n clearHistory: function() {this.history = new History(this.history.maxGeneration);},\n\n markClean: function() {\n this.cleanGeneration = this.changeGeneration(true);\n },\n changeGeneration: function(forceSplit) {\n if (forceSplit)\n { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }\n return this.history.generation\n },\n isClean: function (gen) {\n return this.history.generation == (gen || this.cleanGeneration)\n },\n\n getHistory: function() {\n return {done: copyHistoryArray(this.history.done),\n undone: copyHistoryArray(this.history.undone)}\n },\n setHistory: function(histData) {\n var hist = this.history = new History(this.history.maxGeneration);\n hist.done = copyHistoryArray(histData.done.slice(0), null, true);\n hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);\n },\n\n setGutterMarker: docMethodOp(function(line, gutterID, value) {\n return changeLine(this, line, \"gutter\", function (line) {\n var markers = line.gutterMarkers || (line.gutterMarkers = {});\n markers[gutterID] = value;\n if (!value && isEmpty(markers)) { line.gutterMarkers = null; }\n return true\n })\n }),\n\n clearGutter: docMethodOp(function(gutterID) {\n var this$1 = this;\n\n this.iter(function (line) {\n if (line.gutterMarkers && line.gutterMarkers[gutterID]) {\n changeLine(this$1, line, \"gutter\", function () {\n line.gutterMarkers[gutterID] = null;\n if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }\n return true\n });\n }\n });\n }),\n\n lineInfo: function(line) {\n var n;\n if (typeof line == \"number\") {\n if (!isLine(this, line)) { return null }\n n = line;\n line = getLine(this, line);\n if (!line) { return null }\n } else {\n n = lineNo(line);\n if (n == null) { return null }\n }\n return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,\n textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,\n widgets: line.widgets}\n },\n\n addLineClass: docMethodOp(function(handle, where, cls) {\n return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", function (line) {\n var prop = where == \"text\" ? \"textClass\"\n : where == \"background\" ? \"bgClass\"\n : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\";\n if (!line[prop]) { line[prop] = cls; }\n else if (classTest(cls).test(line[prop])) { return false }\n else { line[prop] += \" \" + cls; }\n return true\n })\n }),\n removeLineClass: docMethodOp(function(handle, where, cls) {\n return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", function (line) {\n var prop = where == \"text\" ? \"textClass\"\n : where == \"background\" ? \"bgClass\"\n : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\";\n var cur = line[prop];\n if (!cur) { return false }\n else if (cls == null) { line[prop] = null; }\n else {\n var found = cur.match(classTest(cls));\n if (!found) { return false }\n var end = found.index + found[0].length;\n line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? \"\" : \" \") + cur.slice(end) || null;\n }\n return true\n })\n }),\n\n addLineWidget: docMethodOp(function(handle, node, options) {\n return addLineWidget(this, handle, node, options)\n }),\n removeLineWidget: function(widget) { widget.clear(); },\n\n markText: function(from, to, options) {\n return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || \"range\")\n },\n setBookmark: function(pos, options) {\n var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),\n insertLeft: options && options.insertLeft,\n clearWhenEmpty: false, shared: options && options.shared,\n handleMouseEvents: options && options.handleMouseEvents};\n pos = clipPos(this, pos);\n return markText(this, pos, pos, realOpts, \"bookmark\")\n },\n findMarksAt: function(pos) {\n pos = clipPos(this, pos);\n var markers = [], spans = getLine(this, pos.line).markedSpans;\n if (spans) { for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if ((span.from == null || span.from <= pos.ch) &&\n (span.to == null || span.to >= pos.ch))\n { markers.push(span.marker.parent || span.marker); }\n } }\n return markers\n },\n findMarks: function(from, to, filter) {\n from = clipPos(this, from); to = clipPos(this, to);\n var found = [], lineNo$$1 = from.line;\n this.iter(from.line, to.line + 1, function (line) {\n var spans = line.markedSpans;\n if (spans) { for (var i = 0; i < spans.length; i++) {\n var span = spans[i];\n if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||\n span.from == null && lineNo$$1 != from.line ||\n span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&\n (!filter || filter(span.marker)))\n { found.push(span.marker.parent || span.marker); }\n } }\n ++lineNo$$1;\n });\n return found\n },\n getAllMarks: function() {\n var markers = [];\n this.iter(function (line) {\n var sps = line.markedSpans;\n if (sps) { for (var i = 0; i < sps.length; ++i)\n { if (sps[i].from != null) { markers.push(sps[i].marker); } } }\n });\n return markers\n },\n\n posFromIndex: function(off) {\n var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;\n this.iter(function (line) {\n var sz = line.text.length + sepSize;\n if (sz > off) { ch = off; return true }\n off -= sz;\n ++lineNo$$1;\n });\n return clipPos(this, Pos(lineNo$$1, ch))\n },\n indexFromPos: function (coords) {\n coords = clipPos(this, coords);\n var index = coords.ch;\n if (coords.line < this.first || coords.ch < 0) { return 0 }\n var sepSize = this.lineSeparator().length;\n this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value\n index += line.text.length + sepSize;\n });\n return index\n },\n\n copy: function(copyHistory) {\n var doc = new Doc(getLines(this, this.first, this.first + this.size),\n this.modeOption, this.first, this.lineSep, this.direction);\n doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;\n doc.sel = this.sel;\n doc.extend = false;\n if (copyHistory) {\n doc.history.undoDepth = this.history.undoDepth;\n doc.setHistory(this.getHistory());\n }\n return doc\n },\n\n linkedDoc: function(options) {\n if (!options) { options = {}; }\n var from = this.first, to = this.first + this.size;\n if (options.from != null && options.from > from) { from = options.from; }\n if (options.to != null && options.to < to) { to = options.to; }\n var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);\n if (options.sharedHist) { copy.history = this.history\n ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});\n copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];\n copySharedMarkers(copy, findSharedMarkers(this));\n return copy\n },\n unlinkDoc: function(other) {\n var this$1 = this;\n\n if (other instanceof CodeMirror) { other = other.doc; }\n if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {\n var link = this$1.linked[i];\n if (link.doc != other) { continue }\n this$1.linked.splice(i, 1);\n other.unlinkDoc(this$1);\n detachSharedMarkers(findSharedMarkers(this$1));\n break\n } }\n // If the histories were shared, split them again\n if (other.history == this.history) {\n var splitIds = [other.id];\n linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);\n other.history = new History(null);\n other.history.done = copyHistoryArray(this.history.done, splitIds);\n other.history.undone = copyHistoryArray(this.history.undone, splitIds);\n }\n },\n iterLinkedDocs: function(f) {linkedDocs(this, f);},\n\n getMode: function() {return this.mode},\n getEditor: function() {return this.cm},\n\n splitLines: function(str) {\n if (this.lineSep) { return str.split(this.lineSep) }\n return splitLinesAuto(str)\n },\n lineSeparator: function() { return this.lineSep || \"\\n\" },\n\n setDirection: docMethodOp(function (dir) {\n if (dir != \"rtl\") { dir = \"ltr\"; }\n if (dir == this.direction) { return }\n this.direction = dir;\n this.iter(function (line) { return line.order = null; });\n if (this.cm) { directionChanged(this.cm); }\n })\n });\n\n // Public alias.\n Doc.prototype.eachLine = Doc.prototype.iter;\n\n // Kludge to work around strange IE behavior where it'll sometimes\n // re-fire a series of drag-related events right after the drop (#1551)\n var lastDrop = 0;\n\n function onDrop(e) {\n var cm = this;\n clearDragCursor(cm);\n if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))\n { return }\n e_preventDefault(e);\n if (ie) { lastDrop = +new Date; }\n var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;\n if (!pos || cm.isReadOnly()) { return }\n // Might be a file drop, in which case we simply extract the text\n // and insert it.\n if (files && files.length && window.FileReader && window.File) {\n var n = files.length, text = Array(n), read = 0;\n var loadFile = function (file, i) {\n if (cm.options.allowDropFileTypes &&\n indexOf(cm.options.allowDropFileTypes, file.type) == -1)\n { return }\n\n var reader = new FileReader;\n reader.onload = operation(cm, function () {\n var content = reader.result;\n if (/[\\x00-\\x08\\x0e-\\x1f]{2}/.test(content)) { content = \"\"; }\n text[i] = content;\n if (++read == n) {\n pos = clipPos(cm.doc, pos);\n var change = {from: pos, to: pos,\n text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),\n origin: \"paste\"};\n makeChange(cm.doc, change);\n setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));\n }\n });\n reader.readAsText(file);\n };\n for (var i = 0; i < n; ++i) { loadFile(files[i], i); }\n } else { // Normal drop\n // Don't do a replace if the drop happened inside of the selected text.\n if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {\n cm.state.draggingText(e);\n // Ensure the editor is re-focused\n setTimeout(function () { return cm.display.input.focus(); }, 20);\n return\n }\n try {\n var text$1 = e.dataTransfer.getData(\"Text\");\n if (text$1) {\n var selected;\n if (cm.state.draggingText && !cm.state.draggingText.copy)\n { selected = cm.listSelections(); }\n setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));\n if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)\n { replaceRange(cm.doc, \"\", selected[i$1].anchor, selected[i$1].head, \"drag\"); } }\n cm.replaceSelection(text$1, \"around\", \"paste\");\n cm.display.input.focus();\n }\n }\n catch(e){}\n }\n }\n\n function onDragStart(cm, e) {\n if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }\n if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }\n\n e.dataTransfer.setData(\"Text\", cm.getSelection());\n e.dataTransfer.effectAllowed = \"copyMove\";\n\n // Use dummy image instead of default browsers image.\n // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.\n if (e.dataTransfer.setDragImage && !safari) {\n var img = elt(\"img\", null, null, \"position: fixed; left: 0; top: 0;\");\n img.src = \"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\";\n if (presto) {\n img.width = img.height = 1;\n cm.display.wrapper.appendChild(img);\n // Force a relayout, or Opera won't use our image for some obscure reason\n img._top = img.offsetTop;\n }\n e.dataTransfer.setDragImage(img, 0, 0);\n if (presto) { img.parentNode.removeChild(img); }\n }\n }\n\n function onDragOver(cm, e) {\n var pos = posFromMouse(cm, e);\n if (!pos) { return }\n var frag = document.createDocumentFragment();\n drawSelectionCursor(cm, pos, frag);\n if (!cm.display.dragCursor) {\n cm.display.dragCursor = elt(\"div\", null, \"CodeMirror-cursors CodeMirror-dragcursors\");\n cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);\n }\n removeChildrenAndAdd(cm.display.dragCursor, frag);\n }\n\n function clearDragCursor(cm) {\n if (cm.display.dragCursor) {\n cm.display.lineSpace.removeChild(cm.display.dragCursor);\n cm.display.dragCursor = null;\n }\n }\n\n // These must be handled carefully, because naively registering a\n // handler for each editor will cause the editors to never be\n // garbage collected.\n\n function forEachCodeMirror(f) {\n if (!document.getElementsByClassName) { return }\n var byClass = document.getElementsByClassName(\"CodeMirror\"), editors = [];\n for (var i = 0; i < byClass.length; i++) {\n var cm = byClass[i].CodeMirror;\n if (cm) { editors.push(cm); }\n }\n if (editors.length) { editors[0].operation(function () {\n for (var i = 0; i < editors.length; i++) { f(editors[i]); }\n }); }\n }\n\n var globalsRegistered = false;\n function ensureGlobalHandlers() {\n if (globalsRegistered) { return }\n registerGlobalHandlers();\n globalsRegistered = true;\n }\n function registerGlobalHandlers() {\n // When the window resizes, we need to refresh active editors.\n var resizeTimer;\n on(window, \"resize\", function () {\n if (resizeTimer == null) { resizeTimer = setTimeout(function () {\n resizeTimer = null;\n forEachCodeMirror(onResize);\n }, 100); }\n });\n // When the window loses focus, we want to show the editor as blurred\n on(window, \"blur\", function () { return forEachCodeMirror(onBlur); });\n }\n // Called when the window resizes\n function onResize(cm) {\n var d = cm.display;\n // Might be a text scaling operation, clear size caches.\n d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n d.scrollbarsClipped = false;\n cm.setSize();\n }\n\n var keyNames = {\n 3: \"Pause\", 8: \"Backspace\", 9: \"Tab\", 13: \"Enter\", 16: \"Shift\", 17: \"Ctrl\", 18: \"Alt\",\n 19: \"Pause\", 20: \"CapsLock\", 27: \"Esc\", 32: \"Space\", 33: \"PageUp\", 34: \"PageDown\", 35: \"End\",\n 36: \"Home\", 37: \"Left\", 38: \"Up\", 39: \"Right\", 40: \"Down\", 44: \"PrintScrn\", 45: \"Insert\",\n 46: \"Delete\", 59: \";\", 61: \"=\", 91: \"Mod\", 92: \"Mod\", 93: \"Mod\",\n 106: \"*\", 107: \"=\", 109: \"-\", 110: \".\", 111: \"/\", 127: \"Delete\", 145: \"ScrollLock\",\n 173: \"-\", 186: \";\", 187: \"=\", 188: \",\", 189: \"-\", 190: \".\", 191: \"/\", 192: \"`\", 219: \"[\", 220: \"\\\\\",\n 221: \"]\", 222: \"'\", 63232: \"Up\", 63233: \"Down\", 63234: \"Left\", 63235: \"Right\", 63272: \"Delete\",\n 63273: \"Home\", 63275: \"End\", 63276: \"PageUp\", 63277: \"PageDown\", 63302: \"Insert\"\n };\n\n // Number keys\n for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }\n // Alphabetic keys\n for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }\n // Function keys\n for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = \"F\" + i$2; }\n\n var keyMap = {};\n\n keyMap.basic = {\n \"Left\": \"goCharLeft\", \"Right\": \"goCharRight\", \"Up\": \"goLineUp\", \"Down\": \"goLineDown\",\n \"End\": \"goLineEnd\", \"Home\": \"goLineStartSmart\", \"PageUp\": \"goPageUp\", \"PageDown\": \"goPageDown\",\n \"Delete\": \"delCharAfter\", \"Backspace\": \"delCharBefore\", \"Shift-Backspace\": \"delCharBefore\",\n \"Tab\": \"defaultTab\", \"Shift-Tab\": \"indentAuto\",\n \"Enter\": \"newlineAndIndent\", \"Insert\": \"toggleOverwrite\",\n \"Esc\": \"singleSelection\"\n };\n // Note that the save and find-related commands aren't defined by\n // default. User code or addons can define them. Unknown commands\n // are simply ignored.\n keyMap.pcDefault = {\n \"Ctrl-A\": \"selectAll\", \"Ctrl-D\": \"deleteLine\", \"Ctrl-Z\": \"undo\", \"Shift-Ctrl-Z\": \"redo\", \"Ctrl-Y\": \"redo\",\n \"Ctrl-Home\": \"goDocStart\", \"Ctrl-End\": \"goDocEnd\", \"Ctrl-Up\": \"goLineUp\", \"Ctrl-Down\": \"goLineDown\",\n \"Ctrl-Left\": \"goGroupLeft\", \"Ctrl-Right\": \"goGroupRight\", \"Alt-Left\": \"goLineStart\", \"Alt-Right\": \"goLineEnd\",\n \"Ctrl-Backspace\": \"delGroupBefore\", \"Ctrl-Delete\": \"delGroupAfter\", \"Ctrl-S\": \"save\", \"Ctrl-F\": \"find\",\n \"Ctrl-G\": \"findNext\", \"Shift-Ctrl-G\": \"findPrev\", \"Shift-Ctrl-F\": \"replace\", \"Shift-Ctrl-R\": \"replaceAll\",\n \"Ctrl-[\": \"indentLess\", \"Ctrl-]\": \"indentMore\",\n \"Ctrl-U\": \"undoSelection\", \"Shift-Ctrl-U\": \"redoSelection\", \"Alt-U\": \"redoSelection\",\n \"fallthrough\": \"basic\"\n };\n // Very basic readline/emacs-style bindings, which are standard on Mac.\n keyMap.emacsy = {\n \"Ctrl-F\": \"goCharRight\", \"Ctrl-B\": \"goCharLeft\", \"Ctrl-P\": \"goLineUp\", \"Ctrl-N\": \"goLineDown\",\n \"Alt-F\": \"goWordRight\", \"Alt-B\": \"goWordLeft\", \"Ctrl-A\": \"goLineStart\", \"Ctrl-E\": \"goLineEnd\",\n \"Ctrl-V\": \"goPageDown\", \"Shift-Ctrl-V\": \"goPageUp\", \"Ctrl-D\": \"delCharAfter\", \"Ctrl-H\": \"delCharBefore\",\n \"Alt-D\": \"delWordAfter\", \"Alt-Backspace\": \"delWordBefore\", \"Ctrl-K\": \"killLine\", \"Ctrl-T\": \"transposeChars\",\n \"Ctrl-O\": \"openLine\"\n };\n keyMap.macDefault = {\n \"Cmd-A\": \"selectAll\", \"Cmd-D\": \"deleteLine\", \"Cmd-Z\": \"undo\", \"Shift-Cmd-Z\": \"redo\", \"Cmd-Y\": \"redo\",\n \"Cmd-Home\": \"goDocStart\", \"Cmd-Up\": \"goDocStart\", \"Cmd-End\": \"goDocEnd\", \"Cmd-Down\": \"goDocEnd\", \"Alt-Left\": \"goGroupLeft\",\n \"Alt-Right\": \"goGroupRight\", \"Cmd-Left\": \"goLineLeft\", \"Cmd-Right\": \"goLineRight\", \"Alt-Backspace\": \"delGroupBefore\",\n \"Ctrl-Alt-Backspace\": \"delGroupAfter\", \"Alt-Delete\": \"delGroupAfter\", \"Cmd-S\": \"save\", \"Cmd-F\": \"find\",\n \"Cmd-G\": \"findNext\", \"Shift-Cmd-G\": \"findPrev\", \"Cmd-Alt-F\": \"replace\", \"Shift-Cmd-Alt-F\": \"replaceAll\",\n \"Cmd-[\": \"indentLess\", \"Cmd-]\": \"indentMore\", \"Cmd-Backspace\": \"delWrappedLineLeft\", \"Cmd-Delete\": \"delWrappedLineRight\",\n \"Cmd-U\": \"undoSelection\", \"Shift-Cmd-U\": \"redoSelection\", \"Ctrl-Up\": \"goDocStart\", \"Ctrl-Down\": \"goDocEnd\",\n \"fallthrough\": [\"basic\", \"emacsy\"]\n };\n keyMap[\"default\"] = mac ? keyMap.macDefault : keyMap.pcDefault;\n\n // KEYMAP DISPATCH\n\n function normalizeKeyName(name) {\n var parts = name.split(/-(?!$)/);\n name = parts[parts.length - 1];\n var alt, ctrl, shift, cmd;\n for (var i = 0; i < parts.length - 1; i++) {\n var mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }\n else if (/^a(lt)?$/i.test(mod)) { alt = true; }\n else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }\n else if (/^s(hift)?$/i.test(mod)) { shift = true; }\n else { throw new Error(\"Unrecognized modifier name: \" + mod) }\n }\n if (alt) { name = \"Alt-\" + name; }\n if (ctrl) { name = \"Ctrl-\" + name; }\n if (cmd) { name = \"Cmd-\" + name; }\n if (shift) { name = \"Shift-\" + name; }\n return name\n }\n\n // This is a kludge to keep keymaps mostly working as raw objects\n // (backwards compatibility) while at the same time support features\n // like normalization and multi-stroke key bindings. It compiles a\n // new normalized keymap, and then updates the old object to reflect\n // this.\n function normalizeKeyMap(keymap) {\n var copy = {};\n for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {\n var value = keymap[keyname];\n if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }\n if (value == \"...\") { delete keymap[keyname]; continue }\n\n var keys = map(keyname.split(\" \"), normalizeKeyName);\n for (var i = 0; i < keys.length; i++) {\n var val = (void 0), name = (void 0);\n if (i == keys.length - 1) {\n name = keys.join(\" \");\n val = value;\n } else {\n name = keys.slice(0, i + 1).join(\" \");\n val = \"...\";\n }\n var prev = copy[name];\n if (!prev) { copy[name] = val; }\n else if (prev != val) { throw new Error(\"Inconsistent bindings for \" + name) }\n }\n delete keymap[keyname];\n } }\n for (var prop in copy) { keymap[prop] = copy[prop]; }\n return keymap\n }\n\n function lookupKey(key, map$$1, handle, context) {\n map$$1 = getKeyMap(map$$1);\n var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];\n if (found === false) { return \"nothing\" }\n if (found === \"...\") { return \"multi\" }\n if (found != null && handle(found)) { return \"handled\" }\n\n if (map$$1.fallthrough) {\n if (Object.prototype.toString.call(map$$1.fallthrough) != \"[object Array]\")\n { return lookupKey(key, map$$1.fallthrough, handle, context) }\n for (var i = 0; i < map$$1.fallthrough.length; i++) {\n var result = lookupKey(key, map$$1.fallthrough[i], handle, context);\n if (result) { return result }\n }\n }\n }\n\n // Modifier key presses don't count as 'real' key presses for the\n // purpose of keymap fallthrough.\n function isModifierKey(value) {\n var name = typeof value == \"string\" ? value : keyNames[value.keyCode];\n return name == \"Ctrl\" || name == \"Alt\" || name == \"Shift\" || name == \"Mod\"\n }\n\n function addModifierNames(name, event, noShift) {\n var base = name;\n if (event.altKey && base != \"Alt\") { name = \"Alt-\" + name; }\n if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != \"Ctrl\") { name = \"Ctrl-\" + name; }\n if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != \"Cmd\") { name = \"Cmd-\" + name; }\n if (!noShift && event.shiftKey && base != \"Shift\") { name = \"Shift-\" + name; }\n return name\n }\n\n // Look up the name of a key as indicated by an event object.\n function keyName(event, noShift) {\n if (presto && event.keyCode == 34 && event[\"char\"]) { return false }\n var name = keyNames[event.keyCode];\n if (name == null || event.altGraphKey) { return false }\n // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,\n // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)\n if (event.keyCode == 3 && event.code) { name = event.code; }\n return addModifierNames(name, event, noShift)\n }\n\n function getKeyMap(val) {\n return typeof val == \"string\" ? keyMap[val] : val\n }\n\n // Helper for deleting text near the selection(s), used to implement\n // backspace, delete, and similar functionality.\n function deleteNearSelection(cm, compute) {\n var ranges = cm.doc.sel.ranges, kill = [];\n // Build up a set of ranges to kill first, merging overlapping\n // ranges.\n for (var i = 0; i < ranges.length; i++) {\n var toKill = compute(ranges[i]);\n while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {\n var replaced = kill.pop();\n if (cmp(replaced.from, toKill.from) < 0) {\n toKill.from = replaced.from;\n break\n }\n }\n kill.push(toKill);\n }\n // Next, remove those actual ranges.\n runInOp(cm, function () {\n for (var i = kill.length - 1; i >= 0; i--)\n { replaceRange(cm.doc, \"\", kill[i].from, kill[i].to, \"+delete\"); }\n ensureCursorVisible(cm);\n });\n }\n\n function moveCharLogically(line, ch, dir) {\n var target = skipExtendingChars(line.text, ch + dir, dir);\n return target < 0 || target > line.text.length ? null : target\n }\n\n function moveLogically(line, start, dir) {\n var ch = moveCharLogically(line, start.ch, dir);\n return ch == null ? null : new Pos(start.line, ch, dir < 0 ? \"after\" : \"before\")\n }\n\n function endOfLine(visually, cm, lineObj, lineNo, dir) {\n if (visually) {\n var order = getOrder(lineObj, cm.doc.direction);\n if (order) {\n var part = dir < 0 ? lst(order) : order[0];\n var moveInStorageOrder = (dir < 0) == (part.level == 1);\n var sticky = moveInStorageOrder ? \"after\" : \"before\";\n var ch;\n // With a wrapped rtl chunk (possibly spanning multiple bidi parts),\n // it could be that the last bidi part is not on the last visual line,\n // since visual lines contain content order-consecutive chunks.\n // Thus, in rtl, we are looking for the first (content-order) character\n // in the rtl chunk that is on the last line (that is, the same line\n // as the last (content-order) character).\n if (part.level > 0 || cm.doc.direction == \"rtl\") {\n var prep = prepareMeasureForLine(cm, lineObj);\n ch = dir < 0 ? lineObj.text.length - 1 : 0;\n var targetTop = measureCharPrepared(cm, prep, ch).top;\n ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);\n if (sticky == \"before\") { ch = moveCharLogically(lineObj, ch, 1); }\n } else { ch = dir < 0 ? part.to : part.from; }\n return new Pos(lineNo, ch, sticky)\n }\n }\n return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? \"before\" : \"after\")\n }\n\n function moveVisually(cm, line, start, dir) {\n var bidi = getOrder(line, cm.doc.direction);\n if (!bidi) { return moveLogically(line, start, dir) }\n if (start.ch >= line.text.length) {\n start.ch = line.text.length;\n start.sticky = \"before\";\n } else if (start.ch <= 0) {\n start.ch = 0;\n start.sticky = \"after\";\n }\n var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];\n if (cm.doc.direction == \"ltr\" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {\n // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,\n // nothing interesting happens.\n return moveLogically(line, start, dir)\n }\n\n var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };\n var prep;\n var getWrappedLineExtent = function (ch) {\n if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }\n prep = prep || prepareMeasureForLine(cm, line);\n return wrappedLineExtentChar(cm, line, prep, ch)\n };\n var wrappedLineExtent = getWrappedLineExtent(start.sticky == \"before\" ? mv(start, -1) : start.ch);\n\n if (cm.doc.direction == \"rtl\" || part.level == 1) {\n var moveInStorageOrder = (part.level == 1) == (dir < 0);\n var ch = mv(start, moveInStorageOrder ? 1 : -1);\n if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {\n // Case 2: We move within an rtl part or in an rtl editor on the same visual line\n var sticky = moveInStorageOrder ? \"before\" : \"after\";\n return new Pos(start.line, ch, sticky)\n }\n }\n\n // Case 3: Could not move within this bidi part in this visual line, so leave\n // the current bidi part\n\n var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {\n var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder\n ? new Pos(start.line, mv(ch, 1), \"before\")\n : new Pos(start.line, ch, \"after\"); };\n\n for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {\n var part = bidi[partPos];\n var moveInStorageOrder = (dir > 0) == (part.level != 1);\n var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);\n if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }\n ch = moveInStorageOrder ? part.from : mv(part.to, -1);\n if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }\n }\n };\n\n // Case 3a: Look for other bidi parts on the same visual line\n var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);\n if (res) { return res }\n\n // Case 3b: Look for other bidi parts on the next visual line\n var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);\n if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {\n res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));\n if (res) { return res }\n }\n\n // Case 4: Nowhere to move\n return null\n }\n\n // Commands are parameter-less actions that can be performed on an\n // editor, mostly used for keybindings.\n var commands = {\n selectAll: selectAll,\n singleSelection: function (cm) { return cm.setSelection(cm.getCursor(\"anchor\"), cm.getCursor(\"head\"), sel_dontScroll); },\n killLine: function (cm) { return deleteNearSelection(cm, function (range) {\n if (range.empty()) {\n var len = getLine(cm.doc, range.head.line).text.length;\n if (range.head.ch == len && range.head.line < cm.lastLine())\n { return {from: range.head, to: Pos(range.head.line + 1, 0)} }\n else\n { return {from: range.head, to: Pos(range.head.line, len)} }\n } else {\n return {from: range.from(), to: range.to()}\n }\n }); },\n deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({\n from: Pos(range.from().line, 0),\n to: clipPos(cm.doc, Pos(range.to().line + 1, 0))\n }); }); },\n delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({\n from: Pos(range.from().line, 0), to: range.from()\n }); }); },\n delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {\n var top = cm.charCoords(range.head, \"div\").top + 5;\n var leftPos = cm.coordsChar({left: 0, top: top}, \"div\");\n return {from: leftPos, to: range.from()}\n }); },\n delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {\n var top = cm.charCoords(range.head, \"div\").top + 5;\n var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\");\n return {from: range.from(), to: rightPos }\n }); },\n undo: function (cm) { return cm.undo(); },\n redo: function (cm) { return cm.redo(); },\n undoSelection: function (cm) { return cm.undoSelection(); },\n redoSelection: function (cm) { return cm.redoSelection(); },\n goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },\n goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },\n goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },\n {origin: \"+move\", bias: 1}\n ); },\n goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },\n {origin: \"+move\", bias: 1}\n ); },\n goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },\n {origin: \"+move\", bias: -1}\n ); },\n goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {\n var top = cm.cursorCoords(range.head, \"div\").top + 5;\n return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\")\n }, sel_move); },\n goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {\n var top = cm.cursorCoords(range.head, \"div\").top + 5;\n return cm.coordsChar({left: 0, top: top}, \"div\")\n }, sel_move); },\n goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {\n var top = cm.cursorCoords(range.head, \"div\").top + 5;\n var pos = cm.coordsChar({left: 0, top: top}, \"div\");\n if (pos.ch < cm.getLine(pos.line).search(/\\S/)) { return lineStartSmart(cm, range.head) }\n return pos\n }, sel_move); },\n goLineUp: function (cm) { return cm.moveV(-1, \"line\"); },\n goLineDown: function (cm) { return cm.moveV(1, \"line\"); },\n goPageUp: function (cm) { return cm.moveV(-1, \"page\"); },\n goPageDown: function (cm) { return cm.moveV(1, \"page\"); },\n goCharLeft: function (cm) { return cm.moveH(-1, \"char\"); },\n goCharRight: function (cm) { return cm.moveH(1, \"char\"); },\n goColumnLeft: function (cm) { return cm.moveH(-1, \"column\"); },\n goColumnRight: function (cm) { return cm.moveH(1, \"column\"); },\n goWordLeft: function (cm) { return cm.moveH(-1, \"word\"); },\n goGroupRight: function (cm) { return cm.moveH(1, \"group\"); },\n goGroupLeft: function (cm) { return cm.moveH(-1, \"group\"); },\n goWordRight: function (cm) { return cm.moveH(1, \"word\"); },\n delCharBefore: function (cm) { return cm.deleteH(-1, \"char\"); },\n delCharAfter: function (cm) { return cm.deleteH(1, \"char\"); },\n delWordBefore: function (cm) { return cm.deleteH(-1, \"word\"); },\n delWordAfter: function (cm) { return cm.deleteH(1, \"word\"); },\n delGroupBefore: function (cm) { return cm.deleteH(-1, \"group\"); },\n delGroupAfter: function (cm) { return cm.deleteH(1, \"group\"); },\n indentAuto: function (cm) { return cm.indentSelection(\"smart\"); },\n indentMore: function (cm) { return cm.indentSelection(\"add\"); },\n indentLess: function (cm) { return cm.indentSelection(\"subtract\"); },\n insertTab: function (cm) { return cm.replaceSelection(\"\\t\"); },\n insertSoftTab: function (cm) {\n var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;\n for (var i = 0; i < ranges.length; i++) {\n var pos = ranges[i].from();\n var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);\n spaces.push(spaceStr(tabSize - col % tabSize));\n }\n cm.replaceSelections(spaces);\n },\n defaultTab: function (cm) {\n if (cm.somethingSelected()) { cm.indentSelection(\"add\"); }\n else { cm.execCommand(\"insertTab\"); }\n },\n // Swap the two chars left and right of each selection's head.\n // Move cursor behind the two swapped characters afterwards.\n //\n // Doesn't consider line feeds a character.\n // Doesn't scan more than one line above to find a character.\n // Doesn't do anything on an empty line.\n // Doesn't do anything with non-empty selections.\n transposeChars: function (cm) { return runInOp(cm, function () {\n var ranges = cm.listSelections(), newSel = [];\n for (var i = 0; i < ranges.length; i++) {\n if (!ranges[i].empty()) { continue }\n var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;\n if (line) {\n if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }\n if (cur.ch > 0) {\n cur = new Pos(cur.line, cur.ch + 1);\n cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),\n Pos(cur.line, cur.ch - 2), cur, \"+transpose\");\n } else if (cur.line > cm.doc.first) {\n var prev = getLine(cm.doc, cur.line - 1).text;\n if (prev) {\n cur = new Pos(cur.line, 1);\n cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +\n prev.charAt(prev.length - 1),\n Pos(cur.line - 1, prev.length - 1), cur, \"+transpose\");\n }\n }\n }\n newSel.push(new Range(cur, cur));\n }\n cm.setSelections(newSel);\n }); },\n newlineAndIndent: function (cm) { return runInOp(cm, function () {\n var sels = cm.listSelections();\n for (var i = sels.length - 1; i >= 0; i--)\n { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, \"+input\"); }\n sels = cm.listSelections();\n for (var i$1 = 0; i$1 < sels.length; i$1++)\n { cm.indentLine(sels[i$1].from().line, null, true); }\n ensureCursorVisible(cm);\n }); },\n openLine: function (cm) { return cm.replaceSelection(\"\\n\", \"start\"); },\n toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }\n };\n\n\n function lineStart(cm, lineN) {\n var line = getLine(cm.doc, lineN);\n var visual = visualLine(line);\n if (visual != line) { lineN = lineNo(visual); }\n return endOfLine(true, cm, visual, lineN, 1)\n }\n function lineEnd(cm, lineN) {\n var line = getLine(cm.doc, lineN);\n var visual = visualLineEnd(line);\n if (visual != line) { lineN = lineNo(visual); }\n return endOfLine(true, cm, line, lineN, -1)\n }\n function lineStartSmart(cm, pos) {\n var start = lineStart(cm, pos.line);\n var line = getLine(cm.doc, start.line);\n var order = getOrder(line, cm.doc.direction);\n if (!order || order[0].level == 0) {\n var firstNonWS = Math.max(0, line.text.search(/\\S/));\n var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;\n return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)\n }\n return start\n }\n\n // Run a handler that was bound to a key.\n function doHandleBinding(cm, bound, dropShift) {\n if (typeof bound == \"string\") {\n bound = commands[bound];\n if (!bound) { return false }\n }\n // Ensure previous input has been read, so that the handler sees a\n // consistent view of the document\n cm.display.input.ensurePolled();\n var prevShift = cm.display.shift, done = false;\n try {\n if (cm.isReadOnly()) { cm.state.suppressEdits = true; }\n if (dropShift) { cm.display.shift = false; }\n done = bound(cm) != Pass;\n } finally {\n cm.display.shift = prevShift;\n cm.state.suppressEdits = false;\n }\n return done\n }\n\n function lookupKeyForEditor(cm, name, handle) {\n for (var i = 0; i < cm.state.keyMaps.length; i++) {\n var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);\n if (result) { return result }\n }\n return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))\n || lookupKey(name, cm.options.keyMap, handle, cm)\n }\n\n // Note that, despite the name, this function is also used to check\n // for bound mouse clicks.\n\n var stopSeq = new Delayed;\n\n function dispatchKey(cm, name, e, handle) {\n var seq = cm.state.keySeq;\n if (seq) {\n if (isModifierKey(name)) { return \"handled\" }\n if (/\\'$/.test(name))\n { cm.state.keySeq = null; }\n else\n { stopSeq.set(50, function () {\n if (cm.state.keySeq == seq) {\n cm.state.keySeq = null;\n cm.display.input.reset();\n }\n }); }\n if (dispatchKeyInner(cm, seq + \" \" + name, e, handle)) { return true }\n }\n return dispatchKeyInner(cm, name, e, handle)\n }\n\n function dispatchKeyInner(cm, name, e, handle) {\n var result = lookupKeyForEditor(cm, name, handle);\n\n if (result == \"multi\")\n { cm.state.keySeq = name; }\n if (result == \"handled\")\n { signalLater(cm, \"keyHandled\", cm, name, e); }\n\n if (result == \"handled\" || result == \"multi\") {\n e_preventDefault(e);\n restartBlink(cm);\n }\n\n return !!result\n }\n\n // Handle a key from the keydown event.\n function handleKeyBinding(cm, e) {\n var name = keyName(e, true);\n if (!name) { return false }\n\n if (e.shiftKey && !cm.state.keySeq) {\n // First try to resolve full name (including 'Shift-'). Failing\n // that, see if there is a cursor-motion command (starting with\n // 'go') bound to the keyname without 'Shift-'.\n return dispatchKey(cm, \"Shift-\" + name, e, function (b) { return doHandleBinding(cm, b, true); })\n || dispatchKey(cm, name, e, function (b) {\n if (typeof b == \"string\" ? /^go[A-Z]/.test(b) : b.motion)\n { return doHandleBinding(cm, b) }\n })\n } else {\n return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })\n }\n }\n\n // Handle a key from the keypress event\n function handleCharBinding(cm, e, ch) {\n return dispatchKey(cm, \"'\" + ch + \"'\", e, function (b) { return doHandleBinding(cm, b, true); })\n }\n\n var lastStoppedKey = null;\n function onKeyDown(e) {\n var cm = this;\n cm.curOp.focus = activeElt();\n if (signalDOMEvent(cm, e)) { return }\n // IE does strange things with escape.\n if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }\n var code = e.keyCode;\n cm.display.shift = code == 16 || e.shiftKey;\n var handled = handleKeyBinding(cm, e);\n if (presto) {\n lastStoppedKey = handled ? code : null;\n // Opera has no cut event... we try to at least catch the key combo\n if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))\n { cm.replaceSelection(\"\", null, \"cut\"); }\n }\n\n // Turn mouse into crosshair when Alt is held on Mac.\n if (code == 18 && !/\\bCodeMirror-crosshair\\b/.test(cm.display.lineDiv.className))\n { showCrossHair(cm); }\n }\n\n function showCrossHair(cm) {\n var lineDiv = cm.display.lineDiv;\n addClass(lineDiv, \"CodeMirror-crosshair\");\n\n function up(e) {\n if (e.keyCode == 18 || !e.altKey) {\n rmClass(lineDiv, \"CodeMirror-crosshair\");\n off(document, \"keyup\", up);\n off(document, \"mouseover\", up);\n }\n }\n on(document, \"keyup\", up);\n on(document, \"mouseover\", up);\n }\n\n function onKeyUp(e) {\n if (e.keyCode == 16) { this.doc.sel.shift = false; }\n signalDOMEvent(this, e);\n }\n\n function onKeyPress(e) {\n var cm = this;\n if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }\n var keyCode = e.keyCode, charCode = e.charCode;\n if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}\n if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }\n var ch = String.fromCharCode(charCode == null ? keyCode : charCode);\n // Some browsers fire keypress events for backspace\n if (ch == \"\\x08\") { return }\n if (handleCharBinding(cm, e, ch)) { return }\n cm.display.input.onKeyPress(e);\n }\n\n var DOUBLECLICK_DELAY = 400;\n\n var PastClick = function(time, pos, button) {\n this.time = time;\n this.pos = pos;\n this.button = button;\n };\n\n PastClick.prototype.compare = function (time, pos, button) {\n return this.time + DOUBLECLICK_DELAY > time &&\n cmp(pos, this.pos) == 0 && button == this.button\n };\n\n var lastClick, lastDoubleClick;\n function clickRepeat(pos, button) {\n var now = +new Date;\n if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {\n lastClick = lastDoubleClick = null;\n return \"triple\"\n } else if (lastClick && lastClick.compare(now, pos, button)) {\n lastDoubleClick = new PastClick(now, pos, button);\n lastClick = null;\n return \"double\"\n } else {\n lastClick = new PastClick(now, pos, button);\n lastDoubleClick = null;\n return \"single\"\n }\n }\n\n // A mouse down can be a single click, double click, triple click,\n // start of selection drag, start of text drag, new cursor\n // (ctrl-click), rectangle drag (alt-drag), or xwin\n // middle-click-paste. Or it might be a click on something we should\n // not interfere with, such as a scrollbar or widget.\n function onMouseDown(e) {\n var cm = this, display = cm.display;\n if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }\n display.input.ensurePolled();\n display.shift = e.shiftKey;\n\n if (eventInWidget(display, e)) {\n if (!webkit) {\n // Briefly turn off draggability, to allow widgets to do\n // normal dragging things.\n display.scroller.draggable = false;\n setTimeout(function () { return display.scroller.draggable = true; }, 100);\n }\n return\n }\n if (clickInGutter(cm, e)) { return }\n var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : \"single\";\n window.focus();\n\n // #3261: make sure, that we're not starting a second selection\n if (button == 1 && cm.state.selectingText)\n { cm.state.selectingText(e); }\n\n if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }\n\n if (button == 1) {\n if (pos) { leftButtonDown(cm, pos, repeat, e); }\n else if (e_target(e) == display.scroller) { e_preventDefault(e); }\n } else if (button == 2) {\n if (pos) { extendSelection(cm.doc, pos); }\n setTimeout(function () { return display.input.focus(); }, 20);\n } else if (button == 3) {\n if (captureRightClick) { cm.display.input.onContextMenu(e); }\n else { delayBlurEvent(cm); }\n }\n }\n\n function handleMappedButton(cm, button, pos, repeat, event) {\n var name = \"Click\";\n if (repeat == \"double\") { name = \"Double\" + name; }\n else if (repeat == \"triple\") { name = \"Triple\" + name; }\n name = (button == 1 ? \"Left\" : button == 2 ? \"Middle\" : \"Right\") + name;\n\n return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {\n if (typeof bound == \"string\") { bound = commands[bound]; }\n if (!bound) { return false }\n var done = false;\n try {\n if (cm.isReadOnly()) { cm.state.suppressEdits = true; }\n done = bound(cm, pos) != Pass;\n } finally {\n cm.state.suppressEdits = false;\n }\n return done\n })\n }\n\n function configureMouse(cm, repeat, event) {\n var option = cm.getOption(\"configureMouse\");\n var value = option ? option(cm, repeat, event) : {};\n if (value.unit == null) {\n var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;\n value.unit = rect ? \"rectangle\" : repeat == \"single\" ? \"char\" : repeat == \"double\" ? \"word\" : \"line\";\n }\n if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }\n if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }\n if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }\n return value\n }\n\n function leftButtonDown(cm, pos, repeat, event) {\n if (ie) { setTimeout(bind(ensureFocus, cm), 0); }\n else { cm.curOp.focus = activeElt(); }\n\n var behavior = configureMouse(cm, repeat, event);\n\n var sel = cm.doc.sel, contained;\n if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&\n repeat == \"single\" && (contained = sel.contains(pos)) > -1 &&\n (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&\n (cmp(contained.to(), pos) > 0 || pos.xRel < 0))\n { leftButtonStartDrag(cm, event, pos, behavior); }\n else\n { leftButtonSelect(cm, event, pos, behavior); }\n }\n\n // Start a text drag. When it ends, see if any dragging actually\n // happen, and treat as a click if it didn't.\n function leftButtonStartDrag(cm, event, pos, behavior) {\n var display = cm.display, moved = false;\n var dragEnd = operation(cm, function (e) {\n if (webkit) { display.scroller.draggable = false; }\n cm.state.draggingText = false;\n off(display.wrapper.ownerDocument, \"mouseup\", dragEnd);\n off(display.wrapper.ownerDocument, \"mousemove\", mouseMove);\n off(display.scroller, \"dragstart\", dragStart);\n off(display.scroller, \"drop\", dragEnd);\n if (!moved) {\n e_preventDefault(e);\n if (!behavior.addNew)\n { extendSelection(cm.doc, pos, null, null, behavior.extend); }\n // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)\n if (webkit || ie && ie_version == 9)\n { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }\n else\n { display.input.focus(); }\n }\n });\n var mouseMove = function(e2) {\n moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;\n };\n var dragStart = function () { return moved = true; };\n // Let the drag handler handle this.\n if (webkit) { display.scroller.draggable = true; }\n cm.state.draggingText = dragEnd;\n dragEnd.copy = !behavior.moveOnDrag;\n // IE's approach to draggable\n if (display.scroller.dragDrop) { display.scroller.dragDrop(); }\n on(display.wrapper.ownerDocument, \"mouseup\", dragEnd);\n on(display.wrapper.ownerDocument, \"mousemove\", mouseMove);\n on(display.scroller, \"dragstart\", dragStart);\n on(display.scroller, \"drop\", dragEnd);\n\n delayBlurEvent(cm);\n setTimeout(function () { return display.input.focus(); }, 20);\n }\n\n function rangeForUnit(cm, pos, unit) {\n if (unit == \"char\") { return new Range(pos, pos) }\n if (unit == \"word\") { return cm.findWordAt(pos) }\n if (unit == \"line\") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }\n var result = unit(cm, pos);\n return new Range(result.from, result.to)\n }\n\n // Normal selection, as opposed to text dragging.\n function leftButtonSelect(cm, event, start, behavior) {\n var display = cm.display, doc = cm.doc;\n e_preventDefault(event);\n\n var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;\n if (behavior.addNew && !behavior.extend) {\n ourIndex = doc.sel.contains(start);\n if (ourIndex > -1)\n { ourRange = ranges[ourIndex]; }\n else\n { ourRange = new Range(start, start); }\n } else {\n ourRange = doc.sel.primary();\n ourIndex = doc.sel.primIndex;\n }\n\n if (behavior.unit == \"rectangle\") {\n if (!behavior.addNew) { ourRange = new Range(start, start); }\n start = posFromMouse(cm, event, true, true);\n ourIndex = -1;\n } else {\n var range$$1 = rangeForUnit(cm, start, behavior.unit);\n if (behavior.extend)\n { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }\n else\n { ourRange = range$$1; }\n }\n\n if (!behavior.addNew) {\n ourIndex = 0;\n setSelection(doc, new Selection([ourRange], 0), sel_mouse);\n startSel = doc.sel;\n } else if (ourIndex == -1) {\n ourIndex = ranges.length;\n setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),\n {scroll: false, origin: \"*mouse\"});\n } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == \"char\" && !behavior.extend) {\n setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),\n {scroll: false, origin: \"*mouse\"});\n startSel = doc.sel;\n } else {\n replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);\n }\n\n var lastPos = start;\n function extendTo(pos) {\n if (cmp(lastPos, pos) == 0) { return }\n lastPos = pos;\n\n if (behavior.unit == \"rectangle\") {\n var ranges = [], tabSize = cm.options.tabSize;\n var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);\n var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);\n var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);\n for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));\n line <= end; line++) {\n var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);\n if (left == right)\n { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }\n else if (text.length > leftPos)\n { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }\n }\n if (!ranges.length) { ranges.push(new Range(start, start)); }\n setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),\n {origin: \"*mouse\", scroll: false});\n cm.scrollIntoView(pos);\n } else {\n var oldRange = ourRange;\n var range$$1 = rangeForUnit(cm, pos, behavior.unit);\n var anchor = oldRange.anchor, head;\n if (cmp(range$$1.anchor, anchor) > 0) {\n head = range$$1.head;\n anchor = minPos(oldRange.from(), range$$1.anchor);\n } else {\n head = range$$1.anchor;\n anchor = maxPos(oldRange.to(), range$$1.head);\n }\n var ranges$1 = startSel.ranges.slice(0);\n ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));\n setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);\n }\n }\n\n var editorSize = display.wrapper.getBoundingClientRect();\n // Used to ensure timeout re-tries don't fire when another extend\n // happened in the meantime (clearTimeout isn't reliable -- at\n // least on Chrome, the timeouts still happen even when cleared,\n // if the clear happens after their scheduled firing time).\n var counter = 0;\n\n function extend(e) {\n var curCount = ++counter;\n var cur = posFromMouse(cm, e, true, behavior.unit == \"rectangle\");\n if (!cur) { return }\n if (cmp(cur, lastPos) != 0) {\n cm.curOp.focus = activeElt();\n extendTo(cur);\n var visible = visibleLines(display, doc);\n if (cur.line >= visible.to || cur.line < visible.from)\n { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }\n } else {\n var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;\n if (outside) { setTimeout(operation(cm, function () {\n if (counter != curCount) { return }\n display.scroller.scrollTop += outside;\n extend(e);\n }), 50); }\n }\n }\n\n function done(e) {\n cm.state.selectingText = false;\n counter = Infinity;\n e_preventDefault(e);\n display.input.focus();\n off(display.wrapper.ownerDocument, \"mousemove\", move);\n off(display.wrapper.ownerDocument, \"mouseup\", up);\n doc.history.lastSelOrigin = null;\n }\n\n var move = operation(cm, function (e) {\n if (e.buttons === 0 || !e_button(e)) { done(e); }\n else { extend(e); }\n });\n var up = operation(cm, done);\n cm.state.selectingText = up;\n on(display.wrapper.ownerDocument, \"mousemove\", move);\n on(display.wrapper.ownerDocument, \"mouseup\", up);\n }\n\n // Used when mouse-selecting to adjust the anchor to the proper side\n // of a bidi jump depending on the visual position of the head.\n function bidiSimplify(cm, range$$1) {\n var anchor = range$$1.anchor;\n var head = range$$1.head;\n var anchorLine = getLine(cm.doc, anchor.line);\n if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }\n var order = getOrder(anchorLine);\n if (!order) { return range$$1 }\n var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];\n if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }\n var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);\n if (boundary == 0 || boundary == order.length) { return range$$1 }\n\n // Compute the relative visual position of the head compared to the\n // anchor (<0 is to the left, >0 to the right)\n var leftSide;\n if (head.line != anchor.line) {\n leftSide = (head.line - anchor.line) * (cm.doc.direction == \"ltr\" ? 1 : -1) > 0;\n } else {\n var headIndex = getBidiPartAt(order, head.ch, head.sticky);\n var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);\n if (headIndex == boundary - 1 || headIndex == boundary)\n { leftSide = dir < 0; }\n else\n { leftSide = dir > 0; }\n }\n\n var usePart = order[boundary + (leftSide ? -1 : 0)];\n var from = leftSide == (usePart.level == 1);\n var ch = from ? usePart.from : usePart.to, sticky = from ? \"after\" : \"before\";\n return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)\n }\n\n\n // Determines whether an event happened in the gutter, and fires the\n // handlers for the corresponding event.\n function gutterEvent(cm, e, type, prevent) {\n var mX, mY;\n if (e.touches) {\n mX = e.touches[0].clientX;\n mY = e.touches[0].clientY;\n } else {\n try { mX = e.clientX; mY = e.clientY; }\n catch(e) { return false }\n }\n if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }\n if (prevent) { e_preventDefault(e); }\n\n var display = cm.display;\n var lineBox = display.lineDiv.getBoundingClientRect();\n\n if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }\n mY -= lineBox.top - display.viewOffset;\n\n for (var i = 0; i < cm.options.gutters.length; ++i) {\n var g = display.gutters.childNodes[i];\n if (g && g.getBoundingClientRect().right >= mX) {\n var line = lineAtHeight(cm.doc, mY);\n var gutter = cm.options.gutters[i];\n signal(cm, type, cm, line, gutter, e);\n return e_defaultPrevented(e)\n }\n }\n }\n\n function clickInGutter(cm, e) {\n return gutterEvent(cm, e, \"gutterClick\", true)\n }\n\n // CONTEXT MENU HANDLING\n\n // To make the context menu work, we need to briefly unhide the\n // textarea (making it as unobtrusive as possible) to let the\n // right-click take effect on it.\n function onContextMenu(cm, e) {\n if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }\n if (signalDOMEvent(cm, e, \"contextmenu\")) { return }\n if (!captureRightClick) { cm.display.input.onContextMenu(e); }\n }\n\n function contextMenuInGutter(cm, e) {\n if (!hasHandler(cm, \"gutterContextMenu\")) { return false }\n return gutterEvent(cm, e, \"gutterContextMenu\", false)\n }\n\n function themeChanged(cm) {\n cm.display.wrapper.className = cm.display.wrapper.className.replace(/\\s*cm-s-\\S+/g, \"\") +\n cm.options.theme.replace(/(^|\\s)\\s*/g, \" cm-s-\");\n clearCaches(cm);\n }\n\n var Init = {toString: function(){return \"CodeMirror.Init\"}};\n\n var defaults = {};\n var optionHandlers = {};\n\n function defineOptions(CodeMirror) {\n var optionHandlers = CodeMirror.optionHandlers;\n\n function option(name, deflt, handle, notOnInit) {\n CodeMirror.defaults[name] = deflt;\n if (handle) { optionHandlers[name] =\n notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }\n }\n\n CodeMirror.defineOption = option;\n\n // Passed to option handlers when there is no old value.\n CodeMirror.Init = Init;\n\n // These two are, on init, called from the constructor because they\n // have to be initialized before the editor can start at all.\n option(\"value\", \"\", function (cm, val) { return cm.setValue(val); }, true);\n option(\"mode\", null, function (cm, val) {\n cm.doc.modeOption = val;\n loadMode(cm);\n }, true);\n\n option(\"indentUnit\", 2, loadMode, true);\n option(\"indentWithTabs\", false);\n option(\"smartIndent\", true);\n option(\"tabSize\", 4, function (cm) {\n resetModeState(cm);\n clearCaches(cm);\n regChange(cm);\n }, true);\n\n option(\"lineSeparator\", null, function (cm, val) {\n cm.doc.lineSep = val;\n if (!val) { return }\n var newBreaks = [], lineNo = cm.doc.first;\n cm.doc.iter(function (line) {\n for (var pos = 0;;) {\n var found = line.text.indexOf(val, pos);\n if (found == -1) { break }\n pos = found + val.length;\n newBreaks.push(Pos(lineNo, found));\n }\n lineNo++;\n });\n for (var i = newBreaks.length - 1; i >= 0; i--)\n { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }\n });\n option(\"specialChars\", /[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u061c\\u200b-\\u200f\\u2028\\u2029\\ufeff]/g, function (cm, val, old) {\n cm.state.specialChars = new RegExp(val.source + (val.test(\"\\t\") ? \"\" : \"|\\t\"), \"g\");\n if (old != Init) { cm.refresh(); }\n });\n option(\"specialCharPlaceholder\", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);\n option(\"electricChars\", true);\n option(\"inputStyle\", mobile ? \"contenteditable\" : \"textarea\", function () {\n throw new Error(\"inputStyle can not (yet) be changed in a running editor\") // FIXME\n }, true);\n option(\"spellcheck\", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);\n option(\"rtlMoveVisually\", !windows);\n option(\"wholeLineUpdateBefore\", true);\n\n option(\"theme\", \"default\", function (cm) {\n themeChanged(cm);\n guttersChanged(cm);\n }, true);\n option(\"keyMap\", \"default\", function (cm, val, old) {\n var next = getKeyMap(val);\n var prev = old != Init && getKeyMap(old);\n if (prev && prev.detach) { prev.detach(cm, next); }\n if (next.attach) { next.attach(cm, prev || null); }\n });\n option(\"extraKeys\", null);\n option(\"configureMouse\", null);\n\n option(\"lineWrapping\", false, wrappingChanged, true);\n option(\"gutters\", [], function (cm) {\n setGuttersForLineNumbers(cm.options);\n guttersChanged(cm);\n }, true);\n option(\"fixedGutter\", true, function (cm, val) {\n cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + \"px\" : \"0\";\n cm.refresh();\n }, true);\n option(\"coverGutterNextToScrollbar\", false, function (cm) { return updateScrollbars(cm); }, true);\n option(\"scrollbarStyle\", \"native\", function (cm) {\n initScrollbars(cm);\n updateScrollbars(cm);\n cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);\n cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);\n }, true);\n option(\"lineNumbers\", false, function (cm) {\n setGuttersForLineNumbers(cm.options);\n guttersChanged(cm);\n }, true);\n option(\"firstLineNumber\", 1, guttersChanged, true);\n option(\"lineNumberFormatter\", function (integer) { return integer; }, guttersChanged, true);\n option(\"showCursorWhenSelecting\", false, updateSelection, true);\n\n option(\"resetSelectionOnContextMenu\", true);\n option(\"lineWiseCopyCut\", true);\n option(\"pasteLinesPerSelection\", true);\n option(\"selectionsMayTouch\", false);\n\n option(\"readOnly\", false, function (cm, val) {\n if (val == \"nocursor\") {\n onBlur(cm);\n cm.display.input.blur();\n }\n cm.display.input.readOnlyChanged(val);\n });\n option(\"disableInput\", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);\n option(\"dragDrop\", true, dragDropChanged);\n option(\"allowDropFileTypes\", null);\n\n option(\"cursorBlinkRate\", 530);\n option(\"cursorScrollMargin\", 0);\n option(\"cursorHeight\", 1, updateSelection, true);\n option(\"singleCursorHeightPerLine\", true, updateSelection, true);\n option(\"workTime\", 100);\n option(\"workDelay\", 100);\n option(\"flattenSpans\", true, resetModeState, true);\n option(\"addModeClass\", false, resetModeState, true);\n option(\"pollInterval\", 100);\n option(\"undoDepth\", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });\n option(\"historyEventDelay\", 1250);\n option(\"viewportMargin\", 10, function (cm) { return cm.refresh(); }, true);\n option(\"maxHighlightLength\", 10000, resetModeState, true);\n option(\"moveInputWithCursor\", true, function (cm, val) {\n if (!val) { cm.display.input.resetPosition(); }\n });\n\n option(\"tabindex\", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || \"\"; });\n option(\"autofocus\", null);\n option(\"direction\", \"ltr\", function (cm, val) { return cm.doc.setDirection(val); }, true);\n option(\"phrases\", null);\n }\n\n function guttersChanged(cm) {\n updateGutters(cm);\n regChange(cm);\n alignHorizontally(cm);\n }\n\n function dragDropChanged(cm, value, old) {\n var wasOn = old && old != Init;\n if (!value != !wasOn) {\n var funcs = cm.display.dragFunctions;\n var toggle = value ? on : off;\n toggle(cm.display.scroller, \"dragstart\", funcs.start);\n toggle(cm.display.scroller, \"dragenter\", funcs.enter);\n toggle(cm.display.scroller, \"dragover\", funcs.over);\n toggle(cm.display.scroller, \"dragleave\", funcs.leave);\n toggle(cm.display.scroller, \"drop\", funcs.drop);\n }\n }\n\n function wrappingChanged(cm) {\n if (cm.options.lineWrapping) {\n addClass(cm.display.wrapper, \"CodeMirror-wrap\");\n cm.display.sizer.style.minWidth = \"\";\n cm.display.sizerWidth = null;\n } else {\n rmClass(cm.display.wrapper, \"CodeMirror-wrap\");\n findMaxLine(cm);\n }\n estimateLineHeights(cm);\n regChange(cm);\n clearCaches(cm);\n setTimeout(function () { return updateScrollbars(cm); }, 100);\n }\n\n // A CodeMirror instance represents an editor. This is the object\n // that user code is usually dealing with.\n\n function CodeMirror(place, options) {\n var this$1 = this;\n\n if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }\n\n this.options = options = options ? copyObj(options) : {};\n // Determine effective options based on given values and defaults.\n copyObj(defaults, options, false);\n setGuttersForLineNumbers(options);\n\n var doc = options.value;\n if (typeof doc == \"string\") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }\n else if (options.mode) { doc.modeOption = options.mode; }\n this.doc = doc;\n\n var input = new CodeMirror.inputStyles[options.inputStyle](this);\n var display = this.display = new Display(place, doc, input);\n display.wrapper.CodeMirror = this;\n updateGutters(this);\n themeChanged(this);\n if (options.lineWrapping)\n { this.display.wrapper.className += \" CodeMirror-wrap\"; }\n initScrollbars(this);\n\n this.state = {\n keyMaps: [], // stores maps added by addKeyMap\n overlays: [], // highlighting overlays, as added by addOverlay\n modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info\n overwrite: false,\n delayingBlurEvent: false,\n focused: false,\n suppressEdits: false, // used to disable editing during key handlers when in readOnly mode\n pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll\n selectingText: false,\n draggingText: false,\n highlight: new Delayed(), // stores highlight worker timeout\n keySeq: null, // Unfinished key sequence\n specialChars: null\n };\n\n if (options.autofocus && !mobile) { display.input.focus(); }\n\n // Override magic textarea content restore that IE sometimes does\n // on our hidden textarea on reload\n if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }\n\n registerEventHandlers(this);\n ensureGlobalHandlers();\n\n startOperation(this);\n this.curOp.forceUpdate = true;\n attachDoc(this, doc);\n\n if ((options.autofocus && !mobile) || this.hasFocus())\n { setTimeout(bind(onFocus, this), 20); }\n else\n { onBlur(this); }\n\n for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))\n { optionHandlers[opt](this$1, options[opt], Init); } }\n maybeUpdateLineNumberWidth(this);\n if (options.finishInit) { options.finishInit(this); }\n for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }\n endOperation(this);\n // Suppress optimizelegibility in Webkit, since it breaks text\n // measuring on line wrapping boundaries.\n if (webkit && options.lineWrapping &&\n getComputedStyle(display.lineDiv).textRendering == \"optimizelegibility\")\n { display.lineDiv.style.textRendering = \"auto\"; }\n }\n\n // The default configuration options.\n CodeMirror.defaults = defaults;\n // Functions to run when options are changed.\n CodeMirror.optionHandlers = optionHandlers;\n\n // Attach the necessary event handlers when initializing the editor\n function registerEventHandlers(cm) {\n var d = cm.display;\n on(d.scroller, \"mousedown\", operation(cm, onMouseDown));\n // Older IE's will not fire a second mousedown for a double click\n if (ie && ie_version < 11)\n { on(d.scroller, \"dblclick\", operation(cm, function (e) {\n if (signalDOMEvent(cm, e)) { return }\n var pos = posFromMouse(cm, e);\n if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }\n e_preventDefault(e);\n var word = cm.findWordAt(pos);\n extendSelection(cm.doc, word.anchor, word.head);\n })); }\n else\n { on(d.scroller, \"dblclick\", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }\n // Some browsers fire contextmenu *after* opening the menu, at\n // which point we can't mess with it anymore. Context menu is\n // handled in onMouseDown for these browsers.\n on(d.scroller, \"contextmenu\", function (e) { return onContextMenu(cm, e); });\n\n // Used to suppress mouse event handling when a touch happens\n var touchFinished, prevTouch = {end: 0};\n function finishTouch() {\n if (d.activeTouch) {\n touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);\n prevTouch = d.activeTouch;\n prevTouch.end = +new Date;\n }\n }\n function isMouseLikeTouchEvent(e) {\n if (e.touches.length != 1) { return false }\n var touch = e.touches[0];\n return touch.radiusX <= 1 && touch.radiusY <= 1\n }\n function farAway(touch, other) {\n if (other.left == null) { return true }\n var dx = other.left - touch.left, dy = other.top - touch.top;\n return dx * dx + dy * dy > 20 * 20\n }\n on(d.scroller, \"touchstart\", function (e) {\n if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {\n d.input.ensurePolled();\n clearTimeout(touchFinished);\n var now = +new Date;\n d.activeTouch = {start: now, moved: false,\n prev: now - prevTouch.end <= 300 ? prevTouch : null};\n if (e.touches.length == 1) {\n d.activeTouch.left = e.touches[0].pageX;\n d.activeTouch.top = e.touches[0].pageY;\n }\n }\n });\n on(d.scroller, \"touchmove\", function () {\n if (d.activeTouch) { d.activeTouch.moved = true; }\n });\n on(d.scroller, \"touchend\", function (e) {\n var touch = d.activeTouch;\n if (touch && !eventInWidget(d, e) && touch.left != null &&\n !touch.moved && new Date - touch.start < 300) {\n var pos = cm.coordsChar(d.activeTouch, \"page\"), range;\n if (!touch.prev || farAway(touch, touch.prev)) // Single tap\n { range = new Range(pos, pos); }\n else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap\n { range = cm.findWordAt(pos); }\n else // Triple tap\n { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }\n cm.setSelection(range.anchor, range.head);\n cm.focus();\n e_preventDefault(e);\n }\n finishTouch();\n });\n on(d.scroller, \"touchcancel\", finishTouch);\n\n // Sync scrolling between fake scrollbars and real scrollable\n // area, ensure viewport is updated when scrolling.\n on(d.scroller, \"scroll\", function () {\n if (d.scroller.clientHeight) {\n updateScrollTop(cm, d.scroller.scrollTop);\n setScrollLeft(cm, d.scroller.scrollLeft, true);\n signal(cm, \"scroll\", cm);\n }\n });\n\n // Listen to wheel events in order to try and update the viewport on time.\n on(d.scroller, \"mousewheel\", function (e) { return onScrollWheel(cm, e); });\n on(d.scroller, \"DOMMouseScroll\", function (e) { return onScrollWheel(cm, e); });\n\n // Prevent wrapper from ever scrolling\n on(d.wrapper, \"scroll\", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });\n\n d.dragFunctions = {\n enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},\n over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},\n start: function (e) { return onDragStart(cm, e); },\n drop: operation(cm, onDrop),\n leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}\n };\n\n var inp = d.input.getField();\n on(inp, \"keyup\", function (e) { return onKeyUp.call(cm, e); });\n on(inp, \"keydown\", operation(cm, onKeyDown));\n on(inp, \"keypress\", operation(cm, onKeyPress));\n on(inp, \"focus\", function (e) { return onFocus(cm, e); });\n on(inp, \"blur\", function (e) { return onBlur(cm, e); });\n }\n\n var initHooks = [];\n CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };\n\n // Indent the given line. The how parameter can be \"smart\",\n // \"add\"/null, \"subtract\", or \"prev\". When aggressive is false\n // (typically set to true for forced single-line indents), empty\n // lines are not indented, and places where the mode returns Pass\n // are left alone.\n function indentLine(cm, n, how, aggressive) {\n var doc = cm.doc, state;\n if (how == null) { how = \"add\"; }\n if (how == \"smart\") {\n // Fall back to \"prev\" when the mode doesn't have an indentation\n // method.\n if (!doc.mode.indent) { how = \"prev\"; }\n else { state = getContextBefore(cm, n).state; }\n }\n\n var tabSize = cm.options.tabSize;\n var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);\n if (line.stateAfter) { line.stateAfter = null; }\n var curSpaceString = line.text.match(/^\\s*/)[0], indentation;\n if (!aggressive && !/\\S/.test(line.text)) {\n indentation = 0;\n how = \"not\";\n } else if (how == \"smart\") {\n indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);\n if (indentation == Pass || indentation > 150) {\n if (!aggressive) { return }\n how = \"prev\";\n }\n }\n if (how == \"prev\") {\n if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }\n else { indentation = 0; }\n } else if (how == \"add\") {\n indentation = curSpace + cm.options.indentUnit;\n } else if (how == \"subtract\") {\n indentation = curSpace - cm.options.indentUnit;\n } else if (typeof how == \"number\") {\n indentation = curSpace + how;\n }\n indentation = Math.max(0, indentation);\n\n var indentString = \"\", pos = 0;\n if (cm.options.indentWithTabs)\n { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += \"\\t\";} }\n if (pos < indentation) { indentString += spaceStr(indentation - pos); }\n\n if (indentString != curSpaceString) {\n replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), \"+input\");\n line.stateAfter = null;\n return true\n } else {\n // Ensure that, if the cursor was in the whitespace at the start\n // of the line, it is moved to the end of that space.\n for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {\n var range = doc.sel.ranges[i$1];\n if (range.head.line == n && range.head.ch < curSpaceString.length) {\n var pos$1 = Pos(n, curSpaceString.length);\n replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));\n break\n }\n }\n }\n }\n\n // This will be set to a {lineWise: bool, text: [string]} object, so\n // that, when pasting, we know what kind of selections the copied\n // text was made out of.\n var lastCopied = null;\n\n function setLastCopied(newLastCopied) {\n lastCopied = newLastCopied;\n }\n\n function applyTextInput(cm, inserted, deleted, sel, origin) {\n var doc = cm.doc;\n cm.display.shift = false;\n if (!sel) { sel = doc.sel; }\n\n var paste = cm.state.pasteIncoming || origin == \"paste\";\n var textLines = splitLinesAuto(inserted), multiPaste = null;\n // When pasting N lines into N selections, insert one line per selection\n if (paste && sel.ranges.length > 1) {\n if (lastCopied && lastCopied.text.join(\"\\n\") == inserted) {\n if (sel.ranges.length % lastCopied.text.length == 0) {\n multiPaste = [];\n for (var i = 0; i < lastCopied.text.length; i++)\n { multiPaste.push(doc.splitLines(lastCopied.text[i])); }\n }\n } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {\n multiPaste = map(textLines, function (l) { return [l]; });\n }\n }\n\n var updateInput;\n // Normal behavior is to insert the new text into every selection\n for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {\n var range$$1 = sel.ranges[i$1];\n var from = range$$1.from(), to = range$$1.to();\n if (range$$1.empty()) {\n if (deleted && deleted > 0) // Handle deletion\n { from = Pos(from.line, from.ch - deleted); }\n else if (cm.state.overwrite && !paste) // Handle overwrite\n { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }\n else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join(\"\\n\") == inserted)\n { from = to = Pos(from.line, 0); }\n }\n updateInput = cm.curOp.updateInput;\n var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,\n origin: origin || (paste ? \"paste\" : cm.state.cutIncoming ? \"cut\" : \"+input\")};\n makeChange(cm.doc, changeEvent);\n signalLater(cm, \"inputRead\", cm, changeEvent);\n }\n if (inserted && !paste)\n { triggerElectric(cm, inserted); }\n\n ensureCursorVisible(cm);\n cm.curOp.updateInput = updateInput;\n cm.curOp.typing = true;\n cm.state.pasteIncoming = cm.state.cutIncoming = false;\n }\n\n function handlePaste(e, cm) {\n var pasted = e.clipboardData && e.clipboardData.getData(\"Text\");\n if (pasted) {\n e.preventDefault();\n if (!cm.isReadOnly() && !cm.options.disableInput)\n { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, \"paste\"); }); }\n return true\n }\n }\n\n function triggerElectric(cm, inserted) {\n // When an 'electric' character is inserted, immediately trigger a reindent\n if (!cm.options.electricChars || !cm.options.smartIndent) { return }\n var sel = cm.doc.sel;\n\n for (var i = sel.ranges.length - 1; i >= 0; i--) {\n var range$$1 = sel.ranges[i];\n if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }\n var mode = cm.getModeAt(range$$1.head);\n var indented = false;\n if (mode.electricChars) {\n for (var j = 0; j < mode.electricChars.length; j++)\n { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {\n indented = indentLine(cm, range$$1.head.line, \"smart\");\n break\n } }\n } else if (mode.electricInput) {\n if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))\n { indented = indentLine(cm, range$$1.head.line, \"smart\"); }\n }\n if (indented) { signalLater(cm, \"electricInput\", cm, range$$1.head.line); }\n }\n }\n\n function copyableRanges(cm) {\n var text = [], ranges = [];\n for (var i = 0; i < cm.doc.sel.ranges.length; i++) {\n var line = cm.doc.sel.ranges[i].head.line;\n var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};\n ranges.push(lineRange);\n text.push(cm.getRange(lineRange.anchor, lineRange.head));\n }\n return {text: text, ranges: ranges}\n }\n\n function disableBrowserMagic(field, spellcheck) {\n field.setAttribute(\"autocorrect\", \"off\");\n field.setAttribute(\"autocapitalize\", \"off\");\n field.setAttribute(\"spellcheck\", !!spellcheck);\n }\n\n function hiddenTextarea() {\n var te = elt(\"textarea\", null, null, \"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none\");\n var div = elt(\"div\", [te], null, \"overflow: hidden; position: relative; width: 3px; height: 0px;\");\n // The textarea is kept positioned near the cursor to prevent the\n // fact that it'll be scrolled into view on input from scrolling\n // our fake cursor out of view. On webkit, when wrap=off, paste is\n // very slow. So make the area wide instead.\n if (webkit) { te.style.width = \"1000px\"; }\n else { te.setAttribute(\"wrap\", \"off\"); }\n // If border: 0; -- iOS fails to open keyboard (issue #1287)\n if (ios) { te.style.border = \"1px solid black\"; }\n disableBrowserMagic(te);\n return div\n }\n\n // The publicly visible API. Note that methodOp(f) means\n // 'wrap f in an operation, performed on its `this` parameter'.\n\n // This is not the complete set of editor methods. Most of the\n // methods defined on the Doc type are also injected into\n // CodeMirror.prototype, for backwards compatibility and\n // convenience.\n\n function addEditorMethods(CodeMirror) {\n var optionHandlers = CodeMirror.optionHandlers;\n\n var helpers = CodeMirror.helpers = {};\n\n CodeMirror.prototype = {\n constructor: CodeMirror,\n focus: function(){window.focus(); this.display.input.focus();},\n\n setOption: function(option, value) {\n var options = this.options, old = options[option];\n if (options[option] == value && option != \"mode\") { return }\n options[option] = value;\n if (optionHandlers.hasOwnProperty(option))\n { operation(this, optionHandlers[option])(this, value, old); }\n signal(this, \"optionChange\", this, option);\n },\n\n getOption: function(option) {return this.options[option]},\n getDoc: function() {return this.doc},\n\n addKeyMap: function(map$$1, bottom) {\n this.state.keyMaps[bottom ? \"push\" : \"unshift\"](getKeyMap(map$$1));\n },\n removeKeyMap: function(map$$1) {\n var maps = this.state.keyMaps;\n for (var i = 0; i < maps.length; ++i)\n { if (maps[i] == map$$1 || maps[i].name == map$$1) {\n maps.splice(i, 1);\n return true\n } }\n },\n\n addOverlay: methodOp(function(spec, options) {\n var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);\n if (mode.startState) { throw new Error(\"Overlays may not be stateful.\") }\n insertSorted(this.state.overlays,\n {mode: mode, modeSpec: spec, opaque: options && options.opaque,\n priority: (options && options.priority) || 0},\n function (overlay) { return overlay.priority; });\n this.state.modeGen++;\n regChange(this);\n }),\n removeOverlay: methodOp(function(spec) {\n var this$1 = this;\n\n var overlays = this.state.overlays;\n for (var i = 0; i < overlays.length; ++i) {\n var cur = overlays[i].modeSpec;\n if (cur == spec || typeof spec == \"string\" && cur.name == spec) {\n overlays.splice(i, 1);\n this$1.state.modeGen++;\n regChange(this$1);\n return\n }\n }\n }),\n\n indentLine: methodOp(function(n, dir, aggressive) {\n if (typeof dir != \"string\" && typeof dir != \"number\") {\n if (dir == null) { dir = this.options.smartIndent ? \"smart\" : \"prev\"; }\n else { dir = dir ? \"add\" : \"subtract\"; }\n }\n if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }\n }),\n indentSelection: methodOp(function(how) {\n var this$1 = this;\n\n var ranges = this.doc.sel.ranges, end = -1;\n for (var i = 0; i < ranges.length; i++) {\n var range$$1 = ranges[i];\n if (!range$$1.empty()) {\n var from = range$$1.from(), to = range$$1.to();\n var start = Math.max(end, from.line);\n end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;\n for (var j = start; j < end; ++j)\n { indentLine(this$1, j, how); }\n var newRanges = this$1.doc.sel.ranges;\n if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)\n { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }\n } else if (range$$1.head.line > end) {\n indentLine(this$1, range$$1.head.line, how, true);\n end = range$$1.head.line;\n if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }\n }\n }\n }),\n\n // Fetch the parser token for a given character. Useful for hacks\n // that want to inspect the mode state (say, for completion).\n getTokenAt: function(pos, precise) {\n return takeToken(this, pos, precise)\n },\n\n getLineTokens: function(line, precise) {\n return takeToken(this, Pos(line), precise, true)\n },\n\n getTokenTypeAt: function(pos) {\n pos = clipPos(this.doc, pos);\n var styles = getLineStyles(this, getLine(this.doc, pos.line));\n var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;\n var type;\n if (ch == 0) { type = styles[2]; }\n else { for (;;) {\n var mid = (before + after) >> 1;\n if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }\n else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }\n else { type = styles[mid * 2 + 2]; break }\n } }\n var cut = type ? type.indexOf(\"overlay \") : -1;\n return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)\n },\n\n getModeAt: function(pos) {\n var mode = this.doc.mode;\n if (!mode.innerMode) { return mode }\n return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode\n },\n\n getHelper: function(pos, type) {\n return this.getHelpers(pos, type)[0]\n },\n\n getHelpers: function(pos, type) {\n var this$1 = this;\n\n var found = [];\n if (!helpers.hasOwnProperty(type)) { return found }\n var help = helpers[type], mode = this.getModeAt(pos);\n if (typeof mode[type] == \"string\") {\n if (help[mode[type]]) { found.push(help[mode[type]]); }\n } else if (mode[type]) {\n for (var i = 0; i < mode[type].length; i++) {\n var val = help[mode[type][i]];\n if (val) { found.push(val); }\n }\n } else if (mode.helperType && help[mode.helperType]) {\n found.push(help[mode.helperType]);\n } else if (help[mode.name]) {\n found.push(help[mode.name]);\n }\n for (var i$1 = 0; i$1 < help._global.length; i$1++) {\n var cur = help._global[i$1];\n if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)\n { found.push(cur.val); }\n }\n return found\n },\n\n getStateAfter: function(line, precise) {\n var doc = this.doc;\n line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);\n return getContextBefore(this, line + 1, precise).state\n },\n\n cursorCoords: function(start, mode) {\n var pos, range$$1 = this.doc.sel.primary();\n if (start == null) { pos = range$$1.head; }\n else if (typeof start == \"object\") { pos = clipPos(this.doc, start); }\n else { pos = start ? range$$1.from() : range$$1.to(); }\n return cursorCoords(this, pos, mode || \"page\")\n },\n\n charCoords: function(pos, mode) {\n return charCoords(this, clipPos(this.doc, pos), mode || \"page\")\n },\n\n coordsChar: function(coords, mode) {\n coords = fromCoordSystem(this, coords, mode || \"page\");\n return coordsChar(this, coords.left, coords.top)\n },\n\n lineAtHeight: function(height, mode) {\n height = fromCoordSystem(this, {top: height, left: 0}, mode || \"page\").top;\n return lineAtHeight(this.doc, height + this.display.viewOffset)\n },\n heightAtLine: function(line, mode, includeWidgets) {\n var end = false, lineObj;\n if (typeof line == \"number\") {\n var last = this.doc.first + this.doc.size - 1;\n if (line < this.doc.first) { line = this.doc.first; }\n else if (line > last) { line = last; end = true; }\n lineObj = getLine(this.doc, line);\n } else {\n lineObj = line;\n }\n return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || \"page\", includeWidgets || end).top +\n (end ? this.doc.height - heightAtLine(lineObj) : 0)\n },\n\n defaultTextHeight: function() { return textHeight(this.display) },\n defaultCharWidth: function() { return charWidth(this.display) },\n\n getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},\n\n addWidget: function(pos, node, scroll, vert, horiz) {\n var display = this.display;\n pos = cursorCoords(this, clipPos(this.doc, pos));\n var top = pos.bottom, left = pos.left;\n node.style.position = \"absolute\";\n node.setAttribute(\"cm-ignore-events\", \"true\");\n this.display.input.setUneditable(node);\n display.sizer.appendChild(node);\n if (vert == \"over\") {\n top = pos.top;\n } else if (vert == \"above\" || vert == \"near\") {\n var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),\n hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);\n // Default to positioning above (if specified and possible); otherwise default to positioning below\n if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)\n { top = pos.top - node.offsetHeight; }\n else if (pos.bottom + node.offsetHeight <= vspace)\n { top = pos.bottom; }\n if (left + node.offsetWidth > hspace)\n { left = hspace - node.offsetWidth; }\n }\n node.style.top = top + \"px\";\n node.style.left = node.style.right = \"\";\n if (horiz == \"right\") {\n left = display.sizer.clientWidth - node.offsetWidth;\n node.style.right = \"0px\";\n } else {\n if (horiz == \"left\") { left = 0; }\n else if (horiz == \"middle\") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }\n node.style.left = left + \"px\";\n }\n if (scroll)\n { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }\n },\n\n triggerOnKeyDown: methodOp(onKeyDown),\n triggerOnKeyPress: methodOp(onKeyPress),\n triggerOnKeyUp: onKeyUp,\n triggerOnMouseDown: methodOp(onMouseDown),\n\n execCommand: function(cmd) {\n if (commands.hasOwnProperty(cmd))\n { return commands[cmd].call(null, this) }\n },\n\n triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),\n\n findPosH: function(from, amount, unit, visually) {\n var this$1 = this;\n\n var dir = 1;\n if (amount < 0) { dir = -1; amount = -amount; }\n var cur = clipPos(this.doc, from);\n for (var i = 0; i < amount; ++i) {\n cur = findPosH(this$1.doc, cur, dir, unit, visually);\n if (cur.hitSide) { break }\n }\n return cur\n },\n\n moveH: methodOp(function(dir, unit) {\n var this$1 = this;\n\n this.extendSelectionsBy(function (range$$1) {\n if (this$1.display.shift || this$1.doc.extend || range$$1.empty())\n { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }\n else\n { return dir < 0 ? range$$1.from() : range$$1.to() }\n }, sel_move);\n }),\n\n deleteH: methodOp(function(dir, unit) {\n var sel = this.doc.sel, doc = this.doc;\n if (sel.somethingSelected())\n { doc.replaceSelection(\"\", null, \"+delete\"); }\n else\n { deleteNearSelection(this, function (range$$1) {\n var other = findPosH(doc, range$$1.head, dir, unit, false);\n return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}\n }); }\n }),\n\n findPosV: function(from, amount, unit, goalColumn) {\n var this$1 = this;\n\n var dir = 1, x = goalColumn;\n if (amount < 0) { dir = -1; amount = -amount; }\n var cur = clipPos(this.doc, from);\n for (var i = 0; i < amount; ++i) {\n var coords = cursorCoords(this$1, cur, \"div\");\n if (x == null) { x = coords.left; }\n else { coords.left = x; }\n cur = findPosV(this$1, coords, dir, unit);\n if (cur.hitSide) { break }\n }\n return cur\n },\n\n moveV: methodOp(function(dir, unit) {\n var this$1 = this;\n\n var doc = this.doc, goals = [];\n var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();\n doc.extendSelectionsBy(function (range$$1) {\n if (collapse)\n { return dir < 0 ? range$$1.from() : range$$1.to() }\n var headPos = cursorCoords(this$1, range$$1.head, \"div\");\n if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }\n goals.push(headPos.left);\n var pos = findPosV(this$1, headPos, dir, unit);\n if (unit == \"page\" && range$$1 == doc.sel.primary())\n { addToScrollTop(this$1, charCoords(this$1, pos, \"div\").top - headPos.top); }\n return pos\n }, sel_move);\n if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)\n { doc.sel.ranges[i].goalColumn = goals[i]; } }\n }),\n\n // Find the word at the given position (as returned by coordsChar).\n findWordAt: function(pos) {\n var doc = this.doc, line = getLine(doc, pos.line).text;\n var start = pos.ch, end = pos.ch;\n if (line) {\n var helper = this.getHelper(pos, \"wordChars\");\n if ((pos.sticky == \"before\" || end == line.length) && start) { --start; } else { ++end; }\n var startChar = line.charAt(start);\n var check = isWordChar(startChar, helper)\n ? function (ch) { return isWordChar(ch, helper); }\n : /\\s/.test(startChar) ? function (ch) { return /\\s/.test(ch); }\n : function (ch) { return (!/\\s/.test(ch) && !isWordChar(ch)); };\n while (start > 0 && check(line.charAt(start - 1))) { --start; }\n while (end < line.length && check(line.charAt(end))) { ++end; }\n }\n return new Range(Pos(pos.line, start), Pos(pos.line, end))\n },\n\n toggleOverwrite: function(value) {\n if (value != null && value == this.state.overwrite) { return }\n if (this.state.overwrite = !this.state.overwrite)\n { addClass(this.display.cursorDiv, \"CodeMirror-overwrite\"); }\n else\n { rmClass(this.display.cursorDiv, \"CodeMirror-overwrite\"); }\n\n signal(this, \"overwriteToggle\", this, this.state.overwrite);\n },\n hasFocus: function() { return this.display.input.getField() == activeElt() },\n isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },\n\n scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),\n getScrollInfo: function() {\n var scroller = this.display.scroller;\n return {left: scroller.scrollLeft, top: scroller.scrollTop,\n height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,\n width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,\n clientHeight: displayHeight(this), clientWidth: displayWidth(this)}\n },\n\n scrollIntoView: methodOp(function(range$$1, margin) {\n if (range$$1 == null) {\n range$$1 = {from: this.doc.sel.primary().head, to: null};\n if (margin == null) { margin = this.options.cursorScrollMargin; }\n } else if (typeof range$$1 == \"number\") {\n range$$1 = {from: Pos(range$$1, 0), to: null};\n } else if (range$$1.from == null) {\n range$$1 = {from: range$$1, to: null};\n }\n if (!range$$1.to) { range$$1.to = range$$1.from; }\n range$$1.margin = margin || 0;\n\n if (range$$1.from.line != null) {\n scrollToRange(this, range$$1);\n } else {\n scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);\n }\n }),\n\n setSize: methodOp(function(width, height) {\n var this$1 = this;\n\n var interpret = function (val) { return typeof val == \"number\" || /^\\d+$/.test(String(val)) ? val + \"px\" : val; };\n if (width != null) { this.display.wrapper.style.width = interpret(width); }\n if (height != null) { this.display.wrapper.style.height = interpret(height); }\n if (this.options.lineWrapping) { clearLineMeasurementCache(this); }\n var lineNo$$1 = this.display.viewFrom;\n this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {\n if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)\n { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, \"widget\"); break } } }\n ++lineNo$$1;\n });\n this.curOp.forceUpdate = true;\n signal(this, \"refresh\", this);\n }),\n\n operation: function(f){return runInOp(this, f)},\n startOperation: function(){return startOperation(this)},\n endOperation: function(){return endOperation(this)},\n\n refresh: methodOp(function() {\n var oldHeight = this.display.cachedTextHeight;\n regChange(this);\n this.curOp.forceUpdate = true;\n clearCaches(this);\n scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);\n updateGutterSpace(this);\n if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)\n { estimateLineHeights(this); }\n signal(this, \"refresh\", this);\n }),\n\n swapDoc: methodOp(function(doc) {\n var old = this.doc;\n old.cm = null;\n attachDoc(this, doc);\n clearCaches(this);\n this.display.input.reset();\n scrollToCoords(this, doc.scrollLeft, doc.scrollTop);\n this.curOp.forceScroll = true;\n signalLater(this, \"swapDoc\", this, old);\n return old\n }),\n\n phrase: function(phraseText) {\n var phrases = this.options.phrases;\n return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText\n },\n\n getInputField: function(){return this.display.input.getField()},\n getWrapperElement: function(){return this.display.wrapper},\n getScrollerElement: function(){return this.display.scroller},\n getGutterElement: function(){return this.display.gutters}\n };\n eventMixin(CodeMirror);\n\n CodeMirror.registerHelper = function(type, name, value) {\n if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }\n helpers[type][name] = value;\n };\n CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {\n CodeMirror.registerHelper(type, name, value);\n helpers[type]._global.push({pred: predicate, val: value});\n };\n }\n\n // Used for horizontal relative motion. Dir is -1 or 1 (left or\n // right), unit can be \"char\", \"column\" (like char, but doesn't\n // cross line boundaries), \"word\" (across next word), or \"group\" (to\n // the start of next group of word or non-word-non-whitespace\n // chars). The visually param controls whether, in right-to-left\n // text, direction 1 means to move towards the next index in the\n // string, or towards the character to the right of the current\n // position. The resulting position will have a hitSide=true\n // property if it reached the end of the document.\n function findPosH(doc, pos, dir, unit, visually) {\n var oldPos = pos;\n var origDir = dir;\n var lineObj = getLine(doc, pos.line);\n function findNextLine() {\n var l = pos.line + dir;\n if (l < doc.first || l >= doc.first + doc.size) { return false }\n pos = new Pos(l, pos.ch, pos.sticky);\n return lineObj = getLine(doc, l)\n }\n function moveOnce(boundToLine) {\n var next;\n if (visually) {\n next = moveVisually(doc.cm, lineObj, pos, dir);\n } else {\n next = moveLogically(lineObj, pos, dir);\n }\n if (next == null) {\n if (!boundToLine && findNextLine())\n { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }\n else\n { return false }\n } else {\n pos = next;\n }\n return true\n }\n\n if (unit == \"char\") {\n moveOnce();\n } else if (unit == \"column\") {\n moveOnce(true);\n } else if (unit == \"word\" || unit == \"group\") {\n var sawType = null, group = unit == \"group\";\n var helper = doc.cm && doc.cm.getHelper(pos, \"wordChars\");\n for (var first = true;; first = false) {\n if (dir < 0 && !moveOnce(!first)) { break }\n var cur = lineObj.text.charAt(pos.ch) || \"\\n\";\n var type = isWordChar(cur, helper) ? \"w\"\n : group && cur == \"\\n\" ? \"n\"\n : !group || /\\s/.test(cur) ? null\n : \"p\";\n if (group && !first && !type) { type = \"s\"; }\n if (sawType && sawType != type) {\n if (dir < 0) {dir = 1; moveOnce(); pos.sticky = \"after\";}\n break\n }\n\n if (type) { sawType = type; }\n if (dir > 0 && !moveOnce(!first)) { break }\n }\n }\n var result = skipAtomic(doc, pos, oldPos, origDir, true);\n if (equalCursorPos(oldPos, result)) { result.hitSide = true; }\n return result\n }\n\n // For relative vertical movement. Dir may be -1 or 1. Unit can be\n // \"page\" or \"line\". The resulting position will have a hitSide=true\n // property if it reached the end of the document.\n function findPosV(cm, pos, dir, unit) {\n var doc = cm.doc, x = pos.left, y;\n if (unit == \"page\") {\n var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);\n var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);\n y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;\n\n } else if (unit == \"line\") {\n y = dir > 0 ? pos.bottom + 3 : pos.top - 3;\n }\n var target;\n for (;;) {\n target = coordsChar(cm, x, y);\n if (!target.outside) { break }\n if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }\n y += dir * 5;\n }\n return target\n }\n\n // CONTENTEDITABLE INPUT STYLE\n\n var ContentEditableInput = function(cm) {\n this.cm = cm;\n this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;\n this.polling = new Delayed();\n this.composing = null;\n this.gracePeriod = false;\n this.readDOMTimeout = null;\n };\n\n ContentEditableInput.prototype.init = function (display) {\n var this$1 = this;\n\n var input = this, cm = input.cm;\n var div = input.div = display.lineDiv;\n disableBrowserMagic(div, cm.options.spellcheck);\n\n on(div, \"paste\", function (e) {\n if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }\n // IE doesn't fire input events, so we schedule a read for the pasted content in this way\n if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }\n });\n\n on(div, \"compositionstart\", function (e) {\n this$1.composing = {data: e.data, done: false};\n });\n on(div, \"compositionupdate\", function (e) {\n if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }\n });\n on(div, \"compositionend\", function (e) {\n if (this$1.composing) {\n if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }\n this$1.composing.done = true;\n }\n });\n\n on(div, \"touchstart\", function () { return input.forceCompositionEnd(); });\n\n on(div, \"input\", function () {\n if (!this$1.composing) { this$1.readFromDOMSoon(); }\n });\n\n function onCopyCut(e) {\n if (signalDOMEvent(cm, e)) { return }\n if (cm.somethingSelected()) {\n setLastCopied({lineWise: false, text: cm.getSelections()});\n if (e.type == \"cut\") { cm.replaceSelection(\"\", null, \"cut\"); }\n } else if (!cm.options.lineWiseCopyCut) {\n return\n } else {\n var ranges = copyableRanges(cm);\n setLastCopied({lineWise: true, text: ranges.text});\n if (e.type == \"cut\") {\n cm.operation(function () {\n cm.setSelections(ranges.ranges, 0, sel_dontScroll);\n cm.replaceSelection(\"\", null, \"cut\");\n });\n }\n }\n if (e.clipboardData) {\n e.clipboardData.clearData();\n var content = lastCopied.text.join(\"\\n\");\n // iOS exposes the clipboard API, but seems to discard content inserted into it\n e.clipboardData.setData(\"Text\", content);\n if (e.clipboardData.getData(\"Text\") == content) {\n e.preventDefault();\n return\n }\n }\n // Old-fashioned briefly-focus-a-textarea hack\n var kludge = hiddenTextarea(), te = kludge.firstChild;\n cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);\n te.value = lastCopied.text.join(\"\\n\");\n var hadFocus = document.activeElement;\n selectInput(te);\n setTimeout(function () {\n cm.display.lineSpace.removeChild(kludge);\n hadFocus.focus();\n if (hadFocus == div) { input.showPrimarySelection(); }\n }, 50);\n }\n on(div, \"copy\", onCopyCut);\n on(div, \"cut\", onCopyCut);\n };\n\n ContentEditableInput.prototype.prepareSelection = function () {\n var result = prepareSelection(this.cm, false);\n result.focus = this.cm.state.focused;\n return result\n };\n\n ContentEditableInput.prototype.showSelection = function (info, takeFocus) {\n if (!info || !this.cm.display.view.length) { return }\n if (info.focus || takeFocus) { this.showPrimarySelection(); }\n this.showMultipleSelections(info);\n };\n\n ContentEditableInput.prototype.getSelection = function () {\n return this.cm.display.wrapper.ownerDocument.getSelection()\n };\n\n ContentEditableInput.prototype.showPrimarySelection = function () {\n var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();\n var from = prim.from(), to = prim.to();\n\n if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {\n sel.removeAllRanges();\n return\n }\n\n var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);\n var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);\n if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&\n cmp(minPos(curAnchor, curFocus), from) == 0 &&\n cmp(maxPos(curAnchor, curFocus), to) == 0)\n { return }\n\n var view = cm.display.view;\n var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||\n {node: view[0].measure.map[2], offset: 0};\n var end = to.line < cm.display.viewTo && posToDOM(cm, to);\n if (!end) {\n var measure = view[view.length - 1].measure;\n var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;\n end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};\n }\n\n if (!start || !end) {\n sel.removeAllRanges();\n return\n }\n\n var old = sel.rangeCount && sel.getRangeAt(0), rng;\n try { rng = range(start.node, start.offset, end.offset, end.node); }\n catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible\n if (rng) {\n if (!gecko && cm.state.focused) {\n sel.collapse(start.node, start.offset);\n if (!rng.collapsed) {\n sel.removeAllRanges();\n sel.addRange(rng);\n }\n } else {\n sel.removeAllRanges();\n sel.addRange(rng);\n }\n if (old && sel.anchorNode == null) { sel.addRange(old); }\n else if (gecko) { this.startGracePeriod(); }\n }\n this.rememberSelection();\n };\n\n ContentEditableInput.prototype.startGracePeriod = function () {\n var this$1 = this;\n\n clearTimeout(this.gracePeriod);\n this.gracePeriod = setTimeout(function () {\n this$1.gracePeriod = false;\n if (this$1.selectionChanged())\n { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }\n }, 20);\n };\n\n ContentEditableInput.prototype.showMultipleSelections = function (info) {\n removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);\n removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);\n };\n\n ContentEditableInput.prototype.rememberSelection = function () {\n var sel = this.getSelection();\n this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;\n this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;\n };\n\n ContentEditableInput.prototype.selectionInEditor = function () {\n var sel = this.getSelection();\n if (!sel.rangeCount) { return false }\n var node = sel.getRangeAt(0).commonAncestorContainer;\n return contains(this.div, node)\n };\n\n ContentEditableInput.prototype.focus = function () {\n if (this.cm.options.readOnly != \"nocursor\") {\n if (!this.selectionInEditor())\n { this.showSelection(this.prepareSelection(), true); }\n this.div.focus();\n }\n };\n ContentEditableInput.prototype.blur = function () { this.div.blur(); };\n ContentEditableInput.prototype.getField = function () { return this.div };\n\n ContentEditableInput.prototype.supportsTouch = function () { return true };\n\n ContentEditableInput.prototype.receivedFocus = function () {\n var input = this;\n if (this.selectionInEditor())\n { this.pollSelection(); }\n else\n { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }\n\n function poll() {\n if (input.cm.state.focused) {\n input.pollSelection();\n input.polling.set(input.cm.options.pollInterval, poll);\n }\n }\n this.polling.set(this.cm.options.pollInterval, poll);\n };\n\n ContentEditableInput.prototype.selectionChanged = function () {\n var sel = this.getSelection();\n return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||\n sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset\n };\n\n ContentEditableInput.prototype.pollSelection = function () {\n if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }\n var sel = this.getSelection(), cm = this.cm;\n // On Android Chrome (version 56, at least), backspacing into an\n // uneditable block element will put the cursor in that element,\n // and then, because it's not editable, hide the virtual keyboard.\n // Because Android doesn't allow us to actually detect backspace\n // presses in a sane way, this code checks for when that happens\n // and simulates a backspace press in this case.\n if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {\n this.cm.triggerOnKeyDown({type: \"keydown\", keyCode: 8, preventDefault: Math.abs});\n this.blur();\n this.focus();\n return\n }\n if (this.composing) { return }\n this.rememberSelection();\n var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);\n var head = domToPos(cm, sel.focusNode, sel.focusOffset);\n if (anchor && head) { runInOp(cm, function () {\n setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);\n if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }\n }); }\n };\n\n ContentEditableInput.prototype.pollContent = function () {\n if (this.readDOMTimeout != null) {\n clearTimeout(this.readDOMTimeout);\n this.readDOMTimeout = null;\n }\n\n var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();\n var from = sel.from(), to = sel.to();\n if (from.ch == 0 && from.line > cm.firstLine())\n { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }\n if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())\n { to = Pos(to.line + 1, 0); }\n if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }\n\n var fromIndex, fromLine, fromNode;\n if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {\n fromLine = lineNo(display.view[0].line);\n fromNode = display.view[0].node;\n } else {\n fromLine = lineNo(display.view[fromIndex].line);\n fromNode = display.view[fromIndex - 1].node.nextSibling;\n }\n var toIndex = findViewIndex(cm, to.line);\n var toLine, toNode;\n if (toIndex == display.view.length - 1) {\n toLine = display.viewTo - 1;\n toNode = display.lineDiv.lastChild;\n } else {\n toLine = lineNo(display.view[toIndex + 1].line) - 1;\n toNode = display.view[toIndex + 1].node.previousSibling;\n }\n\n if (!fromNode) { return false }\n var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));\n var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));\n while (newText.length > 1 && oldText.length > 1) {\n if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }\n else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }\n else { break }\n }\n\n var cutFront = 0, cutEnd = 0;\n var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);\n while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))\n { ++cutFront; }\n var newBot = lst(newText), oldBot = lst(oldText);\n var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),\n oldBot.length - (oldText.length == 1 ? cutFront : 0));\n while (cutEnd < maxCutEnd &&\n newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))\n { ++cutEnd; }\n // Try to move start of change to start of selection if ambiguous\n if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {\n while (cutFront && cutFront > from.ch &&\n newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {\n cutFront--;\n cutEnd++;\n }\n }\n\n newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\\u200b+/, \"\");\n newText[0] = newText[0].slice(cutFront).replace(/\\u200b+$/, \"\");\n\n var chFrom = Pos(fromLine, cutFront);\n var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);\n if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {\n replaceRange(cm.doc, newText, chFrom, chTo, \"+input\");\n return true\n }\n };\n\n ContentEditableInput.prototype.ensurePolled = function () {\n this.forceCompositionEnd();\n };\n ContentEditableInput.prototype.reset = function () {\n this.forceCompositionEnd();\n };\n ContentEditableInput.prototype.forceCompositionEnd = function () {\n if (!this.composing) { return }\n clearTimeout(this.readDOMTimeout);\n this.composing = null;\n this.updateFromDOM();\n this.div.blur();\n this.div.focus();\n };\n ContentEditableInput.prototype.readFromDOMSoon = function () {\n var this$1 = this;\n\n if (this.readDOMTimeout != null) { return }\n this.readDOMTimeout = setTimeout(function () {\n this$1.readDOMTimeout = null;\n if (this$1.composing) {\n if (this$1.composing.done) { this$1.composing = null; }\n else { return }\n }\n this$1.updateFromDOM();\n }, 80);\n };\n\n ContentEditableInput.prototype.updateFromDOM = function () {\n var this$1 = this;\n\n if (this.cm.isReadOnly() || !this.pollContent())\n { runInOp(this.cm, function () { return regChange(this$1.cm); }); }\n };\n\n ContentEditableInput.prototype.setUneditable = function (node) {\n node.contentEditable = \"false\";\n };\n\n ContentEditableInput.prototype.onKeyPress = function (e) {\n if (e.charCode == 0 || this.composing) { return }\n e.preventDefault();\n if (!this.cm.isReadOnly())\n { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }\n };\n\n ContentEditableInput.prototype.readOnlyChanged = function (val) {\n this.div.contentEditable = String(val != \"nocursor\");\n };\n\n ContentEditableInput.prototype.onContextMenu = function () {};\n ContentEditableInput.prototype.resetPosition = function () {};\n\n ContentEditableInput.prototype.needsContentAttribute = true;\n\n function posToDOM(cm, pos) {\n var view = findViewForLine(cm, pos.line);\n if (!view || view.hidden) { return null }\n var line = getLine(cm.doc, pos.line);\n var info = mapFromLineView(view, line, pos.line);\n\n var order = getOrder(line, cm.doc.direction), side = \"left\";\n if (order) {\n var partPos = getBidiPartAt(order, pos.ch);\n side = partPos % 2 ? \"right\" : \"left\";\n }\n var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);\n result.offset = result.collapse == \"right\" ? result.end : result.start;\n return result\n }\n\n function isInGutter(node) {\n for (var scan = node; scan; scan = scan.parentNode)\n { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }\n return false\n }\n\n function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }\n\n function domTextBetween(cm, from, to, fromLine, toLine) {\n var text = \"\", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;\n function recognizeMarker(id) { return function (marker) { return marker.id == id; } }\n function close() {\n if (closing) {\n text += lineSep;\n if (extraLinebreak) { text += lineSep; }\n closing = extraLinebreak = false;\n }\n }\n function addText(str) {\n if (str) {\n close();\n text += str;\n }\n }\n function walk(node) {\n if (node.nodeType == 1) {\n var cmText = node.getAttribute(\"cm-text\");\n if (cmText) {\n addText(cmText);\n return\n }\n var markerID = node.getAttribute(\"cm-marker\"), range$$1;\n if (markerID) {\n var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));\n if (found.length && (range$$1 = found[0].find(0)))\n { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }\n return\n }\n if (node.getAttribute(\"contenteditable\") == \"false\") { return }\n var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);\n if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }\n\n if (isBlock) { close(); }\n for (var i = 0; i < node.childNodes.length; i++)\n { walk(node.childNodes[i]); }\n\n if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }\n if (isBlock) { closing = true; }\n } else if (node.nodeType == 3) {\n addText(node.nodeValue.replace(/\\u200b/g, \"\").replace(/\\u00a0/g, \" \"));\n }\n }\n for (;;) {\n walk(from);\n if (from == to) { break }\n from = from.nextSibling;\n extraLinebreak = false;\n }\n return text\n }\n\n function domToPos(cm, node, offset) {\n var lineNode;\n if (node == cm.display.lineDiv) {\n lineNode = cm.display.lineDiv.childNodes[offset];\n if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }\n node = null; offset = 0;\n } else {\n for (lineNode = node;; lineNode = lineNode.parentNode) {\n if (!lineNode || lineNode == cm.display.lineDiv) { return null }\n if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }\n }\n }\n for (var i = 0; i < cm.display.view.length; i++) {\n var lineView = cm.display.view[i];\n if (lineView.node == lineNode)\n { return locateNodeInLineView(lineView, node, offset) }\n }\n }\n\n function locateNodeInLineView(lineView, node, offset) {\n var wrapper = lineView.text.firstChild, bad = false;\n if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }\n if (node == wrapper) {\n bad = true;\n node = wrapper.childNodes[offset];\n offset = 0;\n if (!node) {\n var line = lineView.rest ? lst(lineView.rest) : lineView.line;\n return badPos(Pos(lineNo(line), line.text.length), bad)\n }\n }\n\n var textNode = node.nodeType == 3 ? node : null, topNode = node;\n if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {\n textNode = node.firstChild;\n if (offset) { offset = textNode.nodeValue.length; }\n }\n while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }\n var measure = lineView.measure, maps = measure.maps;\n\n function find(textNode, topNode, offset) {\n for (var i = -1; i < (maps ? maps.length : 0); i++) {\n var map$$1 = i < 0 ? measure.map : maps[i];\n for (var j = 0; j < map$$1.length; j += 3) {\n var curNode = map$$1[j + 2];\n if (curNode == textNode || curNode == topNode) {\n var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);\n var ch = map$$1[j] + offset;\n if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }\n return Pos(line, ch)\n }\n }\n }\n }\n var found = find(textNode, topNode, offset);\n if (found) { return badPos(found, bad) }\n\n // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems\n for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {\n found = find(after, after.firstChild, 0);\n if (found)\n { return badPos(Pos(found.line, found.ch - dist), bad) }\n else\n { dist += after.textContent.length; }\n }\n for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {\n found = find(before, before.firstChild, -1);\n if (found)\n { return badPos(Pos(found.line, found.ch + dist$1), bad) }\n else\n { dist$1 += before.textContent.length; }\n }\n }\n\n // TEXTAREA INPUT STYLE\n\n var TextareaInput = function(cm) {\n this.cm = cm;\n // See input.poll and input.reset\n this.prevInput = \"\";\n\n // Flag that indicates whether we expect input to appear real soon\n // now (after some event like 'keypress' or 'input') and are\n // polling intensively.\n this.pollingFast = false;\n // Self-resetting timeout for the poller\n this.polling = new Delayed();\n // Used to work around IE issue with selection being forgotten when focus moves away from textarea\n this.hasSelection = false;\n this.composing = null;\n };\n\n TextareaInput.prototype.init = function (display) {\n var this$1 = this;\n\n var input = this, cm = this.cm;\n this.createField(display);\n var te = this.textarea;\n\n display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);\n\n // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)\n if (ios) { te.style.width = \"0px\"; }\n\n on(te, \"input\", function () {\n if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }\n input.poll();\n });\n\n on(te, \"paste\", function (e) {\n if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }\n\n cm.state.pasteIncoming = true;\n input.fastPoll();\n });\n\n function prepareCopyCut(e) {\n if (signalDOMEvent(cm, e)) { return }\n if (cm.somethingSelected()) {\n setLastCopied({lineWise: false, text: cm.getSelections()});\n } else if (!cm.options.lineWiseCopyCut) {\n return\n } else {\n var ranges = copyableRanges(cm);\n setLastCopied({lineWise: true, text: ranges.text});\n if (e.type == \"cut\") {\n cm.setSelections(ranges.ranges, null, sel_dontScroll);\n } else {\n input.prevInput = \"\";\n te.value = ranges.text.join(\"\\n\");\n selectInput(te);\n }\n }\n if (e.type == \"cut\") { cm.state.cutIncoming = true; }\n }\n on(te, \"cut\", prepareCopyCut);\n on(te, \"copy\", prepareCopyCut);\n\n on(display.scroller, \"paste\", function (e) {\n if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }\n cm.state.pasteIncoming = true;\n input.focus();\n });\n\n // Prevent normal selection in the editor (we handle our own)\n on(display.lineSpace, \"selectstart\", function (e) {\n if (!eventInWidget(display, e)) { e_preventDefault(e); }\n });\n\n on(te, \"compositionstart\", function () {\n var start = cm.getCursor(\"from\");\n if (input.composing) { input.composing.range.clear(); }\n input.composing = {\n start: start,\n range: cm.markText(start, cm.getCursor(\"to\"), {className: \"CodeMirror-composing\"})\n };\n });\n on(te, \"compositionend\", function () {\n if (input.composing) {\n input.poll();\n input.composing.range.clear();\n input.composing = null;\n }\n });\n };\n\n TextareaInput.prototype.createField = function (_display) {\n // Wraps and hides input textarea\n this.wrapper = hiddenTextarea();\n // The semihidden textarea that is focused when the editor is\n // focused, and receives input.\n this.textarea = this.wrapper.firstChild;\n };\n\n TextareaInput.prototype.prepareSelection = function () {\n // Redraw the selection and/or cursor\n var cm = this.cm, display = cm.display, doc = cm.doc;\n var result = prepareSelection(cm);\n\n // Move the hidden textarea near the cursor to prevent scrolling artifacts\n if (cm.options.moveInputWithCursor) {\n var headPos = cursorCoords(cm, doc.sel.primary().head, \"div\");\n var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();\n result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,\n headPos.top + lineOff.top - wrapOff.top));\n result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,\n headPos.left + lineOff.left - wrapOff.left));\n }\n\n return result\n };\n\n TextareaInput.prototype.showSelection = function (drawn) {\n var cm = this.cm, display = cm.display;\n removeChildrenAndAdd(display.cursorDiv, drawn.cursors);\n removeChildrenAndAdd(display.selectionDiv, drawn.selection);\n if (drawn.teTop != null) {\n this.wrapper.style.top = drawn.teTop + \"px\";\n this.wrapper.style.left = drawn.teLeft + \"px\";\n }\n };\n\n // Reset the input to correspond to the selection (or to be empty,\n // when not typing and nothing is selected)\n TextareaInput.prototype.reset = function (typing) {\n if (this.contextMenuPending || this.composing) { return }\n var cm = this.cm;\n if (cm.somethingSelected()) {\n this.prevInput = \"\";\n var content = cm.getSelection();\n this.textarea.value = content;\n if (cm.state.focused) { selectInput(this.textarea); }\n if (ie && ie_version >= 9) { this.hasSelection = content; }\n } else if (!typing) {\n this.prevInput = this.textarea.value = \"\";\n if (ie && ie_version >= 9) { this.hasSelection = null; }\n }\n };\n\n TextareaInput.prototype.getField = function () { return this.textarea };\n\n TextareaInput.prototype.supportsTouch = function () { return false };\n\n TextareaInput.prototype.focus = function () {\n if (this.cm.options.readOnly != \"nocursor\" && (!mobile || activeElt() != this.textarea)) {\n try { this.textarea.focus(); }\n catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM\n }\n };\n\n TextareaInput.prototype.blur = function () { this.textarea.blur(); };\n\n TextareaInput.prototype.resetPosition = function () {\n this.wrapper.style.top = this.wrapper.style.left = 0;\n };\n\n TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };\n\n // Poll for input changes, using the normal rate of polling. This\n // runs as long as the editor is focused.\n TextareaInput.prototype.slowPoll = function () {\n var this$1 = this;\n\n if (this.pollingFast) { return }\n this.polling.set(this.cm.options.pollInterval, function () {\n this$1.poll();\n if (this$1.cm.state.focused) { this$1.slowPoll(); }\n });\n };\n\n // When an event has just come in that is likely to add or change\n // something in the input textarea, we poll faster, to ensure that\n // the change appears on the screen quickly.\n TextareaInput.prototype.fastPoll = function () {\n var missed = false, input = this;\n input.pollingFast = true;\n function p() {\n var changed = input.poll();\n if (!changed && !missed) {missed = true; input.polling.set(60, p);}\n else {input.pollingFast = false; input.slowPoll();}\n }\n input.polling.set(20, p);\n };\n\n // Read input from the textarea, and update the document to match.\n // When something is selected, it is present in the textarea, and\n // selected (unless it is huge, in which case a placeholder is\n // used). When nothing is selected, the cursor sits after previously\n // seen text (can be empty), which is stored in prevInput (we must\n // not reset the textarea when typing, because that breaks IME).\n TextareaInput.prototype.poll = function () {\n var this$1 = this;\n\n var cm = this.cm, input = this.textarea, prevInput = this.prevInput;\n // Since this is called a *lot*, try to bail out as cheaply as\n // possible when it is clear that nothing happened. hasSelection\n // will be the case when there is a lot of text in the textarea,\n // in which case reading its value would be expensive.\n if (this.contextMenuPending || !cm.state.focused ||\n (hasSelection(input) && !prevInput && !this.composing) ||\n cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)\n { return false }\n\n var text = input.value;\n // If nothing changed, bail.\n if (text == prevInput && !cm.somethingSelected()) { return false }\n // Work around nonsensical selection resetting in IE9/10, and\n // inexplicable appearance of private area unicode characters on\n // some key combos in Mac (#2689).\n if (ie && ie_version >= 9 && this.hasSelection === text ||\n mac && /[\\uf700-\\uf7ff]/.test(text)) {\n cm.display.input.reset();\n return false\n }\n\n if (cm.doc.sel == cm.display.selForContextMenu) {\n var first = text.charCodeAt(0);\n if (first == 0x200b && !prevInput) { prevInput = \"\\u200b\"; }\n if (first == 0x21da) { this.reset(); return this.cm.execCommand(\"undo\") }\n }\n // Find the part of the input that is actually new\n var same = 0, l = Math.min(prevInput.length, text.length);\n while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }\n\n runInOp(cm, function () {\n applyTextInput(cm, text.slice(same), prevInput.length - same,\n null, this$1.composing ? \"*compose\" : null);\n\n // Don't leave long text in the textarea, since it makes further polling slow\n if (text.length > 1000 || text.indexOf(\"\\n\") > -1) { input.value = this$1.prevInput = \"\"; }\n else { this$1.prevInput = text; }\n\n if (this$1.composing) {\n this$1.composing.range.clear();\n this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor(\"to\"),\n {className: \"CodeMirror-composing\"});\n }\n });\n return true\n };\n\n TextareaInput.prototype.ensurePolled = function () {\n if (this.pollingFast && this.poll()) { this.pollingFast = false; }\n };\n\n TextareaInput.prototype.onKeyPress = function () {\n if (ie && ie_version >= 9) { this.hasSelection = null; }\n this.fastPoll();\n };\n\n TextareaInput.prototype.onContextMenu = function (e) {\n var input = this, cm = input.cm, display = cm.display, te = input.textarea;\n var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;\n if (!pos || presto) { return } // Opera is difficult.\n\n // Reset the current text selection only if the click is done outside of the selection\n // and 'resetSelectionOnContextMenu' option is true.\n var reset = cm.options.resetSelectionOnContextMenu;\n if (reset && cm.doc.sel.contains(pos) == -1)\n { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }\n\n var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;\n input.wrapper.style.cssText = \"position: absolute\";\n var wrapperBox = input.wrapper.getBoundingClientRect();\n te.style.cssText = \"position: absolute; width: 30px; height: 30px;\\n top: \" + (e.clientY - wrapperBox.top - 5) + \"px; left: \" + (e.clientX - wrapperBox.left - 5) + \"px;\\n z-index: 1000; background: \" + (ie ? \"rgba(255, 255, 255, .05)\" : \"transparent\") + \";\\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);\";\n var oldScrollY;\n if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)\n display.input.focus();\n if (webkit) { window.scrollTo(null, oldScrollY); }\n display.input.reset();\n // Adds \"Select all\" to context menu in FF\n if (!cm.somethingSelected()) { te.value = input.prevInput = \" \"; }\n input.contextMenuPending = true;\n display.selForContextMenu = cm.doc.sel;\n clearTimeout(display.detectingSelectAll);\n\n // Select-all will be greyed out if there's nothing to select, so\n // this adds a zero-width space so that we can later check whether\n // it got selected.\n function prepareSelectAllHack() {\n if (te.selectionStart != null) {\n var selected = cm.somethingSelected();\n var extval = \"\\u200b\" + (selected ? te.value : \"\");\n te.value = \"\\u21da\"; // Used to catch context-menu undo\n te.value = extval;\n input.prevInput = selected ? \"\" : \"\\u200b\";\n te.selectionStart = 1; te.selectionEnd = extval.length;\n // Re-set this, in case some other handler touched the\n // selection in the meantime.\n display.selForContextMenu = cm.doc.sel;\n }\n }\n function rehide() {\n input.contextMenuPending = false;\n input.wrapper.style.cssText = oldWrapperCSS;\n te.style.cssText = oldCSS;\n if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }\n\n // Try to detect the user choosing select-all\n if (te.selectionStart != null) {\n if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }\n var i = 0, poll = function () {\n if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&\n te.selectionEnd > 0 && input.prevInput == \"\\u200b\") {\n operation(cm, selectAll)(cm);\n } else if (i++ < 10) {\n display.detectingSelectAll = setTimeout(poll, 500);\n } else {\n display.selForContextMenu = null;\n display.input.reset();\n }\n };\n display.detectingSelectAll = setTimeout(poll, 200);\n }\n }\n\n if (ie && ie_version >= 9) { prepareSelectAllHack(); }\n if (captureRightClick) {\n e_stop(e);\n var mouseup = function () {\n off(window, \"mouseup\", mouseup);\n setTimeout(rehide, 20);\n };\n on(window, \"mouseup\", mouseup);\n } else {\n setTimeout(rehide, 50);\n }\n };\n\n TextareaInput.prototype.readOnlyChanged = function (val) {\n if (!val) { this.reset(); }\n this.textarea.disabled = val == \"nocursor\";\n };\n\n TextareaInput.prototype.setUneditable = function () {};\n\n TextareaInput.prototype.needsContentAttribute = false;\n\n function fromTextArea(textarea, options) {\n options = options ? copyObj(options) : {};\n options.value = textarea.value;\n if (!options.tabindex && textarea.tabIndex)\n { options.tabindex = textarea.tabIndex; }\n if (!options.placeholder && textarea.placeholder)\n { options.placeholder = textarea.placeholder; }\n // Set autofocus to true if this textarea is focused, or if it has\n // autofocus and no other element is focused.\n if (options.autofocus == null) {\n var hasFocus = activeElt();\n options.autofocus = hasFocus == textarea ||\n textarea.getAttribute(\"autofocus\") != null && hasFocus == document.body;\n }\n\n function save() {textarea.value = cm.getValue();}\n\n var realSubmit;\n if (textarea.form) {\n on(textarea.form, \"submit\", save);\n // Deplorable hack to make the submit method do the right thing.\n if (!options.leaveSubmitMethodAlone) {\n var form = textarea.form;\n realSubmit = form.submit;\n try {\n var wrappedSubmit = form.submit = function () {\n save();\n form.submit = realSubmit;\n form.submit();\n form.submit = wrappedSubmit;\n };\n } catch(e) {}\n }\n }\n\n options.finishInit = function (cm) {\n cm.save = save;\n cm.getTextArea = function () { return textarea; };\n cm.toTextArea = function () {\n cm.toTextArea = isNaN; // Prevent this from being ran twice\n save();\n textarea.parentNode.removeChild(cm.getWrapperElement());\n textarea.style.display = \"\";\n if (textarea.form) {\n off(textarea.form, \"submit\", save);\n if (typeof textarea.form.submit == \"function\")\n { textarea.form.submit = realSubmit; }\n }\n };\n };\n\n textarea.style.display = \"none\";\n var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },\n options);\n return cm\n }\n\n function addLegacyProps(CodeMirror) {\n CodeMirror.off = off;\n CodeMirror.on = on;\n CodeMirror.wheelEventPixels = wheelEventPixels;\n CodeMirror.Doc = Doc;\n CodeMirror.splitLines = splitLinesAuto;\n CodeMirror.countColumn = countColumn;\n CodeMirror.findColumn = findColumn;\n CodeMirror.isWordChar = isWordCharBasic;\n CodeMirror.Pass = Pass;\n CodeMirror.signal = signal;\n CodeMirror.Line = Line;\n CodeMirror.changeEnd = changeEnd;\n CodeMirror.scrollbarModel = scrollbarModel;\n CodeMirror.Pos = Pos;\n CodeMirror.cmpPos = cmp;\n CodeMirror.modes = modes;\n CodeMirror.mimeModes = mimeModes;\n CodeMirror.resolveMode = resolveMode;\n CodeMirror.getMode = getMode;\n CodeMirror.modeExtensions = modeExtensions;\n CodeMirror.extendMode = extendMode;\n CodeMirror.copyState = copyState;\n CodeMirror.startState = startState;\n CodeMirror.innerMode = innerMode;\n CodeMirror.commands = commands;\n CodeMirror.keyMap = keyMap;\n CodeMirror.keyName = keyName;\n CodeMirror.isModifierKey = isModifierKey;\n CodeMirror.lookupKey = lookupKey;\n CodeMirror.normalizeKeyMap = normalizeKeyMap;\n CodeMirror.StringStream = StringStream;\n CodeMirror.SharedTextMarker = SharedTextMarker;\n CodeMirror.TextMarker = TextMarker;\n CodeMirror.LineWidget = LineWidget;\n CodeMirror.e_preventDefault = e_preventDefault;\n CodeMirror.e_stopPropagation = e_stopPropagation;\n CodeMirror.e_stop = e_stop;\n CodeMirror.addClass = addClass;\n CodeMirror.contains = contains;\n CodeMirror.rmClass = rmClass;\n CodeMirror.keyNames = keyNames;\n }\n\n // EDITOR CONSTRUCTOR\n\n defineOptions(CodeMirror);\n\n addEditorMethods(CodeMirror);\n\n // Set up methods on CodeMirror's prototype to redirect to the editor's document.\n var dontDelegate = \"iter insert remove copy getEditor constructor\".split(\" \");\n for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)\n { CodeMirror.prototype[prop] = (function(method) {\n return function() {return method.apply(this.doc, arguments)}\n })(Doc.prototype[prop]); } }\n\n eventMixin(Doc);\n CodeMirror.inputStyles = {\"textarea\": TextareaInput, \"contenteditable\": ContentEditableInput};\n\n // Extra arguments are stored as the mode's dependencies, which is\n // used by (legacy) mechanisms like loadmode.js to automatically\n // load a mode. (Preferred mechanism is the require/define calls.)\n CodeMirror.defineMode = function(name/*, mode, …*/) {\n if (!CodeMirror.defaults.mode && name != \"null\") { CodeMirror.defaults.mode = name; }\n defineMode.apply(this, arguments);\n };\n\n CodeMirror.defineMIME = defineMIME;\n\n // Minimal default mode.\n CodeMirror.defineMode(\"null\", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });\n CodeMirror.defineMIME(\"text/plain\", \"null\");\n\n // EXTENSIONS\n\n CodeMirror.defineExtension = function (name, func) {\n CodeMirror.prototype[name] = func;\n };\n CodeMirror.defineDocExtension = function (name, func) {\n Doc.prototype[name] = func;\n };\n\n CodeMirror.fromTextArea = fromTextArea;\n\n addLegacyProps(CodeMirror);\n\n CodeMirror.version = \"5.42.0\";\n\n return CodeMirror;\n\n})));\n\n},{}],18:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"css\", function(config, parserConfig) {\n var inline = parserConfig.inline\n if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode(\"text/css\");\n\n var indentUnit = config.indentUnit,\n tokenHooks = parserConfig.tokenHooks,\n documentTypes = parserConfig.documentTypes || {},\n mediaTypes = parserConfig.mediaTypes || {},\n mediaFeatures = parserConfig.mediaFeatures || {},\n mediaValueKeywords = parserConfig.mediaValueKeywords || {},\n propertyKeywords = parserConfig.propertyKeywords || {},\n nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},\n fontProperties = parserConfig.fontProperties || {},\n counterDescriptors = parserConfig.counterDescriptors || {},\n colorKeywords = parserConfig.colorKeywords || {},\n valueKeywords = parserConfig.valueKeywords || {},\n allowNested = parserConfig.allowNested,\n lineComment = parserConfig.lineComment,\n supportsAtComponent = parserConfig.supportsAtComponent === true;\n\n var type, override;\n function ret(style, tp) { type = tp; return style; }\n\n // Tokenizers\n\n function tokenBase(stream, state) {\n var ch = stream.next();\n if (tokenHooks[ch]) {\n var result = tokenHooks[ch](stream, state);\n if (result !== false) return result;\n }\n if (ch == \"@\") {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"def\", stream.current());\n } else if (ch == \"=\" || (ch == \"~\" || ch == \"|\") && stream.eat(\"=\")) {\n return ret(null, \"compare\");\n } else if (ch == \"\\\"\" || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n } else if (ch == \"#\") {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"atom\", \"hash\");\n } else if (ch == \"!\") {\n stream.match(/^\\s*\\w*/);\n return ret(\"keyword\", \"important\");\n } else if (/\\d/.test(ch) || ch == \".\" && stream.eat(/\\d/)) {\n stream.eatWhile(/[\\w.%]/);\n return ret(\"number\", \"unit\");\n } else if (ch === \"-\") {\n if (/[\\d.]/.test(stream.peek())) {\n stream.eatWhile(/[\\w.%]/);\n return ret(\"number\", \"unit\");\n } else if (stream.match(/^-[\\w\\\\\\-]+/)) {\n stream.eatWhile(/[\\w\\\\\\-]/);\n if (stream.match(/^\\s*:/, false))\n return ret(\"variable-2\", \"variable-definition\");\n return ret(\"variable-2\", \"variable\");\n } else if (stream.match(/^\\w+-/)) {\n return ret(\"meta\", \"meta\");\n }\n } else if (/[,+>*\\/]/.test(ch)) {\n return ret(null, \"select-op\");\n } else if (ch == \".\" && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {\n return ret(\"qualifier\", \"qualifier\");\n } else if (/[:;{}\\[\\]\\(\\)]/.test(ch)) {\n return ret(null, ch);\n } else if (((ch == \"u\" || ch == \"U\") && stream.match(/rl(-prefix)?\\(/i)) ||\n ((ch == \"d\" || ch == \"D\") && stream.match(\"omain(\", true, true)) ||\n ((ch == \"r\" || ch == \"R\") && stream.match(\"egexp(\", true, true))) {\n stream.backUp(1);\n state.tokenize = tokenParenthesized;\n return ret(\"property\", \"word\");\n } else if (/[\\w\\\\\\-]/.test(ch)) {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"property\", \"word\");\n } else {\n return ret(null, null);\n }\n }\n\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped) {\n if (quote == \")\") stream.backUp(1);\n break;\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n if (ch == quote || !escaped && quote != \")\") state.tokenize = null;\n return ret(\"string\", \"string\");\n };\n }\n\n function tokenParenthesized(stream, state) {\n stream.next(); // Must be '('\n if (!stream.match(/\\s*[\\\"\\')]/, false))\n state.tokenize = tokenString(\")\");\n else\n state.tokenize = null;\n return ret(null, \"(\");\n }\n\n // Context management\n\n function Context(type, indent, prev) {\n this.type = type;\n this.indent = indent;\n this.prev = prev;\n }\n\n function pushContext(state, stream, type, indent) {\n state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);\n return type;\n }\n\n function popContext(state) {\n if (state.context.prev)\n state.context = state.context.prev;\n return state.context.type;\n }\n\n function pass(type, stream, state) {\n return states[state.context.type](type, stream, state);\n }\n function popAndPass(type, stream, state, n) {\n for (var i = n || 1; i > 0; i--)\n state.context = state.context.prev;\n return pass(type, stream, state);\n }\n\n // Parser\n\n function wordAsValue(stream) {\n var word = stream.current().toLowerCase();\n if (valueKeywords.hasOwnProperty(word))\n override = \"atom\";\n else if (colorKeywords.hasOwnProperty(word))\n override = \"keyword\";\n else\n override = \"variable\";\n }\n\n var states = {};\n\n states.top = function(type, stream, state) {\n if (type == \"{\") {\n return pushContext(state, stream, \"block\");\n } else if (type == \"}\" && state.context.prev) {\n return popContext(state);\n } else if (supportsAtComponent && /@component/i.test(type)) {\n return pushContext(state, stream, \"atComponentBlock\");\n } else if (/^@(-moz-)?document$/i.test(type)) {\n return pushContext(state, stream, \"documentTypes\");\n } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {\n return pushContext(state, stream, \"atBlock\");\n } else if (/^@(font-face|counter-style)/i.test(type)) {\n state.stateArg = type;\n return \"restricted_atBlock_before\";\n } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {\n return \"keyframes\";\n } else if (type && type.charAt(0) == \"@\") {\n return pushContext(state, stream, \"at\");\n } else if (type == \"hash\") {\n override = \"builtin\";\n } else if (type == \"word\") {\n override = \"tag\";\n } else if (type == \"variable-definition\") {\n return \"maybeprop\";\n } else if (type == \"interpolation\") {\n return pushContext(state, stream, \"interpolation\");\n } else if (type == \":\") {\n return \"pseudo\";\n } else if (allowNested && type == \"(\") {\n return pushContext(state, stream, \"parens\");\n }\n return state.context.type;\n };\n\n states.block = function(type, stream, state) {\n if (type == \"word\") {\n var word = stream.current().toLowerCase();\n if (propertyKeywords.hasOwnProperty(word)) {\n override = \"property\";\n return \"maybeprop\";\n } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {\n override = \"string-2\";\n return \"maybeprop\";\n } else if (allowNested) {\n override = stream.match(/^\\s*:(?:\\s|$)/, false) ? \"property\" : \"tag\";\n return \"block\";\n } else {\n override += \" error\";\n return \"maybeprop\";\n }\n } else if (type == \"meta\") {\n return \"block\";\n } else if (!allowNested && (type == \"hash\" || type == \"qualifier\")) {\n override = \"error\";\n return \"block\";\n } else {\n return states.top(type, stream, state);\n }\n };\n\n states.maybeprop = function(type, stream, state) {\n if (type == \":\") return pushContext(state, stream, \"prop\");\n return pass(type, stream, state);\n };\n\n states.prop = function(type, stream, state) {\n if (type == \";\") return popContext(state);\n if (type == \"{\" && allowNested) return pushContext(state, stream, \"propBlock\");\n if (type == \"}\" || type == \"{\") return popAndPass(type, stream, state);\n if (type == \"(\") return pushContext(state, stream, \"parens\");\n\n if (type == \"hash\" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {\n override += \" error\";\n } else if (type == \"word\") {\n wordAsValue(stream);\n } else if (type == \"interpolation\") {\n return pushContext(state, stream, \"interpolation\");\n }\n return \"prop\";\n };\n\n states.propBlock = function(type, _stream, state) {\n if (type == \"}\") return popContext(state);\n if (type == \"word\") { override = \"property\"; return \"maybeprop\"; }\n return state.context.type;\n };\n\n states.parens = function(type, stream, state) {\n if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state);\n if (type == \")\") return popContext(state);\n if (type == \"(\") return pushContext(state, stream, \"parens\");\n if (type == \"interpolation\") return pushContext(state, stream, \"interpolation\");\n if (type == \"word\") wordAsValue(stream);\n return \"parens\";\n };\n\n states.pseudo = function(type, stream, state) {\n if (type == \"meta\") return \"pseudo\";\n\n if (type == \"word\") {\n override = \"variable-3\";\n return state.context.type;\n }\n return pass(type, stream, state);\n };\n\n states.documentTypes = function(type, stream, state) {\n if (type == \"word\" && documentTypes.hasOwnProperty(stream.current())) {\n override = \"tag\";\n return state.context.type;\n } else {\n return states.atBlock(type, stream, state);\n }\n };\n\n states.atBlock = function(type, stream, state) {\n if (type == \"(\") return pushContext(state, stream, \"atBlock_parens\");\n if (type == \"}\" || type == \";\") return popAndPass(type, stream, state);\n if (type == \"{\") return popContext(state) && pushContext(state, stream, allowNested ? \"block\" : \"top\");\n\n if (type == \"interpolation\") return pushContext(state, stream, \"interpolation\");\n\n if (type == \"word\") {\n var word = stream.current().toLowerCase();\n if (word == \"only\" || word == \"not\" || word == \"and\" || word == \"or\")\n override = \"keyword\";\n else if (mediaTypes.hasOwnProperty(word))\n override = \"attribute\";\n else if (mediaFeatures.hasOwnProperty(word))\n override = \"property\";\n else if (mediaValueKeywords.hasOwnProperty(word))\n override = \"keyword\";\n else if (propertyKeywords.hasOwnProperty(word))\n override = \"property\";\n else if (nonStandardPropertyKeywords.hasOwnProperty(word))\n override = \"string-2\";\n else if (valueKeywords.hasOwnProperty(word))\n override = \"atom\";\n else if (colorKeywords.hasOwnProperty(word))\n override = \"keyword\";\n else\n override = \"error\";\n }\n return state.context.type;\n };\n\n states.atComponentBlock = function(type, stream, state) {\n if (type == \"}\")\n return popAndPass(type, stream, state);\n if (type == \"{\")\n return popContext(state) && pushContext(state, stream, allowNested ? \"block\" : \"top\", false);\n if (type == \"word\")\n override = \"error\";\n return state.context.type;\n };\n\n states.atBlock_parens = function(type, stream, state) {\n if (type == \")\") return popContext(state);\n if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state, 2);\n return states.atBlock(type, stream, state);\n };\n\n states.restricted_atBlock_before = function(type, stream, state) {\n if (type == \"{\")\n return pushContext(state, stream, \"restricted_atBlock\");\n if (type == \"word\" && state.stateArg == \"@counter-style\") {\n override = \"variable\";\n return \"restricted_atBlock_before\";\n }\n return pass(type, stream, state);\n };\n\n states.restricted_atBlock = function(type, stream, state) {\n if (type == \"}\") {\n state.stateArg = null;\n return popContext(state);\n }\n if (type == \"word\") {\n if ((state.stateArg == \"@font-face\" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||\n (state.stateArg == \"@counter-style\" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))\n override = \"error\";\n else\n override = \"property\";\n return \"maybeprop\";\n }\n return \"restricted_atBlock\";\n };\n\n states.keyframes = function(type, stream, state) {\n if (type == \"word\") { override = \"variable\"; return \"keyframes\"; }\n if (type == \"{\") return pushContext(state, stream, \"top\");\n return pass(type, stream, state);\n };\n\n states.at = function(type, stream, state) {\n if (type == \";\") return popContext(state);\n if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state);\n if (type == \"word\") override = \"tag\";\n else if (type == \"hash\") override = \"builtin\";\n return \"at\";\n };\n\n states.interpolation = function(type, stream, state) {\n if (type == \"}\") return popContext(state);\n if (type == \"{\" || type == \";\") return popAndPass(type, stream, state);\n if (type == \"word\") override = \"variable\";\n else if (type != \"variable\" && type != \"(\" && type != \")\") override = \"error\";\n return \"interpolation\";\n };\n\n return {\n startState: function(base) {\n return {tokenize: null,\n state: inline ? \"block\" : \"top\",\n stateArg: null,\n context: new Context(inline ? \"block\" : \"top\", base || 0, null)};\n },\n\n token: function(stream, state) {\n if (!state.tokenize && stream.eatSpace()) return null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style && typeof style == \"object\") {\n type = style[1];\n style = style[0];\n }\n override = style;\n if (type != \"comment\")\n state.state = states[state.state](type, stream, state);\n return override;\n },\n\n indent: function(state, textAfter) {\n var cx = state.context, ch = textAfter && textAfter.charAt(0);\n var indent = cx.indent;\n if (cx.type == \"prop\" && (ch == \"}\" || ch == \")\")) cx = cx.prev;\n if (cx.prev) {\n if (ch == \"}\" && (cx.type == \"block\" || cx.type == \"top\" ||\n cx.type == \"interpolation\" || cx.type == \"restricted_atBlock\")) {\n // Resume indentation from parent context.\n cx = cx.prev;\n indent = cx.indent;\n } else if (ch == \")\" && (cx.type == \"parens\" || cx.type == \"atBlock_parens\") ||\n ch == \"{\" && (cx.type == \"at\" || cx.type == \"atBlock\")) {\n // Dedent relative to current context.\n indent = Math.max(0, cx.indent - indentUnit);\n }\n }\n return indent;\n },\n\n electricChars: \"}\",\n blockCommentStart: \"/*\",\n blockCommentEnd: \"*/\",\n blockCommentContinue: \" * \",\n lineComment: lineComment,\n fold: \"brace\"\n };\n});\n\n function keySet(array) {\n var keys = {};\n for (var i = 0; i < array.length; ++i) {\n keys[array[i].toLowerCase()] = true;\n }\n return keys;\n }\n\n var documentTypes_ = [\n \"domain\", \"regexp\", \"url\", \"url-prefix\"\n ], documentTypes = keySet(documentTypes_);\n\n var mediaTypes_ = [\n \"all\", \"aural\", \"braille\", \"handheld\", \"print\", \"projection\", \"screen\",\n \"tty\", \"tv\", \"embossed\"\n ], mediaTypes = keySet(mediaTypes_);\n\n var mediaFeatures_ = [\n \"width\", \"min-width\", \"max-width\", \"height\", \"min-height\", \"max-height\",\n \"device-width\", \"min-device-width\", \"max-device-width\", \"device-height\",\n \"min-device-height\", \"max-device-height\", \"aspect-ratio\",\n \"min-aspect-ratio\", \"max-aspect-ratio\", \"device-aspect-ratio\",\n \"min-device-aspect-ratio\", \"max-device-aspect-ratio\", \"color\", \"min-color\",\n \"max-color\", \"color-index\", \"min-color-index\", \"max-color-index\",\n \"monochrome\", \"min-monochrome\", \"max-monochrome\", \"resolution\",\n \"min-resolution\", \"max-resolution\", \"scan\", \"grid\", \"orientation\",\n \"device-pixel-ratio\", \"min-device-pixel-ratio\", \"max-device-pixel-ratio\",\n \"pointer\", \"any-pointer\", \"hover\", \"any-hover\"\n ], mediaFeatures = keySet(mediaFeatures_);\n\n var mediaValueKeywords_ = [\n \"landscape\", \"portrait\", \"none\", \"coarse\", \"fine\", \"on-demand\", \"hover\",\n \"interlace\", \"progressive\"\n ], mediaValueKeywords = keySet(mediaValueKeywords_);\n\n var propertyKeywords_ = [\n \"align-content\", \"align-items\", \"align-self\", \"alignment-adjust\",\n \"alignment-baseline\", \"anchor-point\", \"animation\", \"animation-delay\",\n \"animation-direction\", \"animation-duration\", \"animation-fill-mode\",\n \"animation-iteration-count\", \"animation-name\", \"animation-play-state\",\n \"animation-timing-function\", \"appearance\", \"azimuth\", \"backface-visibility\",\n \"background\", \"background-attachment\", \"background-blend-mode\", \"background-clip\",\n \"background-color\", \"background-image\", \"background-origin\", \"background-position\",\n \"background-repeat\", \"background-size\", \"baseline-shift\", \"binding\",\n \"bleed\", \"bookmark-label\", \"bookmark-level\", \"bookmark-state\",\n \"bookmark-target\", \"border\", \"border-bottom\", \"border-bottom-color\",\n \"border-bottom-left-radius\", \"border-bottom-right-radius\",\n \"border-bottom-style\", \"border-bottom-width\", \"border-collapse\",\n \"border-color\", \"border-image\", \"border-image-outset\",\n \"border-image-repeat\", \"border-image-slice\", \"border-image-source\",\n \"border-image-width\", \"border-left\", \"border-left-color\",\n \"border-left-style\", \"border-left-width\", \"border-radius\", \"border-right\",\n \"border-right-color\", \"border-right-style\", \"border-right-width\",\n \"border-spacing\", \"border-style\", \"border-top\", \"border-top-color\",\n \"border-top-left-radius\", \"border-top-right-radius\", \"border-top-style\",\n \"border-top-width\", \"border-width\", \"bottom\", \"box-decoration-break\",\n \"box-shadow\", \"box-sizing\", \"break-after\", \"break-before\", \"break-inside\",\n \"caption-side\", \"caret-color\", \"clear\", \"clip\", \"color\", \"color-profile\", \"column-count\",\n \"column-fill\", \"column-gap\", \"column-rule\", \"column-rule-color\",\n \"column-rule-style\", \"column-rule-width\", \"column-span\", \"column-width\",\n \"columns\", \"content\", \"counter-increment\", \"counter-reset\", \"crop\", \"cue\",\n \"cue-after\", \"cue-before\", \"cursor\", \"direction\", \"display\",\n \"dominant-baseline\", \"drop-initial-after-adjust\",\n \"drop-initial-after-align\", \"drop-initial-before-adjust\",\n \"drop-initial-before-align\", \"drop-initial-size\", \"drop-initial-value\",\n \"elevation\", \"empty-cells\", \"fit\", \"fit-position\", \"flex\", \"flex-basis\",\n \"flex-direction\", \"flex-flow\", \"flex-grow\", \"flex-shrink\", \"flex-wrap\",\n \"float\", \"float-offset\", \"flow-from\", \"flow-into\", \"font\", \"font-feature-settings\",\n \"font-family\", \"font-kerning\", \"font-language-override\", \"font-size\", \"font-size-adjust\",\n \"font-stretch\", \"font-style\", \"font-synthesis\", \"font-variant\",\n \"font-variant-alternates\", \"font-variant-caps\", \"font-variant-east-asian\",\n \"font-variant-ligatures\", \"font-variant-numeric\", \"font-variant-position\",\n \"font-weight\", \"grid\", \"grid-area\", \"grid-auto-columns\", \"grid-auto-flow\",\n \"grid-auto-rows\", \"grid-column\", \"grid-column-end\", \"grid-column-gap\",\n \"grid-column-start\", \"grid-gap\", \"grid-row\", \"grid-row-end\", \"grid-row-gap\",\n \"grid-row-start\", \"grid-template\", \"grid-template-areas\", \"grid-template-columns\",\n \"grid-template-rows\", \"hanging-punctuation\", \"height\", \"hyphens\",\n \"icon\", \"image-orientation\", \"image-rendering\", \"image-resolution\",\n \"inline-box-align\", \"justify-content\", \"justify-items\", \"justify-self\", \"left\", \"letter-spacing\",\n \"line-break\", \"line-height\", \"line-stacking\", \"line-stacking-ruby\",\n \"line-stacking-shift\", \"line-stacking-strategy\", \"list-style\",\n \"list-style-image\", \"list-style-position\", \"list-style-type\", \"margin\",\n \"margin-bottom\", \"margin-left\", \"margin-right\", \"margin-top\",\n \"marks\", \"marquee-direction\", \"marquee-loop\",\n \"marquee-play-count\", \"marquee-speed\", \"marquee-style\", \"max-height\",\n \"max-width\", \"min-height\", \"min-width\", \"mix-blend-mode\", \"move-to\", \"nav-down\", \"nav-index\",\n \"nav-left\", \"nav-right\", \"nav-up\", \"object-fit\", \"object-position\",\n \"opacity\", \"order\", \"orphans\", \"outline\",\n \"outline-color\", \"outline-offset\", \"outline-style\", \"outline-width\",\n \"overflow\", \"overflow-style\", \"overflow-wrap\", \"overflow-x\", \"overflow-y\",\n \"padding\", \"padding-bottom\", \"padding-left\", \"padding-right\", \"padding-top\",\n \"page\", \"page-break-after\", \"page-break-before\", \"page-break-inside\",\n \"page-policy\", \"pause\", \"pause-after\", \"pause-before\", \"perspective\",\n \"perspective-origin\", \"pitch\", \"pitch-range\", \"place-content\", \"place-items\", \"place-self\", \"play-during\", \"position\",\n \"presentation-level\", \"punctuation-trim\", \"quotes\", \"region-break-after\",\n \"region-break-before\", \"region-break-inside\", \"region-fragment\",\n \"rendering-intent\", \"resize\", \"rest\", \"rest-after\", \"rest-before\", \"richness\",\n \"right\", \"rotation\", \"rotation-point\", \"ruby-align\", \"ruby-overhang\",\n \"ruby-position\", \"ruby-span\", \"shape-image-threshold\", \"shape-inside\", \"shape-margin\",\n \"shape-outside\", \"size\", \"speak\", \"speak-as\", \"speak-header\",\n \"speak-numeral\", \"speak-punctuation\", \"speech-rate\", \"stress\", \"string-set\",\n \"tab-size\", \"table-layout\", \"target\", \"target-name\", \"target-new\",\n \"target-position\", \"text-align\", \"text-align-last\", \"text-decoration\",\n \"text-decoration-color\", \"text-decoration-line\", \"text-decoration-skip\",\n \"text-decoration-style\", \"text-emphasis\", \"text-emphasis-color\",\n \"text-emphasis-position\", \"text-emphasis-style\", \"text-height\",\n \"text-indent\", \"text-justify\", \"text-outline\", \"text-overflow\", \"text-shadow\",\n \"text-size-adjust\", \"text-space-collapse\", \"text-transform\", \"text-underline-position\",\n \"text-wrap\", \"top\", \"transform\", \"transform-origin\", \"transform-style\",\n \"transition\", \"transition-delay\", \"transition-duration\",\n \"transition-property\", \"transition-timing-function\", \"unicode-bidi\",\n \"user-select\", \"vertical-align\", \"visibility\", \"voice-balance\", \"voice-duration\",\n \"voice-family\", \"voice-pitch\", \"voice-range\", \"voice-rate\", \"voice-stress\",\n \"voice-volume\", \"volume\", \"white-space\", \"widows\", \"width\", \"will-change\", \"word-break\",\n \"word-spacing\", \"word-wrap\", \"z-index\",\n // SVG-specific\n \"clip-path\", \"clip-rule\", \"mask\", \"enable-background\", \"filter\", \"flood-color\",\n \"flood-opacity\", \"lighting-color\", \"stop-color\", \"stop-opacity\", \"pointer-events\",\n \"color-interpolation\", \"color-interpolation-filters\",\n \"color-rendering\", \"fill\", \"fill-opacity\", \"fill-rule\", \"image-rendering\",\n \"marker\", \"marker-end\", \"marker-mid\", \"marker-start\", \"shape-rendering\", \"stroke\",\n \"stroke-dasharray\", \"stroke-dashoffset\", \"stroke-linecap\", \"stroke-linejoin\",\n \"stroke-miterlimit\", \"stroke-opacity\", \"stroke-width\", \"text-rendering\",\n \"baseline-shift\", \"dominant-baseline\", \"glyph-orientation-horizontal\",\n \"glyph-orientation-vertical\", \"text-anchor\", \"writing-mode\"\n ], propertyKeywords = keySet(propertyKeywords_);\n\n var nonStandardPropertyKeywords_ = [\n \"scrollbar-arrow-color\", \"scrollbar-base-color\", \"scrollbar-dark-shadow-color\",\n \"scrollbar-face-color\", \"scrollbar-highlight-color\", \"scrollbar-shadow-color\",\n \"scrollbar-3d-light-color\", \"scrollbar-track-color\", \"shape-inside\",\n \"searchfield-cancel-button\", \"searchfield-decoration\", \"searchfield-results-button\",\n \"searchfield-results-decoration\", \"zoom\"\n ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);\n\n var fontProperties_ = [\n \"font-family\", \"src\", \"unicode-range\", \"font-variant\", \"font-feature-settings\",\n \"font-stretch\", \"font-weight\", \"font-style\"\n ], fontProperties = keySet(fontProperties_);\n\n var counterDescriptors_ = [\n \"additive-symbols\", \"fallback\", \"negative\", \"pad\", \"prefix\", \"range\",\n \"speak-as\", \"suffix\", \"symbols\", \"system\"\n ], counterDescriptors = keySet(counterDescriptors_);\n\n var colorKeywords_ = [\n \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\",\n \"bisque\", \"black\", \"blanchedalmond\", \"blue\", \"blueviolet\", \"brown\",\n \"burlywood\", \"cadetblue\", \"chartreuse\", \"chocolate\", \"coral\", \"cornflowerblue\",\n \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"darkcyan\", \"darkgoldenrod\",\n \"darkgray\", \"darkgreen\", \"darkkhaki\", \"darkmagenta\", \"darkolivegreen\",\n \"darkorange\", \"darkorchid\", \"darkred\", \"darksalmon\", \"darkseagreen\",\n \"darkslateblue\", \"darkslategray\", \"darkturquoise\", \"darkviolet\",\n \"deeppink\", \"deepskyblue\", \"dimgray\", \"dodgerblue\", \"firebrick\",\n \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\",\n \"gold\", \"goldenrod\", \"gray\", \"grey\", \"green\", \"greenyellow\", \"honeydew\",\n \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\",\n \"lavenderblush\", \"lawngreen\", \"lemonchiffon\", \"lightblue\", \"lightcoral\",\n \"lightcyan\", \"lightgoldenrodyellow\", \"lightgray\", \"lightgreen\", \"lightpink\",\n \"lightsalmon\", \"lightseagreen\", \"lightskyblue\", \"lightslategray\",\n \"lightsteelblue\", \"lightyellow\", \"lime\", \"limegreen\", \"linen\", \"magenta\",\n \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"mediumpurple\",\n \"mediumseagreen\", \"mediumslateblue\", \"mediumspringgreen\", \"mediumturquoise\",\n \"mediumvioletred\", \"midnightblue\", \"mintcream\", \"mistyrose\", \"moccasin\",\n \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\",\n \"orchid\", \"palegoldenrod\", \"palegreen\", \"paleturquoise\", \"palevioletred\",\n \"papayawhip\", \"peachpuff\", \"peru\", \"pink\", \"plum\", \"powderblue\",\n \"purple\", \"rebeccapurple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\",\n \"salmon\", \"sandybrown\", \"seagreen\", \"seashell\", \"sienna\", \"silver\", \"skyblue\",\n \"slateblue\", \"slategray\", \"snow\", \"springgreen\", \"steelblue\", \"tan\",\n \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\",\n \"whitesmoke\", \"yellow\", \"yellowgreen\"\n ], colorKeywords = keySet(colorKeywords_);\n\n var valueKeywords_ = [\n \"above\", \"absolute\", \"activeborder\", \"additive\", \"activecaption\", \"afar\",\n \"after-white-space\", \"ahead\", \"alias\", \"all\", \"all-scroll\", \"alphabetic\", \"alternate\",\n \"always\", \"amharic\", \"amharic-abegede\", \"antialiased\", \"appworkspace\",\n \"arabic-indic\", \"armenian\", \"asterisks\", \"attr\", \"auto\", \"auto-flow\", \"avoid\", \"avoid-column\", \"avoid-page\",\n \"avoid-region\", \"background\", \"backwards\", \"baseline\", \"below\", \"bidi-override\", \"binary\",\n \"bengali\", \"blink\", \"block\", \"block-axis\", \"bold\", \"bolder\", \"border\", \"border-box\",\n \"both\", \"bottom\", \"break\", \"break-all\", \"break-word\", \"bullets\", \"button\", \"button-bevel\",\n \"buttonface\", \"buttonhighlight\", \"buttonshadow\", \"buttontext\", \"calc\", \"cambodian\",\n \"capitalize\", \"caps-lock-indicator\", \"caption\", \"captiontext\", \"caret\",\n \"cell\", \"center\", \"checkbox\", \"circle\", \"cjk-decimal\", \"cjk-earthly-branch\",\n \"cjk-heavenly-stem\", \"cjk-ideographic\", \"clear\", \"clip\", \"close-quote\",\n \"col-resize\", \"collapse\", \"color\", \"color-burn\", \"color-dodge\", \"column\", \"column-reverse\",\n \"compact\", \"condensed\", \"contain\", \"content\", \"contents\",\n \"content-box\", \"context-menu\", \"continuous\", \"copy\", \"counter\", \"counters\", \"cover\", \"crop\",\n \"cross\", \"crosshair\", \"currentcolor\", \"cursive\", \"cyclic\", \"darken\", \"dashed\", \"decimal\",\n \"decimal-leading-zero\", \"default\", \"default-button\", \"dense\", \"destination-atop\",\n \"destination-in\", \"destination-out\", \"destination-over\", \"devanagari\", \"difference\",\n \"disc\", \"discard\", \"disclosure-closed\", \"disclosure-open\", \"document\",\n \"dot-dash\", \"dot-dot-dash\",\n \"dotted\", \"double\", \"down\", \"e-resize\", \"ease\", \"ease-in\", \"ease-in-out\", \"ease-out\",\n \"element\", \"ellipse\", \"ellipsis\", \"embed\", \"end\", \"ethiopic\", \"ethiopic-abegede\",\n \"ethiopic-abegede-am-et\", \"ethiopic-abegede-gez\", \"ethiopic-abegede-ti-er\",\n \"ethiopic-abegede-ti-et\", \"ethiopic-halehame-aa-er\",\n \"ethiopic-halehame-aa-et\", \"ethiopic-halehame-am-et\",\n \"ethiopic-halehame-gez\", \"ethiopic-halehame-om-et\",\n \"ethiopic-halehame-sid-et\", \"ethiopic-halehame-so-et\",\n \"ethiopic-halehame-ti-er\", \"ethiopic-halehame-ti-et\", \"ethiopic-halehame-tig\",\n \"ethiopic-numeric\", \"ew-resize\", \"exclusion\", \"expanded\", \"extends\", \"extra-condensed\",\n \"extra-expanded\", \"fantasy\", \"fast\", \"fill\", \"fixed\", \"flat\", \"flex\", \"flex-end\", \"flex-start\", \"footnotes\",\n \"forwards\", \"from\", \"geometricPrecision\", \"georgian\", \"graytext\", \"grid\", \"groove\",\n \"gujarati\", \"gurmukhi\", \"hand\", \"hangul\", \"hangul-consonant\", \"hard-light\", \"hebrew\",\n \"help\", \"hidden\", \"hide\", \"higher\", \"highlight\", \"highlighttext\",\n \"hiragana\", \"hiragana-iroha\", \"horizontal\", \"hsl\", \"hsla\", \"hue\", \"icon\", \"ignore\",\n \"inactiveborder\", \"inactivecaption\", \"inactivecaptiontext\", \"infinite\",\n \"infobackground\", \"infotext\", \"inherit\", \"initial\", \"inline\", \"inline-axis\",\n \"inline-block\", \"inline-flex\", \"inline-grid\", \"inline-table\", \"inset\", \"inside\", \"intrinsic\", \"invert\",\n \"italic\", \"japanese-formal\", \"japanese-informal\", \"justify\", \"kannada\",\n \"katakana\", \"katakana-iroha\", \"keep-all\", \"khmer\",\n \"korean-hangul-formal\", \"korean-hanja-formal\", \"korean-hanja-informal\",\n \"landscape\", \"lao\", \"large\", \"larger\", \"left\", \"level\", \"lighter\", \"lighten\",\n \"line-through\", \"linear\", \"linear-gradient\", \"lines\", \"list-item\", \"listbox\", \"listitem\",\n \"local\", \"logical\", \"loud\", \"lower\", \"lower-alpha\", \"lower-armenian\",\n \"lower-greek\", \"lower-hexadecimal\", \"lower-latin\", \"lower-norwegian\",\n \"lower-roman\", \"lowercase\", \"ltr\", \"luminosity\", \"malayalam\", \"match\", \"matrix\", \"matrix3d\",\n \"media-controls-background\", \"media-current-time-display\",\n \"media-fullscreen-button\", \"media-mute-button\", \"media-play-button\",\n \"media-return-to-realtime-button\", \"media-rewind-button\",\n \"media-seek-back-button\", \"media-seek-forward-button\", \"media-slider\",\n \"media-sliderthumb\", \"media-time-remaining-display\", \"media-volume-slider\",\n \"media-volume-slider-container\", \"media-volume-sliderthumb\", \"medium\",\n \"menu\", \"menulist\", \"menulist-button\", \"menulist-text\",\n \"menulist-textfield\", \"menutext\", \"message-box\", \"middle\", \"min-intrinsic\",\n \"mix\", \"mongolian\", \"monospace\", \"move\", \"multiple\", \"multiply\", \"myanmar\", \"n-resize\",\n \"narrower\", \"ne-resize\", \"nesw-resize\", \"no-close-quote\", \"no-drop\",\n \"no-open-quote\", \"no-repeat\", \"none\", \"normal\", \"not-allowed\", \"nowrap\",\n \"ns-resize\", \"numbers\", \"numeric\", \"nw-resize\", \"nwse-resize\", \"oblique\", \"octal\", \"opacity\", \"open-quote\",\n \"optimizeLegibility\", \"optimizeSpeed\", \"oriya\", \"oromo\", \"outset\",\n \"outside\", \"outside-shape\", \"overlay\", \"overline\", \"padding\", \"padding-box\",\n \"painted\", \"page\", \"paused\", \"persian\", \"perspective\", \"plus-darker\", \"plus-lighter\",\n \"pointer\", \"polygon\", \"portrait\", \"pre\", \"pre-line\", \"pre-wrap\", \"preserve-3d\",\n \"progress\", \"push-button\", \"radial-gradient\", \"radio\", \"read-only\",\n \"read-write\", \"read-write-plaintext-only\", \"rectangle\", \"region\",\n \"relative\", \"repeat\", \"repeating-linear-gradient\",\n \"repeating-radial-gradient\", \"repeat-x\", \"repeat-y\", \"reset\", \"reverse\",\n \"rgb\", \"rgba\", \"ridge\", \"right\", \"rotate\", \"rotate3d\", \"rotateX\", \"rotateY\",\n \"rotateZ\", \"round\", \"row\", \"row-resize\", \"row-reverse\", \"rtl\", \"run-in\", \"running\",\n \"s-resize\", \"sans-serif\", \"saturation\", \"scale\", \"scale3d\", \"scaleX\", \"scaleY\", \"scaleZ\", \"screen\",\n \"scroll\", \"scrollbar\", \"scroll-position\", \"se-resize\", \"searchfield\",\n \"searchfield-cancel-button\", \"searchfield-decoration\",\n \"searchfield-results-button\", \"searchfield-results-decoration\", \"self-start\", \"self-end\",\n \"semi-condensed\", \"semi-expanded\", \"separate\", \"serif\", \"show\", \"sidama\",\n \"simp-chinese-formal\", \"simp-chinese-informal\", \"single\",\n \"skew\", \"skewX\", \"skewY\", \"skip-white-space\", \"slide\", \"slider-horizontal\",\n \"slider-vertical\", \"sliderthumb-horizontal\", \"sliderthumb-vertical\", \"slow\",\n \"small\", \"small-caps\", \"small-caption\", \"smaller\", \"soft-light\", \"solid\", \"somali\",\n \"source-atop\", \"source-in\", \"source-out\", \"source-over\", \"space\", \"space-around\", \"space-between\", \"space-evenly\", \"spell-out\", \"square\",\n \"square-button\", \"start\", \"static\", \"status-bar\", \"stretch\", \"stroke\", \"sub\",\n \"subpixel-antialiased\", \"super\", \"sw-resize\", \"symbolic\", \"symbols\", \"system-ui\", \"table\",\n \"table-caption\", \"table-cell\", \"table-column\", \"table-column-group\",\n \"table-footer-group\", \"table-header-group\", \"table-row\", \"table-row-group\",\n \"tamil\",\n \"telugu\", \"text\", \"text-bottom\", \"text-top\", \"textarea\", \"textfield\", \"thai\",\n \"thick\", \"thin\", \"threeddarkshadow\", \"threedface\", \"threedhighlight\",\n \"threedlightshadow\", \"threedshadow\", \"tibetan\", \"tigre\", \"tigrinya-er\",\n \"tigrinya-er-abegede\", \"tigrinya-et\", \"tigrinya-et-abegede\", \"to\", \"top\",\n \"trad-chinese-formal\", \"trad-chinese-informal\", \"transform\",\n \"translate\", \"translate3d\", \"translateX\", \"translateY\", \"translateZ\",\n \"transparent\", \"ultra-condensed\", \"ultra-expanded\", \"underline\", \"unset\", \"up\",\n \"upper-alpha\", \"upper-armenian\", \"upper-greek\", \"upper-hexadecimal\",\n \"upper-latin\", \"upper-norwegian\", \"upper-roman\", \"uppercase\", \"urdu\", \"url\",\n \"var\", \"vertical\", \"vertical-text\", \"visible\", \"visibleFill\", \"visiblePainted\",\n \"visibleStroke\", \"visual\", \"w-resize\", \"wait\", \"wave\", \"wider\",\n \"window\", \"windowframe\", \"windowtext\", \"words\", \"wrap\", \"wrap-reverse\", \"x-large\", \"x-small\", \"xor\",\n \"xx-large\", \"xx-small\"\n ], valueKeywords = keySet(valueKeywords_);\n\n var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)\n .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)\n .concat(valueKeywords_);\n CodeMirror.registerHelper(\"hintWords\", \"css\", allWords);\n\n function tokenCComment(stream, state) {\n var maybeEnd = false, ch;\n while ((ch = stream.next()) != null) {\n if (maybeEnd && ch == \"/\") {\n state.tokenize = null;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return [\"comment\", \"comment\"];\n }\n\n CodeMirror.defineMIME(\"text/css\", {\n documentTypes: documentTypes,\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n mediaValueKeywords: mediaValueKeywords,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n fontProperties: fontProperties,\n counterDescriptors: counterDescriptors,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n tokenHooks: {\n \"/\": function(stream, state) {\n if (!stream.eat(\"*\")) return false;\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n }\n },\n name: \"css\"\n });\n\n CodeMirror.defineMIME(\"text/x-scss\", {\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n mediaValueKeywords: mediaValueKeywords,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n fontProperties: fontProperties,\n allowNested: true,\n lineComment: \"//\",\n tokenHooks: {\n \"/\": function(stream, state) {\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return [\"comment\", \"comment\"];\n } else if (stream.eat(\"*\")) {\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n } else {\n return [\"operator\", \"operator\"];\n }\n },\n \":\": function(stream) {\n if (stream.match(/\\s*\\{/, false))\n return [null, null]\n return false;\n },\n \"$\": function(stream) {\n stream.match(/^[\\w-]+/);\n if (stream.match(/^\\s*:/, false))\n return [\"variable-2\", \"variable-definition\"];\n return [\"variable-2\", \"variable\"];\n },\n \"#\": function(stream) {\n if (!stream.eat(\"{\")) return false;\n return [null, \"interpolation\"];\n }\n },\n name: \"css\",\n helperType: \"scss\"\n });\n\n CodeMirror.defineMIME(\"text/x-less\", {\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n mediaValueKeywords: mediaValueKeywords,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n fontProperties: fontProperties,\n allowNested: true,\n lineComment: \"//\",\n tokenHooks: {\n \"/\": function(stream, state) {\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return [\"comment\", \"comment\"];\n } else if (stream.eat(\"*\")) {\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n } else {\n return [\"operator\", \"operator\"];\n }\n },\n \"@\": function(stream) {\n if (stream.eat(\"{\")) return [null, \"interpolation\"];\n if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\\b/i, false)) return false;\n stream.eatWhile(/[\\w\\\\\\-]/);\n if (stream.match(/^\\s*:/, false))\n return [\"variable-2\", \"variable-definition\"];\n return [\"variable-2\", \"variable\"];\n },\n \"&\": function() {\n return [\"atom\", \"atom\"];\n }\n },\n name: \"css\",\n helperType: \"less\"\n });\n\n CodeMirror.defineMIME(\"text/x-gss\", {\n documentTypes: documentTypes,\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n fontProperties: fontProperties,\n counterDescriptors: counterDescriptors,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n supportsAtComponent: true,\n tokenHooks: {\n \"/\": function(stream, state) {\n if (!stream.eat(\"*\")) return false;\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n }\n },\n name: \"css\",\n helperType: \"gss\"\n });\n\n});\n\n},{\"../../lib/codemirror\":17}],19:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"), require(\"../xml/xml\"), require(\"../javascript/javascript\"), require(\"../css/css\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\", \"../xml/xml\", \"../javascript/javascript\", \"../css/css\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n\n var defaultTags = {\n script: [\n [\"lang\", /(javascript|babel)/i, \"javascript\"],\n [\"type\", /^(?:text|application)\\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, \"javascript\"],\n [\"type\", /./, \"text/plain\"],\n [null, null, \"javascript\"]\n ],\n style: [\n [\"lang\", /^css$/i, \"css\"],\n [\"type\", /^(text\\/)?(x-)?(stylesheet|css)$/i, \"css\"],\n [\"type\", /./, \"text/plain\"],\n [null, null, \"css\"]\n ]\n };\n\n function maybeBackup(stream, pat, style) {\n var cur = stream.current(), close = cur.search(pat);\n if (close > -1) {\n stream.backUp(cur.length - close);\n } else if (cur.match(/<\\/?$/)) {\n stream.backUp(cur.length);\n if (!stream.match(pat, false)) stream.match(cur);\n }\n return style;\n }\n\n var attrRegexpCache = {};\n function getAttrRegexp(attr) {\n var regexp = attrRegexpCache[attr];\n if (regexp) return regexp;\n return attrRegexpCache[attr] = new RegExp(\"\\\\s+\" + attr + \"\\\\s*=\\\\s*('|\\\")?([^'\\\"]+)('|\\\")?\\\\s*\");\n }\n\n function getAttrValue(text, attr) {\n var match = text.match(getAttrRegexp(attr))\n return match ? /^\\s*(.*?)\\s*$/.exec(match[2])[1] : \"\"\n }\n\n function getTagRegexp(tagName, anchored) {\n return new RegExp((anchored ? \"^\" : \"\") + \"<\\/\\s*\" + tagName + \"\\s*>\", \"i\");\n }\n\n function addTags(from, to) {\n for (var tag in from) {\n var dest = to[tag] || (to[tag] = []);\n var source = from[tag];\n for (var i = source.length - 1; i >= 0; i--)\n dest.unshift(source[i])\n }\n }\n\n function findMatchingMode(tagInfo, tagText) {\n for (var i = 0; i < tagInfo.length; i++) {\n var spec = tagInfo[i];\n if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];\n }\n }\n\n CodeMirror.defineMode(\"htmlmixed\", function (config, parserConfig) {\n var htmlMode = CodeMirror.getMode(config, {\n name: \"xml\",\n htmlMode: true,\n multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,\n multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag\n });\n\n var tags = {};\n var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;\n addTags(defaultTags, tags);\n if (configTags) addTags(configTags, tags);\n if (configScript) for (var i = configScript.length - 1; i >= 0; i--)\n tags.script.unshift([\"type\", configScript[i].matches, configScript[i].mode])\n\n function html(stream, state) {\n var style = htmlMode.token(stream, state.htmlState), tag = /\\btag\\b/.test(style), tagName\n if (tag && !/[<>\\s\\/]/.test(stream.current()) &&\n (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) &&\n tags.hasOwnProperty(tagName)) {\n state.inTag = tagName + \" \"\n } else if (state.inTag && tag && />$/.test(stream.current())) {\n var inTag = /^([\\S]+) (.*)/.exec(state.inTag)\n state.inTag = null\n var modeSpec = stream.current() == \">\" && findMatchingMode(tags[inTag[1]], inTag[2])\n var mode = CodeMirror.getMode(config, modeSpec)\n var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);\n state.token = function (stream, state) {\n if (stream.match(endTagA, false)) {\n state.token = html;\n state.localState = state.localMode = null;\n return null;\n }\n return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));\n };\n state.localMode = mode;\n state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, \"\"));\n } else if (state.inTag) {\n state.inTag += stream.current()\n if (stream.eol()) state.inTag += \" \"\n }\n return style;\n };\n\n return {\n startState: function () {\n var state = CodeMirror.startState(htmlMode);\n return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};\n },\n\n copyState: function (state) {\n var local;\n if (state.localState) {\n local = CodeMirror.copyState(state.localMode, state.localState);\n }\n return {token: state.token, inTag: state.inTag,\n localMode: state.localMode, localState: local,\n htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};\n },\n\n token: function (stream, state) {\n return state.token(stream, state);\n },\n\n indent: function (state, textAfter, line) {\n if (!state.localMode || /^\\s*<\\//.test(textAfter))\n return htmlMode.indent(state.htmlState, textAfter);\n else if (state.localMode.indent)\n return state.localMode.indent(state.localState, textAfter, line);\n else\n return CodeMirror.Pass;\n },\n\n innerMode: function (state) {\n return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};\n }\n };\n }, \"xml\", \"javascript\", \"css\");\n\n CodeMirror.defineMIME(\"text/html\", \"htmlmixed\");\n});\n\n},{\"../../lib/codemirror\":17,\"../css/css\":18,\"../javascript/javascript\":20,\"../xml/xml\":21}],20:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"javascript\", function(config, parserConfig) {\n var indentUnit = config.indentUnit;\n var statementIndent = parserConfig.statementIndent;\n var jsonldMode = parserConfig.jsonld;\n var jsonMode = parserConfig.json || jsonldMode;\n var isTS = parserConfig.typescript;\n var wordRE = parserConfig.wordCharacters || /[\\w$\\xa1-\\uffff]/;\n\n // Tokenizer\n\n var keywords = function(){\n function kw(type) {return {type: type, style: \"keyword\"};}\n var A = kw(\"keyword a\"), B = kw(\"keyword b\"), C = kw(\"keyword c\"), D = kw(\"keyword d\");\n var operator = kw(\"operator\"), atom = {type: \"atom\", style: \"atom\"};\n\n return {\n \"if\": kw(\"if\"), \"while\": A, \"with\": A, \"else\": B, \"do\": B, \"try\": B, \"finally\": B,\n \"return\": D, \"break\": D, \"continue\": D, \"new\": kw(\"new\"), \"delete\": C, \"void\": C, \"throw\": C,\n \"debugger\": kw(\"debugger\"), \"var\": kw(\"var\"), \"const\": kw(\"var\"), \"let\": kw(\"var\"),\n \"function\": kw(\"function\"), \"catch\": kw(\"catch\"),\n \"for\": kw(\"for\"), \"switch\": kw(\"switch\"), \"case\": kw(\"case\"), \"default\": kw(\"default\"),\n \"in\": operator, \"typeof\": operator, \"instanceof\": operator,\n \"true\": atom, \"false\": atom, \"null\": atom, \"undefined\": atom, \"NaN\": atom, \"Infinity\": atom,\n \"this\": kw(\"this\"), \"class\": kw(\"class\"), \"super\": kw(\"atom\"),\n \"yield\": C, \"export\": kw(\"export\"), \"import\": kw(\"import\"), \"extends\": C,\n \"await\": C\n };\n }();\n\n var isOperatorChar = /[+\\-*&%=<>!?|~^@]/;\n var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)\"/;\n\n function readRegexp(stream) {\n var escaped = false, next, inSet = false;\n while ((next = stream.next()) != null) {\n if (!escaped) {\n if (next == \"/\" && !inSet) return;\n if (next == \"[\") inSet = true;\n else if (inSet && next == \"]\") inSet = false;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n }\n\n // Used as scratch variables to communicate multiple values without\n // consing up tons of objects.\n var type, content;\n function ret(tp, style, cont) {\n type = tp; content = cont;\n return style;\n }\n function tokenBase(stream, state) {\n var ch = stream.next();\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n } else if (ch == \".\" && stream.match(/^\\d+(?:[eE][+\\-]?\\d+)?/)) {\n return ret(\"number\", \"number\");\n } else if (ch == \".\" && stream.match(\"..\")) {\n return ret(\"spread\", \"meta\");\n } else if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n return ret(ch);\n } else if (ch == \"=\" && stream.eat(\">\")) {\n return ret(\"=>\", \"operator\");\n } else if (ch == \"0\" && stream.match(/^(?:x[\\da-f]+|o[0-7]+|b[01]+)n?/i)) {\n return ret(\"number\", \"number\");\n } else if (/\\d/.test(ch)) {\n stream.match(/^\\d*(?:n|(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)?/);\n return ret(\"number\", \"number\");\n } else if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n } else if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return ret(\"comment\", \"comment\");\n } else if (expressionAllowed(stream, state, 1)) {\n readRegexp(stream);\n stream.match(/^\\b(([gimyus])(?![gimyus]*\\2))+\\b/);\n return ret(\"regexp\", \"string-2\");\n } else {\n stream.eat(\"=\");\n return ret(\"operator\", \"operator\", stream.current());\n }\n } else if (ch == \"`\") {\n state.tokenize = tokenQuasi;\n return tokenQuasi(stream, state);\n } else if (ch == \"#\") {\n stream.skipToEnd();\n return ret(\"error\", \"error\");\n } else if (isOperatorChar.test(ch)) {\n if (ch != \">\" || !state.lexical || state.lexical.type != \">\") {\n if (stream.eat(\"=\")) {\n if (ch == \"!\" || ch == \"=\") stream.eat(\"=\")\n } else if (/[<>*+\\-]/.test(ch)) {\n stream.eat(ch)\n if (ch == \">\") stream.eat(ch)\n }\n }\n return ret(\"operator\", \"operator\", stream.current());\n } else if (wordRE.test(ch)) {\n stream.eatWhile(wordRE);\n var word = stream.current()\n if (state.lastType != \".\") {\n if (keywords.propertyIsEnumerable(word)) {\n var kw = keywords[word]\n return ret(kw.type, kw.style, word)\n }\n if (word == \"async\" && stream.match(/^(\\s|\\/\\*.*?\\*\\/)*[\\[\\(\\w]/, false))\n return ret(\"async\", \"keyword\", word)\n }\n return ret(\"variable\", \"variable\", word)\n }\n }\n\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next;\n if (jsonldMode && stream.peek() == \"@\" && stream.match(isJsonldKeyword)){\n state.tokenize = tokenBase;\n return ret(\"jsonld-keyword\", \"meta\");\n }\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) break;\n escaped = !escaped && next == \"\\\\\";\n }\n if (!escaped) state.tokenize = tokenBase;\n return ret(\"string\", \"string\");\n };\n }\n\n function tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return ret(\"comment\", \"comment\");\n }\n\n function tokenQuasi(stream, state) {\n var escaped = false, next;\n while ((next = stream.next()) != null) {\n if (!escaped && (next == \"`\" || next == \"$\" && stream.eat(\"{\"))) {\n state.tokenize = tokenBase;\n break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n return ret(\"quasi\", \"string-2\", stream.current());\n }\n\n var brackets = \"([{}])\";\n // This is a crude lookahead trick to try and notice that we're\n // parsing the argument patterns for a fat-arrow function before we\n // actually hit the arrow token. It only works if the arrow is on\n // the same line as the arguments and there's no strange noise\n // (comments) in between. Fallback is to only notice when we hit the\n // arrow, and not declare the arguments as locals for the arrow\n // body.\n function findFatArrow(stream, state) {\n if (state.fatArrowAt) state.fatArrowAt = null;\n var arrow = stream.string.indexOf(\"=>\", stream.start);\n if (arrow < 0) return;\n\n if (isTS) { // Try to skip TypeScript return type declarations after the arguments\n var m = /:\\s*(?:\\w+(?:<[^>]*>|\\[\\])?|\\{[^}]*\\})\\s*$/.exec(stream.string.slice(stream.start, arrow))\n if (m) arrow = m.index\n }\n\n var depth = 0, sawSomething = false;\n for (var pos = arrow - 1; pos >= 0; --pos) {\n var ch = stream.string.charAt(pos);\n var bracket = brackets.indexOf(ch);\n if (bracket >= 0 && bracket < 3) {\n if (!depth) { ++pos; break; }\n if (--depth == 0) { if (ch == \"(\") sawSomething = true; break; }\n } else if (bracket >= 3 && bracket < 6) {\n ++depth;\n } else if (wordRE.test(ch)) {\n sawSomething = true;\n } else if (/[\"'\\/]/.test(ch)) {\n return;\n } else if (sawSomething && !depth) {\n ++pos;\n break;\n }\n }\n if (sawSomething && !depth) state.fatArrowAt = pos;\n }\n\n // Parser\n\n var atomicTypes = {\"atom\": true, \"number\": true, \"variable\": true, \"string\": true, \"regexp\": true, \"this\": true, \"jsonld-keyword\": true};\n\n function JSLexical(indented, column, type, align, prev, info) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.prev = prev;\n this.info = info;\n if (align != null) this.align = align;\n }\n\n function inScope(state, varname) {\n for (var v = state.localVars; v; v = v.next)\n if (v.name == varname) return true;\n for (var cx = state.context; cx; cx = cx.prev) {\n for (var v = cx.vars; v; v = v.next)\n if (v.name == varname) return true;\n }\n }\n\n function parseJS(state, style, type, content, stream) {\n var cc = state.cc;\n // Communicate our context to the combinators.\n // (Less wasteful than consing up a hundred closures on every call.)\n cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;\n\n if (!state.lexical.hasOwnProperty(\"align\"))\n state.lexical.align = true;\n\n while(true) {\n var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;\n if (combinator(type, content)) {\n while(cc.length && cc[cc.length - 1].lex)\n cc.pop()();\n if (cx.marked) return cx.marked;\n if (type == \"variable\" && inScope(state, content)) return \"variable-2\";\n return style;\n }\n }\n }\n\n // Combinator utils\n\n var cx = {state: null, column: null, marked: null, cc: null};\n function pass() {\n for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);\n }\n function cont() {\n pass.apply(null, arguments);\n return true;\n }\n function inList(name, list) {\n for (var v = list; v; v = v.next) if (v.name == name) return true\n return false;\n }\n function register(varname) {\n var state = cx.state;\n cx.marked = \"def\";\n if (state.context) {\n if (state.lexical.info == \"var\" && state.context && state.context.block) {\n // FIXME function decls are also not block scoped\n var newContext = registerVarScoped(varname, state.context)\n if (newContext != null) {\n state.context = newContext\n return\n }\n } else if (!inList(varname, state.localVars)) {\n state.localVars = new Var(varname, state.localVars)\n return\n }\n }\n // Fall through means this is global\n if (parserConfig.globalVars && !inList(varname, state.globalVars))\n state.globalVars = new Var(varname, state.globalVars)\n }\n function registerVarScoped(varname, context) {\n if (!context) {\n return null\n } else if (context.block) {\n var inner = registerVarScoped(varname, context.prev)\n if (!inner) return null\n if (inner == context.prev) return context\n return new Context(inner, context.vars, true)\n } else if (inList(varname, context.vars)) {\n return context\n } else {\n return new Context(context.prev, new Var(varname, context.vars), false)\n }\n }\n\n function isModifier(name) {\n return name == \"public\" || name == \"private\" || name == \"protected\" || name == \"abstract\" || name == \"readonly\"\n }\n\n // Combinators\n\n function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }\n function Var(name, next) { this.name = name; this.next = next }\n\n var defaultVars = new Var(\"this\", new Var(\"arguments\", null))\n function pushcontext() {\n cx.state.context = new Context(cx.state.context, cx.state.localVars, false)\n cx.state.localVars = defaultVars\n }\n function pushblockcontext() {\n cx.state.context = new Context(cx.state.context, cx.state.localVars, true)\n cx.state.localVars = null\n }\n function popcontext() {\n cx.state.localVars = cx.state.context.vars\n cx.state.context = cx.state.context.prev\n }\n popcontext.lex = true\n function pushlex(type, info) {\n var result = function() {\n var state = cx.state, indent = state.indented;\n if (state.lexical.type == \"stat\") indent = state.lexical.indented;\n else for (var outer = state.lexical; outer && outer.type == \")\" && outer.align; outer = outer.prev)\n indent = outer.indented;\n state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);\n };\n result.lex = true;\n return result;\n }\n function poplex() {\n var state = cx.state;\n if (state.lexical.prev) {\n if (state.lexical.type == \")\")\n state.indented = state.lexical.indented;\n state.lexical = state.lexical.prev;\n }\n }\n poplex.lex = true;\n\n function expect(wanted) {\n function exp(type) {\n if (type == wanted) return cont();\n else if (wanted == \";\" || type == \"}\" || type == \")\" || type == \"]\") return pass();\n else return cont(exp);\n };\n return exp;\n }\n\n function statement(type, value) {\n if (type == \"var\") return cont(pushlex(\"vardef\", value), vardef, expect(\";\"), poplex);\n if (type == \"keyword a\") return cont(pushlex(\"form\"), parenExpr, statement, poplex);\n if (type == \"keyword b\") return cont(pushlex(\"form\"), statement, poplex);\n if (type == \"keyword d\") return cx.stream.match(/^\\s*$/, false) ? cont() : cont(pushlex(\"stat\"), maybeexpression, expect(\";\"), poplex);\n if (type == \"debugger\") return cont(expect(\";\"));\n if (type == \"{\") return cont(pushlex(\"}\"), pushblockcontext, block, poplex, popcontext);\n if (type == \";\") return cont();\n if (type == \"if\") {\n if (cx.state.lexical.info == \"else\" && cx.state.cc[cx.state.cc.length - 1] == poplex)\n cx.state.cc.pop()();\n return cont(pushlex(\"form\"), parenExpr, statement, poplex, maybeelse);\n }\n if (type == \"function\") return cont(functiondef);\n if (type == \"for\") return cont(pushlex(\"form\"), forspec, statement, poplex);\n if (type == \"class\" || (isTS && value == \"interface\")) { cx.marked = \"keyword\"; return cont(pushlex(\"form\"), className, poplex); }\n if (type == \"variable\") {\n if (isTS && value == \"declare\") {\n cx.marked = \"keyword\"\n return cont(statement)\n } else if (isTS && (value == \"module\" || value == \"enum\" || value == \"type\") && cx.stream.match(/^\\s*\\w/, false)) {\n cx.marked = \"keyword\"\n if (value == \"enum\") return cont(enumdef);\n else if (value == \"type\") return cont(typeexpr, expect(\"operator\"), typeexpr, expect(\";\"));\n else return cont(pushlex(\"form\"), pattern, expect(\"{\"), pushlex(\"}\"), block, poplex, poplex)\n } else if (isTS && value == \"namespace\") {\n cx.marked = \"keyword\"\n return cont(pushlex(\"form\"), expression, block, poplex)\n } else if (isTS && value == \"abstract\") {\n cx.marked = \"keyword\"\n return cont(statement)\n } else {\n return cont(pushlex(\"stat\"), maybelabel);\n }\n }\n if (type == \"switch\") return cont(pushlex(\"form\"), parenExpr, expect(\"{\"), pushlex(\"}\", \"switch\"), pushblockcontext,\n block, poplex, poplex, popcontext);\n if (type == \"case\") return cont(expression, expect(\":\"));\n if (type == \"default\") return cont(expect(\":\"));\n if (type == \"catch\") return cont(pushlex(\"form\"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);\n if (type == \"export\") return cont(pushlex(\"stat\"), afterExport, poplex);\n if (type == \"import\") return cont(pushlex(\"stat\"), afterImport, poplex);\n if (type == \"async\") return cont(statement)\n if (value == \"@\") return cont(expression, statement)\n return pass(pushlex(\"stat\"), expression, expect(\";\"), poplex);\n }\n function maybeCatchBinding(type) {\n if (type == \"(\") return cont(funarg, expect(\")\"))\n }\n function expression(type, value) {\n return expressionInner(type, value, false);\n }\n function expressionNoComma(type, value) {\n return expressionInner(type, value, true);\n }\n function parenExpr(type) {\n if (type != \"(\") return pass()\n return cont(pushlex(\")\"), expression, expect(\")\"), poplex)\n }\n function expressionInner(type, value, noComma) {\n if (cx.state.fatArrowAt == cx.stream.start) {\n var body = noComma ? arrowBodyNoComma : arrowBody;\n if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, expect(\"=>\"), body, popcontext);\n else if (type == \"variable\") return pass(pushcontext, pattern, expect(\"=>\"), body, popcontext);\n }\n\n var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;\n if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);\n if (type == \"function\") return cont(functiondef, maybeop);\n if (type == \"class\" || (isTS && value == \"interface\")) { cx.marked = \"keyword\"; return cont(pushlex(\"form\"), classExpression, poplex); }\n if (type == \"keyword c\" || type == \"async\") return cont(noComma ? expressionNoComma : expression);\n if (type == \"(\") return cont(pushlex(\")\"), maybeexpression, expect(\")\"), poplex, maybeop);\n if (type == \"operator\" || type == \"spread\") return cont(noComma ? expressionNoComma : expression);\n if (type == \"[\") return cont(pushlex(\"]\"), arrayLiteral, poplex, maybeop);\n if (type == \"{\") return contCommasep(objprop, \"}\", null, maybeop);\n if (type == \"quasi\") return pass(quasi, maybeop);\n if (type == \"new\") return cont(maybeTarget(noComma));\n if (type == \"import\") return cont(expression);\n return cont();\n }\n function maybeexpression(type) {\n if (type.match(/[;\\}\\)\\],]/)) return pass();\n return pass(expression);\n }\n\n function maybeoperatorComma(type, value) {\n if (type == \",\") return cont(expression);\n return maybeoperatorNoComma(type, value, false);\n }\n function maybeoperatorNoComma(type, value, noComma) {\n var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;\n var expr = noComma == false ? expression : expressionNoComma;\n if (type == \"=>\") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);\n if (type == \"operator\") {\n if (/\\+\\+|--/.test(value) || isTS && value == \"!\") return cont(me);\n if (isTS && value == \"<\" && cx.stream.match(/^([^>]|<.*?>)*>\\s*\\(/, false))\n return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, me);\n if (value == \"?\") return cont(expression, expect(\":\"), expr);\n return cont(expr);\n }\n if (type == \"quasi\") { return pass(quasi, me); }\n if (type == \";\") return;\n if (type == \"(\") return contCommasep(expressionNoComma, \")\", \"call\", me);\n if (type == \".\") return cont(property, me);\n if (type == \"[\") return cont(pushlex(\"]\"), maybeexpression, expect(\"]\"), poplex, me);\n if (isTS && value == \"as\") { cx.marked = \"keyword\"; return cont(typeexpr, me) }\n if (type == \"regexp\") {\n cx.state.lastType = cx.marked = \"operator\"\n cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)\n return cont(expr)\n }\n }\n function quasi(type, value) {\n if (type != \"quasi\") return pass();\n if (value.slice(value.length - 2) != \"${\") return cont(quasi);\n return cont(expression, continueQuasi);\n }\n function continueQuasi(type) {\n if (type == \"}\") {\n cx.marked = \"string-2\";\n cx.state.tokenize = tokenQuasi;\n return cont(quasi);\n }\n }\n function arrowBody(type) {\n findFatArrow(cx.stream, cx.state);\n return pass(type == \"{\" ? statement : expression);\n }\n function arrowBodyNoComma(type) {\n findFatArrow(cx.stream, cx.state);\n return pass(type == \"{\" ? statement : expressionNoComma);\n }\n function maybeTarget(noComma) {\n return function(type) {\n if (type == \".\") return cont(noComma ? targetNoComma : target);\n else if (type == \"variable\" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)\n else return pass(noComma ? expressionNoComma : expression);\n };\n }\n function target(_, value) {\n if (value == \"target\") { cx.marked = \"keyword\"; return cont(maybeoperatorComma); }\n }\n function targetNoComma(_, value) {\n if (value == \"target\") { cx.marked = \"keyword\"; return cont(maybeoperatorNoComma); }\n }\n function maybelabel(type) {\n if (type == \":\") return cont(poplex, statement);\n return pass(maybeoperatorComma, expect(\";\"), poplex);\n }\n function property(type) {\n if (type == \"variable\") {cx.marked = \"property\"; return cont();}\n }\n function objprop(type, value) {\n if (type == \"async\") {\n cx.marked = \"property\";\n return cont(objprop);\n } else if (type == \"variable\" || cx.style == \"keyword\") {\n cx.marked = \"property\";\n if (value == \"get\" || value == \"set\") return cont(getterSetter);\n var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params\n if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\\s*:\\s*/, false)))\n cx.state.fatArrowAt = cx.stream.pos + m[0].length\n return cont(afterprop);\n } else if (type == \"number\" || type == \"string\") {\n cx.marked = jsonldMode ? \"property\" : (cx.style + \" property\");\n return cont(afterprop);\n } else if (type == \"jsonld-keyword\") {\n return cont(afterprop);\n } else if (isTS && isModifier(value)) {\n cx.marked = \"keyword\"\n return cont(objprop)\n } else if (type == \"[\") {\n return cont(expression, maybetype, expect(\"]\"), afterprop);\n } else if (type == \"spread\") {\n return cont(expressionNoComma, afterprop);\n } else if (value == \"*\") {\n cx.marked = \"keyword\";\n return cont(objprop);\n } else if (type == \":\") {\n return pass(afterprop)\n }\n }\n function getterSetter(type) {\n if (type != \"variable\") return pass(afterprop);\n cx.marked = \"property\";\n return cont(functiondef);\n }\n function afterprop(type) {\n if (type == \":\") return cont(expressionNoComma);\n if (type == \"(\") return pass(functiondef);\n }\n function commasep(what, end, sep) {\n function proceed(type, value) {\n if (sep ? sep.indexOf(type) > -1 : type == \",\") {\n var lex = cx.state.lexical;\n if (lex.info == \"call\") lex.pos = (lex.pos || 0) + 1;\n return cont(function(type, value) {\n if (type == end || value == end) return pass()\n return pass(what)\n }, proceed);\n }\n if (type == end || value == end) return cont();\n return cont(expect(end));\n }\n return function(type, value) {\n if (type == end || value == end) return cont();\n return pass(what, proceed);\n };\n }\n function contCommasep(what, end, info) {\n for (var i = 3; i < arguments.length; i++)\n cx.cc.push(arguments[i]);\n return cont(pushlex(end, info), commasep(what, end), poplex);\n }\n function block(type) {\n if (type == \"}\") return cont();\n return pass(statement, block);\n }\n function maybetype(type, value) {\n if (isTS) {\n if (type == \":\") return cont(typeexpr);\n if (value == \"?\") return cont(maybetype);\n }\n }\n function mayberettype(type) {\n if (isTS && type == \":\") {\n if (cx.stream.match(/^\\s*\\w+\\s+is\\b/, false)) return cont(expression, isKW, typeexpr)\n else return cont(typeexpr)\n }\n }\n function isKW(_, value) {\n if (value == \"is\") {\n cx.marked = \"keyword\"\n return cont()\n }\n }\n function typeexpr(type, value) {\n if (value == \"keyof\" || value == \"typeof\") {\n cx.marked = \"keyword\"\n return cont(value == \"keyof\" ? typeexpr : expressionNoComma)\n }\n if (type == \"variable\" || value == \"void\") {\n cx.marked = \"type\"\n return cont(afterType)\n }\n if (type == \"string\" || type == \"number\" || type == \"atom\") return cont(afterType);\n if (type == \"[\") return cont(pushlex(\"]\"), commasep(typeexpr, \"]\", \",\"), poplex, afterType)\n if (type == \"{\") return cont(pushlex(\"}\"), commasep(typeprop, \"}\", \",;\"), poplex, afterType)\n if (type == \"(\") return cont(commasep(typearg, \")\"), maybeReturnType)\n if (type == \"<\") return cont(commasep(typeexpr, \">\"), typeexpr)\n }\n function maybeReturnType(type) {\n if (type == \"=>\") return cont(typeexpr)\n }\n function typeprop(type, value) {\n if (type == \"variable\" || cx.style == \"keyword\") {\n cx.marked = \"property\"\n return cont(typeprop)\n } else if (value == \"?\") {\n return cont(typeprop)\n } else if (type == \":\") {\n return cont(typeexpr)\n } else if (type == \"[\") {\n return cont(expression, maybetype, expect(\"]\"), typeprop)\n }\n }\n function typearg(type, value) {\n if (type == \"variable\" && cx.stream.match(/^\\s*[?:]/, false) || value == \"?\") return cont(typearg)\n if (type == \":\") return cont(typeexpr)\n return pass(typeexpr)\n }\n function afterType(type, value) {\n if (value == \"<\") return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, afterType)\n if (value == \"|\" || type == \".\" || value == \"&\") return cont(typeexpr)\n if (type == \"[\") return cont(expect(\"]\"), afterType)\n if (value == \"extends\" || value == \"implements\") { cx.marked = \"keyword\"; return cont(typeexpr) }\n }\n function maybeTypeArgs(_, value) {\n if (value == \"<\") return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, afterType)\n }\n function typeparam() {\n return pass(typeexpr, maybeTypeDefault)\n }\n function maybeTypeDefault(_, value) {\n if (value == \"=\") return cont(typeexpr)\n }\n function vardef(_, value) {\n if (value == \"enum\") {cx.marked = \"keyword\"; return cont(enumdef)}\n return pass(pattern, maybetype, maybeAssign, vardefCont);\n }\n function pattern(type, value) {\n if (isTS && isModifier(value)) { cx.marked = \"keyword\"; return cont(pattern) }\n if (type == \"variable\") { register(value); return cont(); }\n if (type == \"spread\") return cont(pattern);\n if (type == \"[\") return contCommasep(eltpattern, \"]\");\n if (type == \"{\") return contCommasep(proppattern, \"}\");\n }\n function proppattern(type, value) {\n if (type == \"variable\" && !cx.stream.match(/^\\s*:/, false)) {\n register(value);\n return cont(maybeAssign);\n }\n if (type == \"variable\") cx.marked = \"property\";\n if (type == \"spread\") return cont(pattern);\n if (type == \"}\") return pass();\n if (type == \"[\") return cont(expression, expect(']'), expect(':'), proppattern);\n return cont(expect(\":\"), pattern, maybeAssign);\n }\n function eltpattern() {\n return pass(pattern, maybeAssign)\n }\n function maybeAssign(_type, value) {\n if (value == \"=\") return cont(expressionNoComma);\n }\n function vardefCont(type) {\n if (type == \",\") return cont(vardef);\n }\n function maybeelse(type, value) {\n if (type == \"keyword b\" && value == \"else\") return cont(pushlex(\"form\", \"else\"), statement, poplex);\n }\n function forspec(type, value) {\n if (value == \"await\") return cont(forspec);\n if (type == \"(\") return cont(pushlex(\")\"), forspec1, expect(\")\"), poplex);\n }\n function forspec1(type) {\n if (type == \"var\") return cont(vardef, expect(\";\"), forspec2);\n if (type == \";\") return cont(forspec2);\n if (type == \"variable\") return cont(formaybeinof);\n return pass(expression, expect(\";\"), forspec2);\n }\n function formaybeinof(_type, value) {\n if (value == \"in\" || value == \"of\") { cx.marked = \"keyword\"; return cont(expression); }\n return cont(maybeoperatorComma, forspec2);\n }\n function forspec2(type, value) {\n if (type == \";\") return cont(forspec3);\n if (value == \"in\" || value == \"of\") { cx.marked = \"keyword\"; return cont(expression); }\n return pass(expression, expect(\";\"), forspec3);\n }\n function forspec3(type) {\n if (type != \")\") cont(expression);\n }\n function functiondef(type, value) {\n if (value == \"*\") {cx.marked = \"keyword\"; return cont(functiondef);}\n if (type == \"variable\") {register(value); return cont(functiondef);}\n if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, mayberettype, statement, popcontext);\n if (isTS && value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, functiondef)\n }\n function funarg(type, value) {\n if (value == \"@\") cont(expression, funarg)\n if (type == \"spread\") return cont(funarg);\n if (isTS && isModifier(value)) { cx.marked = \"keyword\"; return cont(funarg); }\n return pass(pattern, maybetype, maybeAssign);\n }\n function classExpression(type, value) {\n // Class expressions may have an optional name.\n if (type == \"variable\") return className(type, value);\n return classNameAfter(type, value);\n }\n function className(type, value) {\n if (type == \"variable\") {register(value); return cont(classNameAfter);}\n }\n function classNameAfter(type, value) {\n if (value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, classNameAfter)\n if (value == \"extends\" || value == \"implements\" || (isTS && type == \",\")) {\n if (value == \"implements\") cx.marked = \"keyword\";\n return cont(isTS ? typeexpr : expression, classNameAfter);\n }\n if (type == \"{\") return cont(pushlex(\"}\"), classBody, poplex);\n }\n function classBody(type, value) {\n if (type == \"async\" ||\n (type == \"variable\" &&\n (value == \"static\" || value == \"get\" || value == \"set\" || (isTS && isModifier(value))) &&\n cx.stream.match(/^\\s+[\\w$\\xa1-\\uffff]/, false))) {\n cx.marked = \"keyword\";\n return cont(classBody);\n }\n if (type == \"variable\" || cx.style == \"keyword\") {\n cx.marked = \"property\";\n return cont(isTS ? classfield : functiondef, classBody);\n }\n if (type == \"[\")\n return cont(expression, maybetype, expect(\"]\"), isTS ? classfield : functiondef, classBody)\n if (value == \"*\") {\n cx.marked = \"keyword\";\n return cont(classBody);\n }\n if (type == \";\") return cont(classBody);\n if (type == \"}\") return cont();\n if (value == \"@\") return cont(expression, classBody)\n }\n function classfield(type, value) {\n if (value == \"?\") return cont(classfield)\n if (type == \":\") return cont(typeexpr, maybeAssign)\n if (value == \"=\") return cont(expressionNoComma)\n return pass(functiondef)\n }\n function afterExport(type, value) {\n if (value == \"*\") { cx.marked = \"keyword\"; return cont(maybeFrom, expect(\";\")); }\n if (value == \"default\") { cx.marked = \"keyword\"; return cont(expression, expect(\";\")); }\n if (type == \"{\") return cont(commasep(exportField, \"}\"), maybeFrom, expect(\";\"));\n return pass(statement);\n }\n function exportField(type, value) {\n if (value == \"as\") { cx.marked = \"keyword\"; return cont(expect(\"variable\")); }\n if (type == \"variable\") return pass(expressionNoComma, exportField);\n }\n function afterImport(type) {\n if (type == \"string\") return cont();\n if (type == \"(\") return pass(expression);\n return pass(importSpec, maybeMoreImports, maybeFrom);\n }\n function importSpec(type, value) {\n if (type == \"{\") return contCommasep(importSpec, \"}\");\n if (type == \"variable\") register(value);\n if (value == \"*\") cx.marked = \"keyword\";\n return cont(maybeAs);\n }\n function maybeMoreImports(type) {\n if (type == \",\") return cont(importSpec, maybeMoreImports)\n }\n function maybeAs(_type, value) {\n if (value == \"as\") { cx.marked = \"keyword\"; return cont(importSpec); }\n }\n function maybeFrom(_type, value) {\n if (value == \"from\") { cx.marked = \"keyword\"; return cont(expression); }\n }\n function arrayLiteral(type) {\n if (type == \"]\") return cont();\n return pass(commasep(expressionNoComma, \"]\"));\n }\n function enumdef() {\n return pass(pushlex(\"form\"), pattern, expect(\"{\"), pushlex(\"}\"), commasep(enummember, \"}\"), poplex, poplex)\n }\n function enummember() {\n return pass(pattern, maybeAssign);\n }\n\n function isContinuedStatement(state, textAfter) {\n return state.lastType == \"operator\" || state.lastType == \",\" ||\n isOperatorChar.test(textAfter.charAt(0)) ||\n /[,.]/.test(textAfter.charAt(0));\n }\n\n function expressionAllowed(stream, state, backUp) {\n return state.tokenize == tokenBase &&\n /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\\[{}\\(,;:]|=>)$/.test(state.lastType) ||\n (state.lastType == \"quasi\" && /\\{\\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))\n }\n\n // Interface\n\n return {\n startState: function(basecolumn) {\n var state = {\n tokenize: tokenBase,\n lastType: \"sof\",\n cc: [],\n lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, \"block\", false),\n localVars: parserConfig.localVars,\n context: parserConfig.localVars && new Context(null, null, false),\n indented: basecolumn || 0\n };\n if (parserConfig.globalVars && typeof parserConfig.globalVars == \"object\")\n state.globalVars = parserConfig.globalVars;\n return state;\n },\n\n token: function(stream, state) {\n if (stream.sol()) {\n if (!state.lexical.hasOwnProperty(\"align\"))\n state.lexical.align = false;\n state.indented = stream.indentation();\n findFatArrow(stream, state);\n }\n if (state.tokenize != tokenComment && stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n if (type == \"comment\") return style;\n state.lastType = type == \"operator\" && (content == \"++\" || content == \"--\") ? \"incdec\" : type;\n return parseJS(state, style, type, content, stream);\n },\n\n indent: function(state, textAfter) {\n if (state.tokenize == tokenComment) return CodeMirror.Pass;\n if (state.tokenize != tokenBase) return 0;\n var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top\n // Kludge to prevent 'maybelse' from blocking lexical scope pops\n if (!/^\\s*else\\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {\n var c = state.cc[i];\n if (c == poplex) lexical = lexical.prev;\n else if (c != maybeelse) break;\n }\n while ((lexical.type == \"stat\" || lexical.type == \"form\") &&\n (firstChar == \"}\" || ((top = state.cc[state.cc.length - 1]) &&\n (top == maybeoperatorComma || top == maybeoperatorNoComma) &&\n !/^[,\\.=+\\-*:?[\\(]/.test(textAfter))))\n lexical = lexical.prev;\n if (statementIndent && lexical.type == \")\" && lexical.prev.type == \"stat\")\n lexical = lexical.prev;\n var type = lexical.type, closing = firstChar == type;\n\n if (type == \"vardef\") return lexical.indented + (state.lastType == \"operator\" || state.lastType == \",\" ? lexical.info.length + 1 : 0);\n else if (type == \"form\" && firstChar == \"{\") return lexical.indented;\n else if (type == \"form\") return lexical.indented + indentUnit;\n else if (type == \"stat\")\n return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);\n else if (lexical.info == \"switch\" && !closing && parserConfig.doubleIndentSwitch != false)\n return lexical.indented + (/^(?:case|default)\\b/.test(textAfter) ? indentUnit : 2 * indentUnit);\n else if (lexical.align) return lexical.column + (closing ? 0 : 1);\n else return lexical.indented + (closing ? 0 : indentUnit);\n },\n\n electricInput: /^\\s*(?:case .*?:|default:|\\{|\\})$/,\n blockCommentStart: jsonMode ? null : \"/*\",\n blockCommentEnd: jsonMode ? null : \"*/\",\n blockCommentContinue: jsonMode ? null : \" * \",\n lineComment: jsonMode ? null : \"//\",\n fold: \"brace\",\n closeBrackets: \"()[]{}''\\\"\\\"``\",\n\n helperType: jsonMode ? \"json\" : \"javascript\",\n jsonldMode: jsonldMode,\n jsonMode: jsonMode,\n\n expressionAllowed: expressionAllowed,\n\n skipExpression: function(state) {\n var top = state.cc[state.cc.length - 1]\n if (top == expression || top == expressionNoComma) state.cc.pop()\n }\n };\n});\n\nCodeMirror.registerHelper(\"wordChars\", \"javascript\", /[\\w$]/);\n\nCodeMirror.defineMIME(\"text/javascript\", \"javascript\");\nCodeMirror.defineMIME(\"text/ecmascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/javascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/x-javascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/ecmascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/json\", {name: \"javascript\", json: true});\nCodeMirror.defineMIME(\"application/x-json\", {name: \"javascript\", json: true});\nCodeMirror.defineMIME(\"application/ld+json\", {name: \"javascript\", jsonld: true});\nCodeMirror.defineMIME(\"text/typescript\", { name: \"javascript\", typescript: true });\nCodeMirror.defineMIME(\"application/typescript\", { name: \"javascript\", typescript: true });\n\n});\n\n},{\"../../lib/codemirror\":17}],21:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nvar htmlConfig = {\n autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,\n 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,\n 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,\n 'track': true, 'wbr': true, 'menuitem': true},\n implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,\n 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,\n 'th': true, 'tr': true},\n contextGrabbers: {\n 'dd': {'dd': true, 'dt': true},\n 'dt': {'dd': true, 'dt': true},\n 'li': {'li': true},\n 'option': {'option': true, 'optgroup': true},\n 'optgroup': {'optgroup': true},\n 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,\n 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,\n 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,\n 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,\n 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},\n 'rp': {'rp': true, 'rt': true},\n 'rt': {'rp': true, 'rt': true},\n 'tbody': {'tbody': true, 'tfoot': true},\n 'td': {'td': true, 'th': true},\n 'tfoot': {'tbody': true},\n 'th': {'td': true, 'th': true},\n 'thead': {'tbody': true, 'tfoot': true},\n 'tr': {'tr': true}\n },\n doNotIndent: {\"pre\": true},\n allowUnquoted: true,\n allowMissing: true,\n caseFold: true\n}\n\nvar xmlConfig = {\n autoSelfClosers: {},\n implicitlyClosed: {},\n contextGrabbers: {},\n doNotIndent: {},\n allowUnquoted: false,\n allowMissing: false,\n allowMissingTagName: false,\n caseFold: false\n}\n\nCodeMirror.defineMode(\"xml\", function(editorConf, config_) {\n var indentUnit = editorConf.indentUnit\n var config = {}\n var defaults = config_.htmlMode ? htmlConfig : xmlConfig\n for (var prop in defaults) config[prop] = defaults[prop]\n for (var prop in config_) config[prop] = config_[prop]\n\n // Return variables for tokenizers\n var type, setStyle;\n\n function inText(stream, state) {\n function chain(parser) {\n state.tokenize = parser;\n return parser(stream, state);\n }\n\n var ch = stream.next();\n if (ch == \"<\") {\n if (stream.eat(\"!\")) {\n if (stream.eat(\"[\")) {\n if (stream.match(\"CDATA[\")) return chain(inBlock(\"atom\", \"]]>\"));\n else return null;\n } else if (stream.match(\"--\")) {\n return chain(inBlock(\"comment\", \"-->\"));\n } else if (stream.match(\"DOCTYPE\", true, true)) {\n stream.eatWhile(/[\\w\\._\\-]/);\n return chain(doctype(1));\n } else {\n return null;\n }\n } else if (stream.eat(\"?\")) {\n stream.eatWhile(/[\\w\\._\\-]/);\n state.tokenize = inBlock(\"meta\", \"?>\");\n return \"meta\";\n } else {\n type = stream.eat(\"/\") ? \"closeTag\" : \"openTag\";\n state.tokenize = inTag;\n return \"tag bracket\";\n }\n } else if (ch == \"&\") {\n var ok;\n if (stream.eat(\"#\")) {\n if (stream.eat(\"x\")) {\n ok = stream.eatWhile(/[a-fA-F\\d]/) && stream.eat(\";\");\n } else {\n ok = stream.eatWhile(/[\\d]/) && stream.eat(\";\");\n }\n } else {\n ok = stream.eatWhile(/[\\w\\.\\-:]/) && stream.eat(\";\");\n }\n return ok ? \"atom\" : \"error\";\n } else {\n stream.eatWhile(/[^&<]/);\n return null;\n }\n }\n inText.isInText = true;\n\n function inTag(stream, state) {\n var ch = stream.next();\n if (ch == \">\" || (ch == \"/\" && stream.eat(\">\"))) {\n state.tokenize = inText;\n type = ch == \">\" ? \"endTag\" : \"selfcloseTag\";\n return \"tag bracket\";\n } else if (ch == \"=\") {\n type = \"equals\";\n return null;\n } else if (ch == \"<\") {\n state.tokenize = inText;\n state.state = baseState;\n state.tagName = state.tagStart = null;\n var next = state.tokenize(stream, state);\n return next ? next + \" tag error\" : \"tag error\";\n } else if (/[\\'\\\"]/.test(ch)) {\n state.tokenize = inAttribute(ch);\n state.stringStartCol = stream.column();\n return state.tokenize(stream, state);\n } else {\n stream.match(/^[^\\s\\u00a0=<>\\\"\\']*[^\\s\\u00a0=<>\\\"\\'\\/]/);\n return \"word\";\n }\n }\n\n function inAttribute(quote) {\n var closure = function(stream, state) {\n while (!stream.eol()) {\n if (stream.next() == quote) {\n state.tokenize = inTag;\n break;\n }\n }\n return \"string\";\n };\n closure.isInAttribute = true;\n return closure;\n }\n\n function inBlock(style, terminator) {\n return function(stream, state) {\n while (!stream.eol()) {\n if (stream.match(terminator)) {\n state.tokenize = inText;\n break;\n }\n stream.next();\n }\n return style;\n }\n }\n\n function doctype(depth) {\n return function(stream, state) {\n var ch;\n while ((ch = stream.next()) != null) {\n if (ch == \"<\") {\n state.tokenize = doctype(depth + 1);\n return state.tokenize(stream, state);\n } else if (ch == \">\") {\n if (depth == 1) {\n state.tokenize = inText;\n break;\n } else {\n state.tokenize = doctype(depth - 1);\n return state.tokenize(stream, state);\n }\n }\n }\n return \"meta\";\n };\n }\n\n function Context(state, tagName, startOfLine) {\n this.prev = state.context;\n this.tagName = tagName;\n this.indent = state.indented;\n this.startOfLine = startOfLine;\n if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))\n this.noIndent = true;\n }\n function popContext(state) {\n if (state.context) state.context = state.context.prev;\n }\n function maybePopContext(state, nextTagName) {\n var parentTagName;\n while (true) {\n if (!state.context) {\n return;\n }\n parentTagName = state.context.tagName;\n if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||\n !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {\n return;\n }\n popContext(state);\n }\n }\n\n function baseState(type, stream, state) {\n if (type == \"openTag\") {\n state.tagStart = stream.column();\n return tagNameState;\n } else if (type == \"closeTag\") {\n return closeTagNameState;\n } else {\n return baseState;\n }\n }\n function tagNameState(type, stream, state) {\n if (type == \"word\") {\n state.tagName = stream.current();\n setStyle = \"tag\";\n return attrState;\n } else if (config.allowMissingTagName && type == \"endTag\") {\n setStyle = \"tag bracket\";\n return attrState(type, stream, state);\n } else {\n setStyle = \"error\";\n return tagNameState;\n }\n }\n function closeTagNameState(type, stream, state) {\n if (type == \"word\") {\n var tagName = stream.current();\n if (state.context && state.context.tagName != tagName &&\n config.implicitlyClosed.hasOwnProperty(state.context.tagName))\n popContext(state);\n if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {\n setStyle = \"tag\";\n return closeState;\n } else {\n setStyle = \"tag error\";\n return closeStateErr;\n }\n } else if (config.allowMissingTagName && type == \"endTag\") {\n setStyle = \"tag bracket\";\n return closeState(type, stream, state);\n } else {\n setStyle = \"error\";\n return closeStateErr;\n }\n }\n\n function closeState(type, _stream, state) {\n if (type != \"endTag\") {\n setStyle = \"error\";\n return closeState;\n }\n popContext(state);\n return baseState;\n }\n function closeStateErr(type, stream, state) {\n setStyle = \"error\";\n return closeState(type, stream, state);\n }\n\n function attrState(type, _stream, state) {\n if (type == \"word\") {\n setStyle = \"attribute\";\n return attrEqState;\n } else if (type == \"endTag\" || type == \"selfcloseTag\") {\n var tagName = state.tagName, tagStart = state.tagStart;\n state.tagName = state.tagStart = null;\n if (type == \"selfcloseTag\" ||\n config.autoSelfClosers.hasOwnProperty(tagName)) {\n maybePopContext(state, tagName);\n } else {\n maybePopContext(state, tagName);\n state.context = new Context(state, tagName, tagStart == state.indented);\n }\n return baseState;\n }\n setStyle = \"error\";\n return attrState;\n }\n function attrEqState(type, stream, state) {\n if (type == \"equals\") return attrValueState;\n if (!config.allowMissing) setStyle = \"error\";\n return attrState(type, stream, state);\n }\n function attrValueState(type, stream, state) {\n if (type == \"string\") return attrContinuedState;\n if (type == \"word\" && config.allowUnquoted) {setStyle = \"string\"; return attrState;}\n setStyle = \"error\";\n return attrState(type, stream, state);\n }\n function attrContinuedState(type, stream, state) {\n if (type == \"string\") return attrContinuedState;\n return attrState(type, stream, state);\n }\n\n return {\n startState: function(baseIndent) {\n var state = {tokenize: inText,\n state: baseState,\n indented: baseIndent || 0,\n tagName: null, tagStart: null,\n context: null}\n if (baseIndent != null) state.baseIndent = baseIndent\n return state\n },\n\n token: function(stream, state) {\n if (!state.tagName && stream.sol())\n state.indented = stream.indentation();\n\n if (stream.eatSpace()) return null;\n type = null;\n var style = state.tokenize(stream, state);\n if ((style || type) && style != \"comment\") {\n setStyle = null;\n state.state = state.state(type || style, stream, state);\n if (setStyle)\n style = setStyle == \"error\" ? style + \" error\" : setStyle;\n }\n return style;\n },\n\n indent: function(state, textAfter, fullLine) {\n var context = state.context;\n // Indent multi-line strings (e.g. css).\n if (state.tokenize.isInAttribute) {\n if (state.tagStart == state.indented)\n return state.stringStartCol + 1;\n else\n return state.indented + indentUnit;\n }\n if (context && context.noIndent) return CodeMirror.Pass;\n if (state.tokenize != inTag && state.tokenize != inText)\n return fullLine ? fullLine.match(/^(\\s*)/)[0].length : 0;\n // Indent the starts of attribute names.\n if (state.tagName) {\n if (config.multilineTagIndentPastTag !== false)\n return state.tagStart + state.tagName.length + 2;\n else\n return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);\n }\n if (config.alignCDATA && /$/,\n blockCommentStart: \"\",\n\n configuration: config.htmlMode ? \"html\" : \"xml\",\n helperType: config.htmlMode ? \"html\" : \"xml\",\n\n skipAttribute: function(state) {\n if (state.state == attrValueState)\n state.state = attrState\n }\n };\n});\n\nCodeMirror.defineMIME(\"text/xml\", \"xml\");\nCodeMirror.defineMIME(\"application/xml\", \"xml\");\nif (!CodeMirror.mimeModes.hasOwnProperty(\"text/html\"))\n CodeMirror.defineMIME(\"text/html\", {name: \"xml\", htmlMode: true});\n\n});\n\n},{\"../../lib/codemirror\":17}],22:[function(require,module,exports){\n/*\n\n Style HTML\n---------------\n\n Written by Nochum Sossonko, (nsossonko@hotmail.com)\n\n Based on code initially developed by: Einar Lielmanis, \n http://jsbeautifier.org/\n\n\n You are free to use this in any way you want, in case you find this useful or working for you.\n\n Usage:\n style_html(html_source);\n\n style_html(html_source, options);\n\n The options are:\n indent_size (default 4) — indentation size,\n indent_char (default space) — character to indent with,\n max_char (default 70) - maximum amount of characters per line,\n brace_style (default \"collapse\") - \"collapse\" | \"expand\" | \"end-expand\"\n put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line.\n unformatted (defaults to inline tags) - list of tags, that shouldn't be reformatted\n indent_scripts (default normal) - \"keep\"|\"separate\"|\"normal\"\n\n e.g.\n\n style_html(html_source, {\n 'indent_size': 2,\n 'indent_char': ' ',\n 'max_char': 78,\n 'brace_style': 'expand',\n 'unformatted': ['a', 'sub', 'sup', 'b', 'i', 'u']\n });\n*/\n\nfunction style_html(html_source, options) {\n//Wrapper function to invoke all the necessary constructors and deal with the output.\n\n var multi_parser,\n indent_size,\n indent_character,\n max_char,\n brace_style,\n unformatted;\n\n options = options || {};\n indent_size = options.indent_size || 4;\n indent_character = options.indent_char || ' ';\n brace_style = options.brace_style || 'collapse';\n max_char = options.max_char == 0 ? Infinity : options.max_char || 70;\n unformatted = options.unformatted || ['a', 'span', 'bdo', 'em', 'strong', 'dfn', 'code', 'samp', 'kbd', 'var', 'cite', 'abbr', 'acronym', 'q', 'sub', 'sup', 'tt', 'i', 'b', 'big', 'small', 'u', 's', 'strike', 'font', 'ins', 'del', 'pre', 'address', 'dt', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];\n\n function Parser() {\n\n this.pos = 0; //Parser position\n this.token = '';\n this.current_mode = 'CONTENT'; //reflects the current Parser mode: TAG/CONTENT\n this.tags = { //An object to hold tags, their position, and their parent-tags, initiated with default values\n parent: 'parent1',\n parentcount: 1,\n parent1: ''\n };\n this.tag_type = '';\n this.token_text = this.last_token = this.last_text = this.token_type = '';\n\n this.Utils = { //Uilities made available to the various functions\n whitespace: \"\\n\\r\\t \".split(''),\n single_token: 'br,input,link,meta,!doctype,basefont,base,area,hr,wbr,param,img,isindex,?xml,embed,?php,?,?='.split(','), //all the single tags for HTML\n extra_liners: 'head,body,/html'.split(','), //for tags that need a line of whitespace before them\n in_array: function (what, arr) {\n for (var i=0; i= this.input.length) {\n return content.length?content.join(''):['', 'TK_EOF'];\n }\n\n input_char = this.input.charAt(this.pos);\n this.pos++;\n this.line_char_count++;\n\n if (this.Utils.in_array(input_char, this.Utils.whitespace)) {\n if (content.length) {\n space = true;\n }\n this.line_char_count--;\n continue; //don't want to insert unnecessary space\n }\n else if (space) {\n if (this.line_char_count >= this.max_char) { //insert a line when the max_char is reached\n content.push('\\n');\n for (var i=0; i', 'igm');\n reg_match.lastIndex = this.pos;\n var reg_array = reg_match.exec(this.input);\n var end_script = reg_array?reg_array.index:this.input.length; //absolute end of script\n if(this.pos < end_script) { //get everything in between the script tags\n content = this.input.substring(this.pos, end_script);\n this.pos = end_script;\n }\n return content;\n }\n\n this.record_tag = function (tag){ //function to record a tag and its parent in this.tags Object\n if (this.tags[tag + 'count']) { //check for the existence of this tag type\n this.tags[tag + 'count']++;\n this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level\n }\n else { //otherwise initialize this tag type\n this.tags[tag + 'count'] = 1;\n this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level\n }\n this.tags[tag + this.tags[tag + 'count'] + 'parent'] = this.tags.parent; //set the parent (i.e. in the case of a div this.tags.div1parent)\n this.tags.parent = tag + this.tags[tag + 'count']; //and make this the current parent (i.e. in the case of a div 'div1')\n }\n\n this.retrieve_tag = function (tag) { //function to retrieve the opening tag to the corresponding closer\n if (this.tags[tag + 'count']) { //if the openener is not in the Object we ignore it\n var temp_parent = this.tags.parent; //check to see if it's a closable tag.\n while (temp_parent) { //till we reach '' (the initial value);\n if (tag + this.tags[tag + 'count'] === temp_parent) { //if this is it use it\n break;\n }\n temp_parent = this.tags[temp_parent + 'parent']; //otherwise keep on climbing up the DOM Tree\n }\n if (temp_parent) { //if we caught something\n this.indent_level = this.tags[tag + this.tags[tag + 'count']]; //set the indent_level accordingly\n this.tags.parent = this.tags[temp_parent + 'parent']; //and set the current parent\n }\n delete this.tags[tag + this.tags[tag + 'count'] + 'parent']; //delete the closed tags parent reference...\n delete this.tags[tag + this.tags[tag + 'count']]; //...and the tag itself\n if (this.tags[tag + 'count'] == 1) {\n delete this.tags[tag + 'count'];\n }\n else {\n this.tags[tag + 'count']--;\n }\n }\n }\n\n this.get_tag = function () { //function to get a full tag and parse its type\n var input_char = '',\n content = [],\n space = false,\n tag_start, tag_end;\n\n do {\n if (this.pos >= this.input.length) {\n return content.length?content.join(''):['', 'TK_EOF'];\n }\n\n input_char = this.input.charAt(this.pos);\n this.pos++;\n this.line_char_count++;\n\n if (this.Utils.in_array(input_char, this.Utils.whitespace)) { //don't want to insert unnecessary space\n space = true;\n this.line_char_count--;\n continue;\n }\n\n if (input_char === \"'\" || input_char === '\"') {\n if (!content[1] || content[1] !== '!') { //if we're in a comment strings don't get treated specially\n input_char += this.get_unformatted(input_char);\n space = true;\n }\n }\n\n if (input_char === '=') { //no space before =\n space = false;\n }\n\n if (content.length && content[content.length-1] !== '=' && input_char !== '>'\n && space) { //no space after = or before >\n if (this.line_char_count >= this.max_char) {\n this.print_newline(false, content);\n this.line_char_count = 0;\n }\n else {\n content.push(' ');\n this.line_char_count++;\n }\n space = false;\n }\n if (input_char === '<') {\n tag_start = this.pos - 1;\n }\n content.push(input_char); //inserts character at-a-time (or string)\n } while (input_char !== '>');\n\n var tag_complete = content.join('');\n var tag_index;\n if (tag_complete.indexOf(' ') != -1) { //if there's whitespace, thats where the tag name ends\n tag_index = tag_complete.indexOf(' ');\n }\n else { //otherwise go with the tag ending\n tag_index = tag_complete.indexOf('>');\n }\n var tag_check = tag_complete.substring(1, tag_index).toLowerCase();\n if (tag_complete.charAt(tag_complete.length-2) === '/' ||\n this.Utils.in_array(tag_check, this.Utils.single_token)) { //if this tag name is a single tag type (either in the list or has a closing /)\n this.tag_type = 'SINGLE';\n }\n else if (tag_check === 'script') { //for later script handling\n this.record_tag(tag_check);\n this.tag_type = 'SCRIPT';\n }\n else if (tag_check === 'style') { //for future style handling (for now it justs uses get_content)\n this.record_tag(tag_check);\n this.tag_type = 'STYLE';\n }\n else if (this.Utils.in_array(tag_check, unformatted)) { // do not reformat the \"unformatted\" tags\n var comment = this.get_unformatted('', tag_complete); //...delegate to get_unformatted function\n content.push(comment);\n // Preserve collapsed whitespace either before or after this tag.\n if (tag_start > 0 && this.Utils.in_array(this.input.charAt(tag_start - 1), this.Utils.whitespace)){\n content.splice(0, 0, this.input.charAt(tag_start - 1));\n }\n tag_end = this.pos - 1;\n if (this.Utils.in_array(this.input.charAt(tag_end + 1), this.Utils.whitespace)){\n content.push(this.input.charAt(tag_end + 1));\n }\n this.tag_type = 'SINGLE';\n }\n else if (tag_check.charAt(0) === '!') { //peek for so...\n var comment = this.get_unformatted('-->', tag_complete); //...delegate to get_unformatted\n content.push(comment);\n }\n this.tag_type = 'START';\n }\n else if (tag_check.indexOf('[endif') != -1) {//peek for ', tag_complete);\n content.push(comment);\n this.tag_type = 'SINGLE';\n }\n }\n else {\n if (tag_check.charAt(0) === '/') { //this tag is a double tag so check for tag-ending\n this.retrieve_tag(tag_check.substring(1)); //remove it and all ancestors\n this.tag_type = 'END';\n }\n else { //otherwise it's a start-tag\n this.record_tag(tag_check); //push it on the tag stack\n this.tag_type = 'START';\n }\n if (this.Utils.in_array(tag_check, this.Utils.extra_liners)) { //check if this double needs an extra line\n this.print_newline(true, this.output);\n }\n }\n return content.join(''); //returns fully formatted tag\n }\n\n this.get_unformatted = function (delimiter, orig_tag) { //function to return unformatted content in its entirety\n\n if (orig_tag && orig_tag.toLowerCase().indexOf(delimiter) != -1) {\n return '';\n }\n var input_char = '';\n var content = '';\n var space = true;\n do {\n\n if (this.pos >= this.input.length) {\n return content;\n }\n\n input_char = this.input.charAt(this.pos);\n this.pos++\n\n if (this.Utils.in_array(input_char, this.Utils.whitespace)) {\n if (!space) {\n this.line_char_count--;\n continue;\n }\n if (input_char === '\\n' || input_char === '\\r') {\n content += '\\n';\n /* Don't change tab indention for unformatted blocks. If using code for html editing, this will greatly affect
 tags if they are specified in the 'unformatted array'\n            for (var i=0; i 0) {\n          this.indent_level--;\n        }\n      }\n    }\n    return this;\n  }\n\n  /*_____________________--------------------_____________________*/\n\n  multi_parser = new Parser(); //wrapping functions Parser\n  multi_parser.printer(html_source, indent_character, indent_size, max_char, brace_style); //initialize starting values\n\n  while (true) {\n      var t = multi_parser.get_token();\n      multi_parser.token_text = t[0];\n      multi_parser.token_type = t[1];\n\n    if (multi_parser.token_type === 'TK_EOF') {\n      break;\n    }\n\n    switch (multi_parser.token_type) {\n      case 'TK_TAG_START':\n        multi_parser.print_newline(false, multi_parser.output);\n        multi_parser.print_token(multi_parser.token_text);\n        multi_parser.indent();\n        multi_parser.current_mode = 'CONTENT';\n        break;\n      case 'TK_TAG_STYLE':\n      case 'TK_TAG_SCRIPT':\n        multi_parser.print_newline(false, multi_parser.output);\n        multi_parser.print_token(multi_parser.token_text);\n        multi_parser.current_mode = 'CONTENT';\n        break;\n      case 'TK_TAG_END':\n        //Print new line only if the tag has no content and has child\n        if (multi_parser.last_token === 'TK_CONTENT' && multi_parser.last_text === '') {\n            var tag_name = multi_parser.token_text.match(/\\w+/)[0];\n            var tag_extracted_from_last_output = multi_parser.output[multi_parser.output.length -1].match(/<\\s*(\\w+)/);\n            if (tag_extracted_from_last_output === null || tag_extracted_from_last_output[1] !== tag_name)\n                multi_parser.print_newline(true, multi_parser.output);\n        }\n        multi_parser.print_token(multi_parser.token_text);\n        multi_parser.current_mode = 'CONTENT';\n        break;\n      case 'TK_TAG_SINGLE':\n        // Don't add a newline before elements that should remain unformatted.\n        var tag_check = multi_parser.token_text.match(/^\\s*<([a-z]+)/i);\n        if (!tag_check || !multi_parser.Utils.in_array(tag_check[1], unformatted)){\n            multi_parser.print_newline(false, multi_parser.output);\n        }\n        multi_parser.print_token(multi_parser.token_text);\n        multi_parser.current_mode = 'CONTENT';\n        break;\n      case 'TK_CONTENT':\n        if (multi_parser.token_text !== '') {\n          multi_parser.print_token(multi_parser.token_text);\n        }\n        multi_parser.current_mode = 'TAG';\n        break;\n      case 'TK_STYLE':\n      case 'TK_SCRIPT':\n        if (multi_parser.token_text !== '') {\n          multi_parser.output.push('\\n');\n          var text = multi_parser.token_text;\n          if (multi_parser.token_type == 'TK_SCRIPT') {\n            var _beautifier = typeof js_beautify == 'function' && js_beautify;\n          } else if (multi_parser.token_type == 'TK_STYLE') {\n            var _beautifier = typeof css_beautify == 'function' && css_beautify;\n          }\n\n          if (options.indent_scripts == \"keep\") {\n            var script_indent_level = 0;\n          } else if (options.indent_scripts == \"separate\") {\n            var script_indent_level = -multi_parser.indent_level;\n          } else {\n            var script_indent_level = 1;\n          }\n\n          var indentation = multi_parser.get_full_indent(script_indent_level);\n          if (_beautifier) {\n            // call the Beautifier if avaliable\n            text = _beautifier(text.replace(/^\\s*/, indentation), options);\n          } else {\n            // simply indent the string otherwise\n            var white = text.match(/^\\s*/)[0];\n            var _level = white.match(/[^\\n\\r]*$/)[0].split(multi_parser.indent_string).length - 1;\n            var reindent = multi_parser.get_full_indent(script_indent_level -_level);\n            text = text.replace(/^\\s*/, indentation)\n                   .replace(/\\r\\n|\\r|\\n/g, '\\n' + reindent)\n                   .replace(/\\s*$/, '');\n          }\n          if (text) {\n            multi_parser.print_token(text);\n            multi_parser.print_newline(true, multi_parser.output);\n          }\n        }\n        multi_parser.current_mode = 'TAG';\n        break;\n    }\n    multi_parser.last_token = multi_parser.token_type;\n    multi_parser.last_text = multi_parser.token_text;\n  }\n  return multi_parser.output.join('');\n}\n\nmodule.exports = {\n  prettyPrint: style_html\n};\n},{}],23:[function(require,module,exports){\n\"use strict\"\n\nmodule.exports = require(\"./stream/stream\")\n\n},{\"./stream/stream\":24}],24:[function(require,module,exports){\n/* eslint-disable */\n;(function() {\n\"use strict\"\n/* eslint-enable */\n\nvar guid = 0, HALT = {}\nfunction createStream() {\n\tfunction stream() {\n\t\tif (arguments.length > 0 && arguments[0] !== HALT) updateStream(stream, arguments[0])\n\t\treturn stream._state.value\n\t}\n\tinitStream(stream)\n\n\tif (arguments.length > 0 && arguments[0] !== HALT) updateStream(stream, arguments[0])\n\n\treturn stream\n}\nfunction initStream(stream) {\n\tstream.constructor = createStream\n\tstream._state = {id: guid++, value: undefined, state: 0, derive: undefined, recover: undefined, deps: {}, parents: [], endStream: undefined, unregister: undefined}\n\tstream.map = stream[\"fantasy-land/map\"] = map, stream[\"fantasy-land/ap\"] = ap, stream[\"fantasy-land/of\"] = createStream\n\tstream.valueOf = valueOf, stream.toJSON = toJSON, stream.toString = valueOf\n\n\tObject.defineProperties(stream, {\n\t\tend: {get: function() {\n\t\t\tif (!stream._state.endStream) {\n\t\t\t\tvar endStream = createStream()\n\t\t\t\tendStream.map(function(value) {\n\t\t\t\t\tif (value === true) {\n\t\t\t\t\t\tunregisterStream(stream)\n\t\t\t\t\t\tendStream._state.unregister = function(){unregisterStream(endStream)}\n\t\t\t\t\t}\n\t\t\t\t\treturn value\n\t\t\t\t})\n\t\t\t\tstream._state.endStream = endStream\n\t\t\t}\n\t\t\treturn stream._state.endStream\n\t\t}}\n\t})\n}\nfunction updateStream(stream, value) {\n\tupdateState(stream, value)\n\tfor (var id in stream._state.deps) updateDependency(stream._state.deps[id], false)\n\tif (stream._state.unregister != null) stream._state.unregister()\n\tfinalize(stream)\n}\nfunction updateState(stream, value) {\n\tstream._state.value = value\n\tstream._state.changed = true\n\tif (stream._state.state !== 2) stream._state.state = 1\n}\nfunction updateDependency(stream, mustSync) {\n\tvar state = stream._state, parents = state.parents\n\tif (parents.length > 0 && parents.every(active) && (mustSync || parents.some(changed))) {\n\t\tvar value = stream._state.derive()\n\t\tif (value === HALT) return false\n\t\tupdateState(stream, value)\n\t}\n}\nfunction finalize(stream) {\n\tstream._state.changed = false\n\tfor (var id in stream._state.deps) stream._state.deps[id]._state.changed = false\n}\n\nfunction combine(fn, streams) {\n\tif (!streams.every(valid)) throw new Error(\"Ensure that each item passed to stream.combine/stream.merge is a stream\")\n\treturn initDependency(createStream(), streams, function() {\n\t\treturn fn.apply(this, streams.concat([streams.filter(changed)]))\n\t})\n}\n\nfunction initDependency(dep, streams, derive) {\n\tvar state = dep._state\n\tstate.derive = derive\n\tstate.parents = streams.filter(notEnded)\n\n\tregisterDependency(dep, state.parents)\n\tupdateDependency(dep, true)\n\n\treturn dep\n}\nfunction registerDependency(stream, parents) {\n\tfor (var i = 0; i < parents.length; i++) {\n\t\tparents[i]._state.deps[stream._state.id] = stream\n\t\tregisterDependency(stream, parents[i]._state.parents)\n\t}\n}\nfunction unregisterStream(stream) {\n\tfor (var i = 0; i < stream._state.parents.length; i++) {\n\t\tvar parent = stream._state.parents[i]\n\t\tdelete parent._state.deps[stream._state.id]\n\t}\n\tfor (var id in stream._state.deps) {\n\t\tvar dependent = stream._state.deps[id]\n\t\tvar index = dependent._state.parents.indexOf(stream)\n\t\tif (index > -1) dependent._state.parents.splice(index, 1)\n\t}\n\tstream._state.state = 2 //ended\n\tstream._state.deps = {}\n}\n\nfunction map(fn) {return combine(function(stream) {return fn(stream())}, [this])}\nfunction ap(stream) {return combine(function(s1, s2) {return s1()(s2())}, [stream, this])}\nfunction valueOf() {return this._state.value}\nfunction toJSON() {return this._state.value != null && typeof this._state.value.toJSON === \"function\" ? this._state.value.toJSON() : this._state.value}\n\nfunction valid(stream) {return stream._state }\nfunction active(stream) {return stream._state.state === 1}\nfunction changed(stream) {return stream._state.changed}\nfunction notEnded(stream) {return stream._state.state !== 2}\n\nfunction merge(streams) {\n\treturn combine(function() {\n\t\treturn streams.map(function(s) {return s()})\n\t}, streams)\n}\n\nfunction scan(reducer, seed, stream) {\n\tvar newStream = combine(function (s) {\n\t\treturn seed = reducer(seed, s._state.value)\n\t}, [stream])\n\n\tif (newStream._state.state === 0) newStream(seed)\n\n\treturn newStream\n}\n\nfunction scanMerge(tuples, seed) {\n\tvar streams = tuples.map(function(tuple) {\n\t\tvar stream = tuple[0]\n\t\tif (stream._state.state === 0) stream(undefined)\n\t\treturn stream\n\t})\n\n\tvar newStream = combine(function() {\n\t\tvar changed = arguments[arguments.length - 1]\n\n\t\tstreams.forEach(function(stream, idx) {\n\t\t\tif (changed.indexOf(stream) > -1) {\n\t\t\t\tseed = tuples[idx][1](seed, stream._state.value)\n\t\t\t}\n\t\t})\n\n\t\treturn seed\n\t}, streams)\n\n\treturn newStream\n}\n\ncreateStream[\"fantasy-land/of\"] = createStream\ncreateStream.merge = merge\ncreateStream.combine = combine\ncreateStream.scan = scan\ncreateStream.scanMerge = scanMerge\ncreateStream.HALT = HALT\n\nif (typeof module !== \"undefined\") module[\"exports\"] = createStream\nelse if (typeof window.m === \"function\" && !(\"stream\" in window.m)) window.m.stream = createStream\nelse window.m = {stream : createStream}\n\n}());\n\n},{}]},{},[11]);\n })();"]}
\ No newline at end of file
+{"version":3,"sources":["forms-admin.js"],"names":["define","undefined","r","e","n","t","o","i","f","c","u","a","Error","code","p","exports","call","length","1","require","module","m","i18n","showType","config","fieldType","type","charAt","toUpperCase","slice","label","fieldLabel","value","onchange","withAttr","placeholder","title","isHidden","initialValue","style","optional","valueHelp","numberMinMax","min","max","isRequired","desc","inputAtts","checked","required","forceRequired","disabled","isFieldRequired","placeholderHelp","useParagraphs","wrap","wrapInParagraphTags","choiceType","options","selected","dropdown","radioButtons","acceptsMultipleValues","push","checkboxes","choices","html","map","choice","index","data-id","name","selectChoice","bind","preselect","remove","class","onclick","key","this","splice","linkToTerms","agreeToTermsLink","link","2","forms","rows","render","text","visibleRows","hidden","submit","number","./field-forms-rows.js","3","htmlutil","setAttributes","vnode","dom","setAttribute","generators","select","attributes","hasSelection","oncreate","unshift","href","target","checkbox","radio","field","htmlTemplate","vdom","document","createElement","showLabel","prettyPrint","innerHTML","4","tabs","editor","fields","events","fieldConfig","generate","overlay","setActiveField","get","join","redraw","createFieldHTMLAndAddToForm","insert","on","view","fieldCategories","getCategories","availableFields","getAll","fieldsChoice","chooseField","category","categoryFields","filter","className","inForm","inFormContent","form","help","trust","onkeydown","window","event","keyCode","addToForm","controller","../overlay.js","./field-forms.js","./field-generator.js","5","registeredFields","register","data","sticky","getFieldType","phone","birthday","registerMergeField","mergeField","listFields","field_type","tag","newsletterType","streetAddress","city","state","zip","country","nl4wp_vars","countries","registerInterestCategory","interestCategory","interestCategories","id","interests","registerListFields","list","merge_fields","sort","b","public","forEach","interest_categories","registerCustomFields","lists","formFields","subscribe","submitButton","listChoice","listChoiceDescription","unsubscribe","formAction","formActionDescription","agreeToTerms","agreeToTermsShort","registerListsFields","deregister","6","prop","timeout","categories","Field","FieldChoice","getAllWhere","searchKey","searchValue","indexOf","existingField","shift","choiceLabel","Object","keys","clearTimeout","setTimeout","trigger","mithril/stream","7","CodeMirror","previewDom","FormEditor","_dom","domDirty","element","getElementById","previewFrame","templateRegex","setPreviewDom","frameContent","contentDocument","contentWindow","querySelector","updatePreview","markup","getValue","replace","dispatchEvent","Event","toLowerCase","addEventListener","signal","query","querySelectorAll","containsField","fieldName","elements","namedItem","replaceSelection","focus","callback","refresh","fromTextArea","selectionPointer","mode","htmlMode","autoCloseTags","autoRefresh","styleActiveLine","matchBrackets","matchTags","bothTags","bubbles","codemirror","codemirror/addon/edit/closetag.js","codemirror/addon/edit/matchbrackets.js","codemirror/addon/edit/matchtags.js","codemirror/addon/fold/xml-fold.js","codemirror/addon/selection/active-line.js","codemirror/mode/css/css","codemirror/mode/htmlmixed/htmlmixed","codemirror/mode/javascript/javascript","codemirror/mode/xml/xml","8","settings","helpers","requiredFieldsInput","updateFields","requiredFields","requiredFieldElements","originalRequiredValue","nameGroup","Array","prototype","el","pos","substr","debounce","9","notices","show","hide","container","heading","parentNode","insertBefore","nextSibling","init","groupingsNotice","requiredFieldsNotice","missingFields","10","_element","_onCloseCallback","close","removeEventListener","onKeyDown","position","preventDefault","windowWidth","innerWidth","documentElement","clientWidth","body","windowHeight","innerHeight","clientHeight","marginLeft","marginTop","left","top","storeElementReference","content","onCloseCallback","onremove","11","nl4wp_forms_i18n","nl4wp","deps","mithril","FormWatcher","FieldHelper","FieldsFactory","formEditor","fieldHelper","mount","fieldsFactory","getSelectedLists","newsletter","./admin/form-editor/field-helper.js","./admin/form-editor/fields-factory.js","./admin/form-editor/fields.js","./admin/form-editor/form-editor.js","./admin/form-editor/form-watcher.js","./admin/notices","12","mod","defineOption","cm","val","old","Init","removeKeyMap","whenClosing","getOption","Pass","autoCloseCurrent","whenOpening","ranges","listSelections","replacements","opt","empty","head","tok","getTokenAt","inner","innerMode","getMode","tagName","configuration","dontCloseTags","htmlDontClose","indentTags","htmlIndent","end","ch","lowerTagName","test","string","closingTagExists","indent","newPos","Pos","line","dontIndentOnAutoClose","info","replaceRange","anchor","sel","setSelections","indentLine","autoCloseGT","addKeyMap","typingSlash","dontIndentOnSlash","replacement","start","context","getLine","replaceSelections","collection","elt","newTag","scanForClosingTag","Math","lastLine","nextClose","cx","onCx","prev","to","next","commands","closeTag","amd","../../lib/codemirror","../fold/xml-fold","13","ie_lt8","navigator","userAgent","documentMode","matching","(",")","[","]","{","}","findMatchingBracket","where","getLineHandle","afterCursor","getWrapperElement","match","dir","strict","getTokenTypeAt","found","scanForBracket","from","forward","maxScanLen","maxScanLineLength","maxScanLines","stack","re","bracketRegex","lineEnd","firstLine","lineNo","pop","autoclear","maxHighlightLen","maxHighlightLineLength","marks","markText","focused","clear","operation","doMatchBrackets","currentlyHighlighted","off","defineExtension","oldConfig","14","tagHit","tagOther","doMatchTags","failedTagMatch","somethingSelected","cur","getCursor","range","getViewport","findMatchingTag","matchBothTags","hit","at","open","other","maybeUpdateMatch","toMatchingTag","extendSelection","15","cmp","nameStartChar","xmlTagStart","RegExp","Iter","tagAt","iter","nextLine","prevLine","toTagEnd","gt","lastSlash","lastIndexOf","selfClose","toTagStart","lt","lastIndex","exec","toNextTag","toPrevTag","findMatchingClose","startLine","startCh","findMatchingOpen","endLine","endCh","registerHelper","openTag","startPos","endPos","here","findEnclosingTag","16","WRAP_CLASS","BACK_CLASS","GUTT_CLASS","clearActiveLines","activeLines","removeLineClass","updateActiveLines","active","option","nonEmpty","getLineHandleVisualStart","sameArray","addLineClass","selectionChange","17","global","factory","platform","gecko","ie_upto10","ie_11up","edge","ie","ie_version","webkit","qtwebkit","chrome","presto","safari","vendor","mac_geMountainLion","phantom","ios","android","mobile","mac","chromeOS","windows","presto_version","Number","flipCtrlCmd","captureRightClick","classTest","cls","rmClass","node","current","after","removeChildren","count","childNodes","removeChild","firstChild","removeChildrenAndAdd","parent","appendChild","cssText","createTextNode","eltP","contains","child","nodeType","host","activeElt","activeElement","shadowRoot","addClass","joinClasses","as","split","createRange","endNode","setEnd","setStart","createTextRange","moveToElementText","collapse","moveEnd","moveStart","selectInput","args","arguments","apply","copyObj","obj","overwrite","hasOwnProperty","countColumn","tabSize","startIndex","startValue","search","nextTab","selectionStart","selectionEnd","_e","Delayed","array","set","ms","scrollerGap","toString","sel_dontScroll","scroll","sel_mouse","origin","sel_move","findColumn","goal","col","skipped","spaceStrs","spaceStr","lst","arr","out","nothing","createObj","base","props","inst","create","nonASCIISingleCaseWordChar","isWordCharBasic","isWordChar","helper","source","isEmpty","extendingChars","isExtendingChar","charCodeAt","skipExtendingChars","str","findFirst","pred","midF","mid","ceil","floor","Display","place","doc","input","d","scrollbarFiller","gutterFiller","lineDiv","selectionDiv","cursorDiv","measure","lineMeasure","lineSpace","lines","mover","sizer","sizerWidth","heightForcer","gutters","lineGutter","scroller","wrapper","zIndex","paddingRight","draggable","viewFrom","viewTo","first","reportedViewFrom","reportedViewTo","renderedView","externalMeasured","viewOffset","lastWrapHeight","lastWrapWidth","updateLineNumbers","nativeBarWidth","barHeight","barWidth","scrollbarsClipped","lineNumWidth","lineNumInnerWidth","lineNumChars","alignWidgets","cachedCharWidth","cachedTextHeight","cachedPaddingH","maxLine","maxLineLength","maxLineChanged","wheelDX","wheelDY","wheelStartX","wheelStartY","selForContextMenu","activeTouch","size","chunk","children","sz","chunkSize","getBetween","getLines","updateLineHeight","height","diff","no","lineAtHeight","h","outer","i$1","lh","isLine","l","lineNumberFor","String","lineNumberFormatter","firstLineNumber","equalCursorPos","copyPos","x","maxPos","minPos","clipLine","clipPos","linelen","last","clipPosArray","sawReadOnlySpans","sawCollapsedSpans","MarkedSpan","marker","getMarkedSpanFor","spans","span","removeMarkedSpan","stretchSpansOverChange","change","full","oldFirst","markedSpans","oldLast","isInsert","nw","inclusiveLeft","insertLeft","endsAfter","inclusiveRight","markedSpansBefore","startsBefore","markedSpansAfter","sameLine","offset","span$1","clearEmptySpans","newMarkers","gapMarkers","gap","i$2","i$3","clearWhenEmpty","detachMarkedSpans","detachLine","attachMarkedSpans","attachLine","extraLeft","extraRight","compareCollapsedMarkers","lenDiff","aPos","find","bPos","fromCmp","toCmp","collapsedSpanAtSide","sps","sp","collapsed","collapsedSpanAtStart","collapsedSpanAtEnd","collapsedSpanAround","conflictingCollapsedRange","lineNo$$1","visualLine","merged","visualLineNo","lineN","vis","visualLineEndNo","lineIsHidden","widgetNode","lineIsHiddenInner","heightAtLine","lineObj","lineLength","len","found$1","findMaxLine","display","bidiOther","getBidiPartAt","order","bidiOrdering","lowTypes","arabicTypes","bidiRE","isNeutral","isStrong","countsAsLeft","countsAsNum","BidiSpan","level","direction","outerType","types","type$1","prev$1","type$2","i$4","type$3","j","i$5","cur$1","type$4","i$6","end$1","before","replace$1","j$1","i$7","j$2","nstart","reverse","getOrder","noHandlers","emitter","attachEvent","map$$1","_handlers","concat","getHandlers","detachEvent","handlers","signalDOMEvent","override","defaultPrevented","e_defaultPrevented","codemirrorIgnore","signalCursorActivity","cursorActivity","curOp","cursorActivityHandlers","hasHandler","eventMixin","ctor","e_preventDefault","returnValue","e_stopPropagation","stopPropagation","cancelBubble","e_stop","e_target","srcElement","e_button","which","button","ctrlKey","zwspSupported","badBidiRects","dragAndDrop","div","zeroWidthElement","offsetHeight","offsetWidth","hasBadBidiRects","txt","r0","getBoundingClientRect","r1","right","splitLinesAuto","result","nl","rt","getSelection","te","range$$1","ownerDocument","selection","parentElement","compareEndPoints","hasCopyEvent","oncopy","badZoomedRects","modes","mimeModes","resolveMode","spec","mfactory","modeObj","modeExtensions","exts","helperType","modeProps","prop$1","extendMode","properties","copyState","nstate","startState","a1","a2","StringStream","lineOracle","lastColumnPos","lastColumnValue","lineStart","eol","sol","peek","eat","eatWhile","eatSpace","skipToEnd","skipTo","backUp","column","indentation","pattern","consume","caseInsensitive","cased","hideFirstChars","lookAhead","oracle","baseToken","SavedContext","Context","maxLookAhead","baseTokens","baseTokenPos","highlightLine","forceToEnd","st","modeGen","lineClasses","runMode","loop","overlays","i_end","opaque","styles","classes","bgClass","textClass","getLineStyles","updateFrontier","getContextBefore","resetState","maxHighlightLength","stateAfter","save","styleClasses","highlightFrontier","modeFrontier","precise","minindent","minline","lim","indented","findStartLine","saved","fromSaved","processLine","startAt","stream","callBlankLine","readToken","blankLine","token","copy","Token","takeToken","asArray","tokens","extractLineClasses","output","lineClass","flattenSpans","curStart","curStyle","addModeClass","mName","Line","estimateHeight","styleToClassCache","styleToClassCacheWithMode","interpretTokenStyle","cache","buildLineContent","lineView","builder","pre","trailingSpace","splitSpaces","rest","addToken","buildToken","buildTokenBadBidi","insertLineContent","maps","caches","lastChild","defaultSpecialCharPlaceholder","startStyle","endStyle","css","displayText","trailingBefore","spaceBefore","special","specialChars","mustWrap","createDocumentFragment","txt$1","tabWidth","specialCharPlaceholder","fullStyle","attr","part","buildCollapsedSpan","ignoreWidget","widget","needsContentAttribute","setUneditable","allText","spanStyle","spanEndStyle","spanStartStyle","nextChange","Infinity","foundBookmarks","endStyles","upto","tokenText","LineView","visualLineContinued","buildViewArray","nextPos","operationGroup","orphanDelayedCallbacks","signalLater","delayedCallbacks","fireOrphanDelayed","delayed","updateLineForChanges","dims","changes","updateLineText","updateLineGutter","updateLineClasses","updateLineWidgets","ensureLineWrapped","replaceChild","getLineContent","ext","built","background","updateLineBackground","wrapClass","gutter","gutterBackground","gutterClass","fixedGutter","fixedPos","gutterTotalWidth","markers","gutterMarkers","lineNumbers","wrap$1","gutterWrap","lineNumber","gutterLeft","k","gutterWidth","alignable","insertLineWidgets","insertLineWidgetsFor","allowAbove","widgets","ws","handleMouseEvents","positionLineWidget","above","noHScroll","width","wrapperWidth","coverGutter","paddingLeft","widgetHeight","parentStyle","eventInWidget","getAttribute","paddingTop","offsetTop","paddingVert","paddingH","getComputedStyle","currentStyle","parseInt","isNaN","scrollGap","displayWidth","displayHeight","mapFromLineView","measureChar","bias","measureCharPrepared","prepareMeasureForLine","findViewForLine","findViewIndex","getDimensions","forceUpdate","updateExternalMeasurement","rect","hasHeights","prepared","varHeight","wrapping","lineWrapping","curWidth","heights","rects","getClientRects","abs","bottom","ensureLineHeights","nodeAndOffsetInLineMap","coverStart","coverEnd","getUsefulRect","screen","logicalXDPI","deviceXDPI","normal","fromRange","hasBadZoomedRects","scaleX","scaleY","logicalYDPI","deviceYDPI","maybeUpdateRectForZooming","rSpan","charWidth","nullRect","rtop","rbot","bot","bogus","singleCursorHeightPerLine","rbottom","measureCharInner","measureText","mStart","mEnd","clearLineMeasurementCacheFor","clearLineMeasurementCache","externalMeasure","clearCaches","pageScrollX","pageXOffset","scrollLeft","pageScrollY","pageYOffset","scrollTop","widgetTopHeight","intoCoordSystem","includeWidgets","yOff","lOff","xOff","fromCoordSystem","coords","localBox","lineSpaceBox","charCoords","cursorCoords","preparedMeasure","getBidi","partPos","invert","estimateCoords","PosWithInfo","outside","xRel","coordsChar","y","coordsCharInner","rangeEnd","wrappedLineExtent","begin","wrappedLineExtentChar","boxIsAfter","box","widgetHeight$$1","ltr","_lineNo","ref","closestDist","endX","dist","baseX","chAround","boxAround","atLeft","atStart","textHeight","clientLeft","offsetLeft","compensateForHScroll","th","perLine","widgetsHeight","estimateLineHeights","est","estHeight","posFromMouse","liberal","forRect","space","clientX","clientY","colDiff","round","updateSelection","showSelection","prepareSelection","primary","curFragment","cursors","selFragment","primIndex","showCursorWhenSelecting","drawSelectionCursor","drawSelectionRange","cursor","cursorHeight","otherCursor","cmpCoords","fragment","padding","leftSide","rightSide","docLTR","add","drawForLine","fromArg","toArg","lineLen","wrapX","side","extent","iterateBidiSections","fromPos","toPos","openStart","openEnd","openRight","topLeft","topRight","botLeft","botRight","sFrom","sTo","fromLine","toLine","singleVLine","leftEnd","rightStart","restartBlink","clearInterval","blinker","visibility","cursorBlinkRate","setInterval","ensureFocus","onFocus","delayBlurEvent","delayingBlurEvent","onBlur","readOnly","reset","receivedFocus","updateHeightsInViewport","prevBottom","updateWidgetHeight","chWidth","w","visibleLines","viewport","ensure","ensureFrom","ensureTo","alignHorizontally","comp","gutterW","align","maybeUpdateLineNumberWidth","innerW","updateGutterSpace","calculateScrollPos","snapMargin","screentop","docBottom","atTop","atBottom","newTop","screenleft","screenw","tooWide","addToScrollTop","resolveScrollToPos","ensureCursorVisible","scrollToPos","margin","cursorScrollMargin","scrollToCoords","scrollToCoordsRange","sPos","updateScrollTop","updateDisplaySimple","setScrollTop","startWorker","forceScroll","scrollHeight","scrollbars","setScrollLeft","isScroller","scrollWidth","measureForScrollbars","docH","viewHeight","viewWidth","barLeft","docHeight","NativeScrollbars","vert","horiz","tabIndex","checkedZeroWidth","minHeight","minWidth","update","needsH","needsV","sWidth","totalHeight","totalWidth","zeroWidthHack","disableHoriz","enableZeroWidthBar","disableVert","pointerEvents","bar","delay","maybeDisable","elementFromPoint","NullScrollbars","updateScrollbars","startWidth","startHeight","updateScrollbarsInner","sizes","paddingBottom","borderBottom","coverGutterNextToScrollbar","scrollbarModel","native","null","initScrollbars","scrollbarStyle","axis","nextOpId","startOperation","op","viewChanged","updateInput","typing","changeObjs","cursorActivityCalled","selectionChanged","updateMaxLine","ops","ownsGroup","endOperation","endCb","group","callbacks","fireCallbacksForOps","finishOperation","endOperation_R1","updatedDisplay","mustUpdate","updateDisplayIfNeeded","endOperation_R2","endOperation_W2","endOperation_finish","endOperations","marginBottom","borderRightWidth","DisplayUpdate","barMeasure","adjustWidthTo","maxScrollLeft","preparedSelection","takeFocus","setDocumentHeight","postUpdateDisplay","doScroll","scrollNode","scrollIntoView","maybeScrollWindow","limit","changed","endCoords","scrollPos","startTop","startLeft","scrollPosIntoView","maybeHiddenMarkers","unhidden","maybeUnhiddenMarkers","finish","runInOp","methodOp","docMethodOp","regChange","lendiff","resetView","cut","viewCuttingPoint","cut$1","cutTop","cutBot","regLineChange","oldN","newN","countDirtyView","dirty","time","highlight","highlightWorker","Date","workTime","changedLines","oldStyles","highlighted","oldCls","newCls","ischange","workDelay","force","visible","editorIsHidden","wrapperHeight","oldDisplayWidth","viewportMargin","different","toUpdate","selSnapshot","hasFocus","anchorNode","extend","anchorOffset","focusNode","focusOffset","selectionSnapshot","updateNumbersFrom","rm","currentWheelTarget","updateNumber","patchDisplay","snapshot","removeAllRanges","addRange","restoreSelection","updateGutters","specs","gElt","setGuttersForLineNumbers","wheelSamples","wheelPixelsPerUnit","wheelEventDelta","dx","wheelDeltaX","dy","wheelDeltaY","detail","HORIZONTAL_AXIS","VERTICAL_AXIS","wheelDelta","wheelEventPixels","delta","onScrollWheel","canScrollX","canScrollY","pixels","movedX","movedY","sample","Selection","equals","there","deepCopy","Range","normalizeSelection","mayTouch","selectionsMayTouch","prim","inv","simpleSelection","changeEnd","adjustForChange","computeSelAfterChange","offsetPos","loadMode","modeOption","resetModeState","isWholeLineUpdate","wholeLineUpdateBefore","updateDoc","estimateHeight$$1","spansFor","updateLine","linesFor","lastText","lastSpans","nlines","added","added$1","added$2","linkedDocs","sharedHistOnly","propagate","skip","sharedHist","linked","rel","shared","attachDoc","setDirectionClass","History","startGen","done","undone","undoDepth","lastModTime","lastSelTime","lastOp","lastSelOp","lastOrigin","lastSelOrigin","generation","maxGeneration","historyChangeFromChange","histChange","attachLocalSpans","clearSelectionEvents","addChangeToHistory","selAfter","opId","hist","history","historyEventDelay","pushSelectionToHistory","addSelectionToHistory","clearRedo","dest","existing","removeClearedSpans","explicitlyCleared","mergeOldSpans","getOldSpans","stretched","oldCur","stretchCur","copyHistoryArray","newGroup","instantiateSel","newChanges","extendRange","posBefore","setSelection","extendSelections","heads","replaceOneSelection","setSimpleSelection","setSelectionReplaceHistory","setSelectionNoUndo","NaN","setSelectionInner","skipAtomicInSelection","reCheckSelection","mayClear","newAnchor","skipAtomic","newHead","skipAtomicInner","oldPos","atomic","near","movePos","far","cantEdit","selectAll","filterChange","canceled","cancel","makeChange","ignoreReadOnly","suppressEdits","mark","parts","mk","newParts","dfrom","dto","removeReadOnlyRanges","makeChangeInner","makeChangeSingleDoc","rebased","rebaseHist","makeChangeFromHistory","allowSelectionOnly","suppress","antiChanges","returned","v","shiftDoc","distance","removed","recomputeMaxLength","checkWidthStart","retreatFrontier","changesHandler","changeHandler","makeChangeSingleDocInEditor","assign","splitLines","rebaseHistSelSingle","rebaseHistArray","sub","ok","copied","changeLine","handle","changeType","LeafChunk","BranchChunk","removeInner","insertInner","iterN","oldHeight","remaining","leaf","maybeSpill","me","sibling","myIndex","used","LineWidget","adjustScrollWhenAboveVisible","this$1","oldH","nextMarkerId","TextMarker","cloneNode","isParent","SharedTextMarker","markTextShared","replacedWith","addToHistory","curLine","clearOnEnter","clearHistory","withOp","visual","dHeight","findSharedMarkers","findMarks","detachSharedMarkers","subMarker","nextDocId","Doc","lineSep","cleanGeneration","constructor","lineSeparator","setValue","getRange","getLineNumber","lineCount","setCursor","extendSelectionsBy","addSelection","getSelections","dup","newSel","hint","oldPrev","newPrev","computeReplacedSel","undo","redo","undoSelection","redoSelection","setExtending","getExtending","historySize","markClean","changeGeneration","forceSplit","isClean","gen","getHistory","setHistory","histData","setGutterMarker","gutterID","clearGutter","lineInfo","addLineWidget","insertAt","aboveVisible","removeLineWidget","setBookmark","realOpts","findMarksAt","getAllMarks","posFromIndex","sepSize","indexFromPos","copyHistory","linkedDoc","mFrom","mTo","subMark","copySharedMarkers","unlinkDoc","splitIds","iterLinkedDocs","getEditor","setDirection","eachLine","lastDrop","onDrop","clearDragCursor","files","dataTransfer","isReadOnly","FileReader","File","read","loadFile","file","allowDropFileTypes","reader","onload","readAsText","draggingText","text$1","getData","dragCursor","forEachCodeMirror","getElementsByClassName","byClass","editors","globalsRegistered","ensureGlobalHandlers","resizeTimer","onResize","setSize","keyNames","18","19","20","27","32","33","34","35","36","37","38","39","40","44","45","46","59","61","91","92","93","106","107","109","110","111","127","145","173","186","187","188","189","190","191","192","219","220","221","222","63232","63233","63234","63235","63272","63273","63275","63276","63277","63302","fromCharCode","keyMap","normalizeKeyName","alt","ctrl","cmd","normalizeKeyMap","keymap","keyname","lookupKey","getKeyMap","fallthrough","isModifierKey","addModifierNames","noShift","altKey","metaKey","shiftKey","keyName","altGraphKey","deleteNearSelection","compute","kill","toKill","replaced","moveCharLogically","moveLogically","endOfLine","visually","prep","targetTop","basic","Left","Right","Up","Down","End","Home","PageUp","PageDown","Delete","Backspace","Shift-Backspace","Tab","Shift-Tab","Enter","Insert","Esc","pcDefault","Ctrl-A","Ctrl-D","Ctrl-Z","Shift-Ctrl-Z","Ctrl-Y","Ctrl-Home","Ctrl-End","Ctrl-Up","Ctrl-Down","Ctrl-Left","Ctrl-Right","Alt-Left","Alt-Right","Ctrl-Backspace","Ctrl-Delete","Ctrl-S","Ctrl-F","Ctrl-G","Shift-Ctrl-G","Shift-Ctrl-F","Shift-Ctrl-R","Ctrl-[","Ctrl-]","Ctrl-U","Shift-Ctrl-U","Alt-U","emacsy","Ctrl-B","Ctrl-P","Ctrl-N","Alt-F","Alt-B","Ctrl-E","Ctrl-V","Shift-Ctrl-V","Ctrl-H","Alt-D","Alt-Backspace","Ctrl-K","Ctrl-T","Ctrl-O","macDefault","Cmd-A","Cmd-D","Cmd-Z","Shift-Cmd-Z","Cmd-Y","Cmd-Home","Cmd-Up","Cmd-End","Cmd-Down","Cmd-Left","Cmd-Right","Ctrl-Alt-Backspace","Alt-Delete","Cmd-S","Cmd-F","Cmd-G","Shift-Cmd-G","Cmd-Alt-F","Shift-Cmd-Alt-F","Cmd-[","Cmd-]","Cmd-Backspace","Cmd-Delete","Cmd-U","Shift-Cmd-U","singleSelection","killLine","deleteLine","delLineLeft","delWrappedLineLeft","delWrappedLineRight","rightPos","goDocStart","goDocEnd","goLineStart","goLineStartSmart","lineStartSmart","goLineEnd","visualLineEnd","goLineRight","goLineLeft","goLineLeftSmart","goLineUp","moveV","goLineDown","goPageUp","goPageDown","goCharLeft","moveH","goCharRight","goColumnLeft","goColumnRight","goWordLeft","goGroupRight","goGroupLeft","goWordRight","delCharBefore","deleteH","delCharAfter","delWordBefore","delWordAfter","delGroupBefore","delGroupAfter","indentAuto","indentSelection","indentMore","indentLess","insertTab","insertSoftTab","spaces","defaultTab","execCommand","transposeChars","newlineAndIndent","sels","openLine","toggleOverwrite","firstNonWS","inWS","doHandleBinding","bound","dropShift","ensurePolled","prevShift","stopSeq","dispatchKey","seq","keySeq","dispatchKeyInner","keyMaps","extraKeys","lookupKeyForEditor","handleKeyBinding","motion","lastStoppedKey","handled","up","showCrossHair","onKeyUp","onKeyPress","charCode","lastClick","lastDoubleClick","PastClick","onMouseDown","supportsTouch","clickInGutter","now","repeat","compare","selectingText","handleMappedButton","contained","behavior","unit","addNew","moveOnDrag","configureMouse","dragDrop","moved","dragEnd","mouseMove","dragStart","e2","leftButtonStartDrag","ourRange","ourIndex","startSel","rangeForUnit","lastPos","extendTo","startCol","posCol","leftPos","oldRange","ranges$1","anchorLine","boundary","headIndex","usePart","bidiSimplify","editorSize","counter","move","buttons","curCount","leftButtonSelect","leftButtonDown","onContextMenu","findWordAt","gutterEvent","prevent","mX","mY","touches","lineBox","g","themeChanged","theme","defaults","optionHandlers","guttersChanged","dragDropChanged","funcs","dragFunctions","toggle","enter","over","leave","drop","wrappingChanged","inputStyles","inputStyle","pasteIncoming","cutIncoming","autofocus","word","touchFinished","prevTouch","finishTouch","farAway","touch","radiusX","radiusY","isMouseLikeTouchEvent","pageX","pageY","frag","onDragOver","setData","effectAllowed","setDragImage","img","src","_top","onDragStart","inp","getField","registerEventHandlers","finishInit","initHooks","textRendering","how","aggressive","curSpace","curSpaceString","indentUnit","indentString","indentWithTabs","pos$1","defineInitHook","lastCopied","setLastCopied","newLastCopied","applyTextInput","inserted","deleted","paste","textLines","multiPaste","pasteLinesPerSelection","lineWise","changeEvent","triggerElectric","handlePaste","pasted","clipboardData","disableInput","electricChars","smartIndent","getModeAt","electricInput","copyableRanges","lineRange","disableBrowserMagic","spellcheck","hiddenTextarea","border","findPosH","origDir","moveOnce","boundToLine","bidi","mv","getWrappedLineExtent","moveInStorageOrder","searchInVisualLine","getRes","res","nextCh","moveVisually","sawType","getHelper","hitSide","findPosV","pageSize","moveAmount","ContentEditableInput","lastAnchorNode","lastAnchorOffset","lastFocusNode","lastFocusOffset","polling","composing","gracePeriod","readDOMTimeout","posToDOM","badPos","bad","domToPos","lineNode","locateNodeInLineView","textNode","topNode","nodeValue","curNode","textContent","previousSibling","dist$1","onCopyCut","lineWiseCopyCut","clearData","kludge","hadFocus","showPrimarySelection","updateFromDOM","readFromDOMSoon","forceCompositionEnd","showMultipleSelections","curAnchor","curFocus","rng","rangeCount","getRangeAt","startGracePeriod","rememberSelection","selectionInEditor","commonAncestorContainer","blur","pollSelection","pollInterval","poll","scan","isInGutter","triggerOnKeyDown","pollContent","fromIndex","fromNode","toNode","toIndex","newText","closing","extraLinebreak","addText","walk","cmText","markerID","isBlock","nodeName","domTextBetween","oldText","cutFront","cutEnd","oldTop","maxCutFront","newBot","oldBot","maxCutEnd","chFrom","chTo","contentEditable","readOnlyChanged","resetPosition","TextareaInput","prevInput","pollingFast","createField","textarea","prepareCopyCut","fastPoll","_display","moveInputWithCursor","headPos","wrapOff","lineOff","teTop","teLeft","drawn","contextMenuPending","slowPoll","missed","same","resetSelectionOnContextMenu","oldCSS","oldWrapperCSS","oldScrollY","wrapperBox","scrollY","scrollTo","detectingSelectAll","prepareSelectAllHack","mouseup","rehide","extval","deflt","notOnInit","newBreaks","getInputField","detach","attach","integer","defineOptions","setOption","getDoc","addOverlay","score","priority","insertSorted","modeSpec","removeOverlay","newRanges","getLineTokens","getHelpers","_global","getStateAfter","defaultTextHeight","defaultCharWidth","addWidget","vspace","hspace","triggerOnKeyPress","triggerOnKeyUp","triggerOnMouseDown","amount","rtlMoveVisually","goalColumn","goals","startChar","check","getScrollInfo","interpret","swapDoc","phrase","phraseText","phrases","getScrollerElement","getGutterElement","registerGlobalHelper","predicate","dontDelegate","method","contenteditable","defineMode","dependencies","defineMIME","mime","func","defineDocExtension","tabindex","realSubmit","leaveSubmitMethodAlone","wrappedSubmit","getTextArea","toTextArea","cmpPos","version","keySet","parserConfig","inline","propertyKeywords","tokenHooks","documentTypes","mediaTypes","mediaFeatures","mediaValueKeywords","nonStandardPropertyKeywords","fontProperties","counterDescriptors","colorKeywords","valueKeywords","allowNested","lineComment","supportsAtComponent","ret","tp","tokenString","quote","escaped","tokenize","tokenParenthesized","pushContext","popContext","pass","states","popAndPass","wordAsValue","stateArg","block","maybeprop","propBlock","_stream","parens","pseudo","atBlock","atComponentBlock","atBlock_parens","restricted_atBlock_before","restricted_atBlock","keyframes","interpolation","textAfter","blockCommentStart","blockCommentEnd","blockCommentContinue","fold","documentTypes_","mediaTypes_","mediaFeatures_","mediaValueKeywords_","propertyKeywords_","nonStandardPropertyKeywords_","colorKeywords_","valueKeywords_","allWords","tokenCComment","maybeEnd","/",":","$","#","@","&","defaultTags","script","attrRegexpCache","getAttrValue","getTagRegexp","anchored","addTags","multilineTagIndentFactor","multilineTagIndentPastTag","tags","configTags","configScript","scriptTypes","matches","htmlState","inTag","tagInfo","tagText","findMatchingMode","endTagA","endTag","localState","localMode","pat","local","../css/css","../javascript/javascript","../xml/xml","statementIndent","jsonldMode","jsonld","jsonMode","json","isTS","typescript","wordRE","wordCharacters","keywords","kw","A","B","C","D","operator","atom","if","while","with","else","do","try","finally","return","break","continue","new","delete","void","throw","debugger","var","const","let","function","catch","for","switch","case","default","in","typeof","instanceof","true","false","super","yield","export","import","extends","await","isOperatorChar","isJsonldKeyword","cont","tokenBase","tokenComment","expressionAllowed","inSet","readRegexp","tokenQuasi","lexical","lastType","propertyIsEnumerable","brackets","findFatArrow","fatArrowAt","arrow","depth","sawSomething","bracket","atomicTypes","variable","regexp","jsonld-keyword","JSLexical","inScope","varname","localVars","vars","marked","cc","inList","newContext","registerVarScoped","Var","globalVars","isModifier","defaultVars","pushcontext","pushblockcontext","popcontext","pushlex","lex","poplex","expect","wanted","exp","statement","vardef","parenExpr","maybeexpression","maybeelse","functiondef","forspec","enumdef","typeexpr","expression","maybelabel","maybeCatchBinding","afterExport","afterImport","funarg","expressionInner","expressionNoComma","noComma","arrowBodyNoComma","arrowBody","commasep","maybeop","maybeoperatorNoComma","maybeoperatorComma","classExpression","arrayLiteral","contCommasep","objprop","quasi","targetNoComma","maybeTypeArgs","expr","property","continueQuasi","_","getterSetter","afterprop","maybetype","what","sep","proceed","mayberettype","isKW","afterType","typeprop","typearg","maybeReturnType","typeparam","maybeTypeDefault","maybeAssign","vardefCont","eltpattern","proppattern","_type","forspec1","forspec2","formaybeinof","forspec3","classNameAfter","classBody","classfield","maybeFrom","exportField","importSpec","maybeMoreImports","maybeAs","enummember","basecolumn","parseJS","firstChar","doubleIndentSwitch","closeBrackets","skipExpression","21","htmlConfig","autoSelfClosers","area","br","command","embed","frame","hr","keygen","meta","param","track","wbr","menuitem","implicitlyClosed","dd","li","optgroup","rp","tbody","td","tfoot","tr","contextGrabbers","dt","address","article","aside","blockquote","dl","fieldset","footer","h1","h2","h3","h4","h5","h6","header","hgroup","menu","nav","ol","section","table","ul","thead","doNotIndent","allowUnquoted","allowMissing","caseFold","xmlConfig","allowMissingTagName","editorConf","config_","setStyle","inText","chain","parser","inBlock","doctype","closure","isInAttribute","stringStartCol","baseState","tagStart","terminator","startOfLine","noIndent","maybePopContext","nextTagName","parentTagName","tagNameState","closeTagNameState","attrState","closeState","closeStateErr","matchClosing","attrEqState","attrValueState","attrContinuedState","isInText","baseIndent","fullLine","alignCDATA","tagAfter","grabbers","skipAttribute","22","html_source","multi_parser","indent_size","indent_character","max_char","brace_style","unformatted","indent_char","current_mode","parentcount","parent1","tag_type","token_text","last_token","last_text","token_type","Utils","whitespace","single_token","extra_liners","in_array","get_content","input_char","line_char_count","indent_level","indent_string","get_contents_to","reg_match","reg_array","end_script","substring","record_tag","retrieve_tag","temp_parent","get_tag","tag_start","tag_end","get_unformatted","print_newline","tag_index","tag_complete","tag_check","comment","unindent","delimiter","orig_tag","get_token","get_full_indent","printer","js_source","ignore","print_token","tag_name","tag_extracted_from_last_output","_beautifier","js_beautify","css_beautify","indent_scripts","script_indent_level","_level","reindent","23","./stream/stream","24","guid","HALT","createStream","updateStream","_state","derive","recover","parents","endStream","unregister","ap","valueOf","toJSON","defineProperties","unregisterStream","updateState","updateDependency","finalize","mustSync","every","some","combine","fn","streams","valid","dep","notEnded","registerDependency","dependent","s1","s2","merge","s","reducer","seed","newStream","scanMerge","tuples","tuple","idx"],"mappings":"CAAA,WAAe,IAA6BA,OAASC,GAAuB,SAASC,EAAEC,EAAEC,EAAEC,GAAG,SAASC,EAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,IAAIE,GAAE,EAAoC,IAAID,GAAGC,EA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vBnB,EAAajiB,KAnCb,SAAcgkB,EAASC,EAAMpyD,GAC5B,IAAIqyD,EAAYd,EAAQ,SAAUW,GACjC,OAAOE,EAAOD,EAAQC,EAAMF,EAAE5B,OAAO9sF,QACnC,CAACw8B,IAIJ,OAF+B,IAA3BqyD,EAAU/B,OAAOhkF,OAAa+lF,EAAUD,GAErCC,GA6BRjC,EAAakC,UA1Bb,SAAmBC,EAAQH,GAC1B,IAAIX,EAAUc,EAAO5sF,IAAI,SAAS6sF,GACjC,IAAIxyD,EAASwyD,EAAM,GAEnB,OAD4B,IAAxBxyD,EAAOswD,OAAOhkF,OAAa0zB,OAAOv+B,GAC/Bu+B,IAeR,OAZgBuxD,EAAQ,WACvB,IAAIv1C,EAAUz0B,UAAUA,UAAU9kB,OAAS,GAQ3C,OANAgvF,EAAQnkF,QAAQ,SAAS0yB,EAAQyyD,IACD,EAA3Bz2C,EAAQjtC,QAAQixB,KACnBoyD,EAAOG,EAAOE,GAAK,GAAGL,EAAMpyD,EAAOswD,OAAO9sF,UAIrC4uF,GACLX,IAUJrB,EAAaD,KAAOA,OAEE,IAAXvtF,EAAwBA,EAAgB,QAAIwtF,EAC1B,mBAAbtlF,OAAOjI,GAAsB,WAAYiI,OAAOjI,EAC3DiI,OAAOjI,EAAI,CAACm9B,OAASowD,GAD0CtlF,OAAOjI,EAAEm9B,OAASowD,EA5JrF,IAiKC,KAAK,GAAG,CAAC,KA16cX","file":"forms-admin.min.js","sourcesContent":["(function () { var require = undefined; var define = undefined; (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i field\n   * @param config\n   * @returns {*}\n   */\n\n  generators.select = function (config) {\n    var attributes = {\n      name: config.name(),\n      required: config.required()\n    };\n    var hasSelection = false;\n    var options = config.choices().map(function (choice) {\n      if (choice.selected()) {\n        hasSelection = true;\n      }\n\n      return m('option', {\n        value: choice.value() !== choice.label() ? choice.value() : undefined,\n        \"selected\": choice.selected(),\n        oncreate: setAttributes\n      }, choice.label());\n    });\n    var placeholder = config.placeholder();\n\n    if (placeholder.length > 0) {\n      options.unshift(m('option', {\n        'disabled': true,\n        'value': '',\n        'selected': !hasSelection,\n        oncreate: setAttributes\n      }, placeholder));\n    }\n\n    return m('select', attributes, options);\n  };\n\n  generators['terms-checkbox'] = function (config) {\n    var label;\n\n    if (config.link().length > 0) {\n      label = m('a', {\n        href: config.link(),\n        target: \"_blank\"\n      }, config.label());\n    } else {\n      label = config.label();\n    }\n\n    return m('label', [m('input', {\n      name: config.name(),\n      type: 'checkbox',\n      value: config.value(),\n      required: config.required()\n    }), ' ', label]);\n  };\n  /**\n   * Generates a checkbox or radio type input field.\n   *\n   * @param config\n   * @returns {*}\n   */\n\n\n  generators.checkbox = function (config) {\n    var fields = config.choices().map(function (choice) {\n      var name = config.name() + (config.type() === 'checkbox' ? '[]' : '');\n      var required = config.required() && config.type() === 'radio';\n      return m('label', [m('input', {\n        name: name,\n        type: config.type(),\n        value: choice.value(),\n        checked: choice.selected(),\n        required: required,\n        oncreate: setAttributes\n      }), ' ', m('span', choice.label())]);\n    });\n    return fields;\n  };\n\n  generators.radio = generators.checkbox;\n  /**\n   * Generates a default field\n   *\n   * - text, url, number, email, date\n   *\n   * @param config\n   * @returns {*}\n   */\n\n  generators['default'] = function (config) {\n    var attributes = {\n      type: config.type()\n    };\n\n    if (config.name()) {\n      attributes.name = config.name();\n    }\n\n    if (config.min()) {\n      attributes.min = config.min();\n    }\n\n    if (config.max()) {\n      attributes.max = config.max();\n    }\n\n    if (config.value().length > 0) {\n      attributes.value = config.value();\n    }\n\n    if (config.placeholder().length > 0) {\n      attributes.placeholder = config.placeholder();\n    }\n\n    attributes.required = config.required();\n    attributes.oncreate = setAttributes;\n    return m('input', attributes);\n  };\n  /**\n   * Generates an HTML string based on a field (config) object\n   *\n   * @param config\n   * @returns {*}\n   */\n\n\n  function generate(config) {\n    var label,\n        field,\n        htmlTemplate,\n        html,\n        vdom = document.createElement('div');\n    label = config.label().length > 0 && config.showLabel() ? m(\"label\", {}, config.label()) : '';\n    field = typeof generators[config.type()] === \"function\" ? generators[config.type()](config) : generators['default'](config);\n    htmlTemplate = config.wrap() ? m('p', [label, field]) : [label, field]; // render in vdom\n\n    m.render(vdom, htmlTemplate); // prettify html\n\n    html = htmlutil.prettyPrint(vdom.innerHTML);\n    return html + \"\\n\";\n  }\n\n  return generate;\n};\n\nmodule.exports = g;\n\n},{\"html\":22}],4:[function(require,module,exports){\n\"use strict\";\n\nvar FieldHelper = function FieldHelper(m, tabs, editor, fields, events, i18n) {\n  'use strict';\n\n  var generate = require('./field-generator.js')(m);\n\n  var overlay = require('../overlay.js')(m, i18n);\n\n  var forms = require('./field-forms.js')(m, i18n);\n\n  var fieldConfig;\n  editor.on('blur', m.redraw);\n  /**\n   * Choose a field to open the helper form for\n   *\n   * @param index\n   * @returns {*}\n   */\n\n  function setActiveField(index) {\n    fieldConfig = fields.get(index); // if this hidden field has choices (hidden groups), glue them together by their label.\n\n    if (fieldConfig && fieldConfig.choices().length > 0) {\n      fieldConfig.value(fieldConfig.choices().map(function (c) {\n        return c.label();\n      }).join('|'));\n    }\n\n    m.redraw();\n  }\n  /**\n   * Controller\n   */\n\n\n  function controller() {}\n  /**\n   * Create HTML based on current config object\n   */\n\n\n  function createFieldHTMLAndAddToForm() {\n    // generate html\n    var html = generate(fieldConfig); // add to editor\n\n    editor.insert(html); // reset field form\n\n    setActiveField(''); // redraw\n\n    m.redraw();\n  }\n  /**\n   * View\n   * @returns {*}\n   */\n\n\n  function view() {\n    // build DOM for fields choice\n    var fieldCategories = fields.getCategories();\n    var availableFields = fields.getAll();\n    var fieldsChoice = m(\"div.available-fields.small-margin\", [m(\"h4\", i18n.chooseField), fieldCategories.map(function (category) {\n      var categoryFields = availableFields.filter(function (f) {\n        return f.category === category;\n      });\n\n      if (!categoryFields.length) {\n        return;\n      }\n\n      return m(\"div.tiny-margin\", [m(\"strong\", category), // render fields\n      categoryFields.map(function (field) {\n        var className = \"button\";\n\n        if (field.forceRequired()) {\n          className += \" is-required\";\n        }\n\n        var inForm = field.inFormContent();\n\n        if (inForm !== null) {\n          className += \" \" + (inForm ? 'in-form' : 'not-in-form');\n        }\n\n        return m(\"button\", {\n          className: className,\n          type: 'button',\n          onclick: m.withAttr(\"value\", setActiveField),\n          value: field.index\n        }, field.title());\n      })]);\n    })]); // build DOM for overlay\n\n    var form = null;\n\n    if (fieldConfig) {\n      form = m(overlay( // field wizard\n      m(\"div.field-wizard\", [//heading\n      m(\"h3\", [fieldConfig.title(), fieldConfig.forceRequired() ? m('span.red', '*') : '', fieldConfig.name().length ? m(\"code\", fieldConfig.name()) : '']), // help text\n      fieldConfig.help().length ? m('p', m.trust(fieldConfig.help())) : '', // actual form\n      forms.render(fieldConfig), // add to form button\n      m(\"p\", [m(\"button\", {\n        \"class\": \"button-primary\",\n        type: \"button\",\n        onkeydown: function onkeydown(e) {\n          e = e || window.event;\n\n          if (e.keyCode == 13) {\n            createFieldHTMLAndAddToForm();\n          }\n        },\n        onclick: createFieldHTMLAndAddToForm\n      }, i18n.addToForm)])]), setActiveField));\n    }\n\n    return [fieldsChoice, form];\n  } // expose some variables\n\n\n  return {\n    view: view,\n    controller: controller\n  };\n};\n\nmodule.exports = FieldHelper;\n\n},{\"../overlay.js\":10,\"./field-forms.js\":2,\"./field-generator.js\":3}],5:[function(require,module,exports){\n\"use strict\";\n\nvar FieldFactory = function FieldFactory(fields, i18n) {\n  'use strict';\n  /**\n   * Array of registered fields\n   *\n   * @type {Array}\n   */\n\n  var registeredFields = [];\n  /**\n   * Reset all previously registered fields\n   */\n\n  function reset() {\n    // clear all of our fields\n    registeredFields.forEach(fields.deregister);\n  }\n  /**\n   * Helper function to quickly register a field and store it in local scope\n   *\n   * @param {object} data\n   * @param {boolean} sticky\n   */\n\n\n  function register(category, data, sticky) {\n    var field = fields.register(category, data);\n\n    if (!sticky) {\n      registeredFields.push(field);\n    }\n  }\n  /**\n   * Normalizes the field type which is passed by Newsletter\n   *\n   * @param type\n   * @returns {*}\n   */\n\n\n  function getFieldType(type) {\n    var map = {\n      'phone': 'tel',\n      'dropdown': 'select',\n      'checkboxes': 'checkbox',\n      'birthday': 'text'\n    };\n    return typeof map[type] !== \"undefined\" ? map[type] : type;\n  }\n  /**\n   * Register the various fields for a merge var\n   *\n   * @param mergeField\n   * @returns {boolean}\n   */\n\n\n  function registerMergeField(mergeField) {\n    var category = i18n.listFields;\n    var fieldType = getFieldType(mergeField.field_type); // name, type, title, value, required, label, placeholder, choices, wrap\n\n    var data = {\n      name: mergeField.tag,\n      title: mergeField.name,\n      required: mergeField.required,\n      forceRequired: mergeField.required,\n      type: fieldType,\n      choices: mergeField.choices,\n      acceptsMultipleValues: false // merge fields never accept multiple values.\n\n    };\n\n    if (data.type !== 'address') {\n      register(category, data, false);\n    } else {\n      register(category, {\n        name: data.name + '[addr1]',\n        type: 'text',\n        newsletterType: 'address',\n        title: i18n.streetAddress\n      });\n      register(category, {\n        name: data.name + '[city]',\n        type: 'text',\n        newsletterType: 'address',\n        title: i18n.city\n      });\n      register(category, {\n        name: data.name + '[state]',\n        type: 'text',\n        newsletterType: 'address',\n        title: i18n.state\n      });\n      register(category, {\n        name: data.name + '[zip]',\n        type: 'text',\n        newsletterType: 'address',\n        title: i18n.zip\n      });\n      register(category, {\n        name: data.name + '[country]',\n        type: 'select',\n        newsletterType: 'address',\n        title: i18n.country,\n        choices: nl4wp_vars.countries\n      });\n    }\n\n    return true;\n  }\n  /**\n   * Register a field for a Newsletter grouping\n   *\n   * @param interestCategory\n   */\n\n\n  function registerInterestCategory(interestCategory) {\n    var category = i18n.interestCategories;\n    var fieldType = getFieldType(interestCategory.field_type);\n    var data = {\n      title: interestCategory.name,\n      name: 'INTERESTS[' + interestCategory.id + ']',\n      type: fieldType,\n      choices: interestCategory.interests,\n      acceptsMultipleValues: fieldType === 'checkbox'\n    };\n    register(category, data, false);\n  }\n  /**\n   * Register all fields belonging to a list\n   *\n   * @param list\n   */\n\n\n  function registerListFields(list) {\n    // make sure EMAIL && public fields come first\n    list.merge_fields = list.merge_fields.sort(function (a, b) {\n      if (a.tag === 'EMAIL' || a.public && !b.public) {\n        return -1;\n      }\n\n      if (!a.public && b.public) {\n        return 1;\n      }\n\n      return 0;\n    }); // loop through merge vars\n\n    list.merge_fields.forEach(registerMergeField); // loop through groupings\n\n    list.interest_categories.forEach(registerInterestCategory);\n  }\n  /**\n   * Register all lists fields\n   *\n   * @param lists\n   */\n\n\n  function registerListsFields(lists) {\n    reset();\n    lists.forEach(registerListFields);\n  }\n\n  function registerCustomFields(lists) {\n    var choices,\n        category = i18n.formFields; // register submit button\n\n    register(category, {\n      name: '',\n      value: i18n.subscribe,\n      type: \"submit\",\n      title: i18n.submitButton\n    }, true); // register lists choice field\n\n    choices = {};\n\n    for (var key in lists) {\n      choices[lists[key].id] = lists[key].name;\n    }\n\n    register(category, {\n      name: '_nl4wp_lists',\n      type: 'checkbox',\n      title: i18n.listChoice,\n      choices: choices,\n      help: i18n.listChoiceDescription,\n      acceptsMultipleValues: true\n    }, true);\n    choices = {\n      'subscribe': \"Subscribe\",\n      'unsubscribe': \"Unsubscribe\"\n    };\n    register(category, {\n      name: '_nl4wp_action',\n      type: 'radio',\n      title: i18n.formAction,\n      choices: choices,\n      value: 'subscribe',\n      help: i18n.formActionDescription\n    }, true);\n    register(category, {\n      name: 'AGREE_TO_TERMS',\n      value: 1,\n      type: \"terms-checkbox\",\n      label: i18n.agreeToTerms,\n      title: i18n.agreeToTermsShort,\n      showLabel: false,\n      required: true\n    }, true);\n  }\n  /**\n   * Expose some methods\n   */\n\n\n  return {\n    'registerCustomFields': registerCustomFields,\n    'registerListFields': registerListFields,\n    'registerListsFields': registerListsFields\n  };\n};\n\nmodule.exports = FieldFactory;\n\n},{}],6:[function(require,module,exports){\n'use strict';\n\nvar prop = require(\"mithril/stream\");\n\nmodule.exports = function (m, events) {\n  var timeout;\n  var fields = [];\n  var categories = [];\n  /**\n   * @internal\n   *\n   *\n   * @param data\n   * @constructor\n   */\n\n  var Field = function Field(data) {\n    this.name = prop(data.name);\n    this.title = prop(data.title || data.name);\n    this.type = prop(data.type);\n    this.newsletterType = prop(data.newsletterType || '');\n    this.label = prop(data.label || data.title || '');\n    this.showLabel = prop(data.showLabel !== undefined ? data.showLabel : true);\n    this.value = prop(data.value || '');\n    this.placeholder = prop(data.placeholder || '');\n    this.required = prop(data.required || false);\n    this.forceRequired = prop(data.forceRequired || false);\n    this.wrap = prop(data.wrap !== undefined ? data.wrap : true);\n    this.min = prop(data.min || null);\n    this.max = prop(data.max || null);\n    this.help = prop(data.help || '');\n    this.choices = prop(data.choices || []);\n    this.inFormContent = prop(null);\n    this.acceptsMultipleValues = data.acceptsMultipleValues;\n    this.link = prop(data.link || '');\n\n    this.selectChoice = function (value) {\n      var field = this;\n      this.choices(this.choices().map(function (choice) {\n        if (choice.value() === value) {\n          choice.selected(true);\n        } else {\n          // only checkboxes allow for multiple selections\n          if (field.type() !== 'checkbox') {\n            choice.selected(false);\n          }\n        }\n\n        return choice;\n      }));\n    };\n  };\n  /**\n   * @internal\n   *\n   * @param data\n   * @constructor\n   */\n\n\n  var FieldChoice = function FieldChoice(data) {\n    this.label = prop(data.label);\n    this.title = prop(data.title || data.label);\n    this.selected = prop(data.selected || false);\n    this.value = prop(data.value || data.label);\n  };\n  /**\n   * Creates FieldChoice objects from an (associative) array of data objects\n   *\n   * @param data\n   * @returns {Array}\n   */\n\n\n  function createChoices(data) {\n    var choices = [];\n\n    if (typeof data.map === \"function\") {\n      choices = data.map(function (choiceLabel) {\n        return new FieldChoice({\n          label: choiceLabel\n        });\n      });\n    } else {\n      choices = Object.keys(data).map(function (key) {\n        var choiceLabel = data[key];\n        return new FieldChoice({\n          label: choiceLabel,\n          value: key\n        });\n      });\n    }\n\n    return choices;\n  }\n  /**\n   * Factory method\n   *\n   * @api\n   *\n   * @param data\n   * @returns {Field}\n   */\n\n\n  function register(category, data) {\n    var field;\n    var existingField = getAllWhere('name', data.name).shift(); // a field with the same \"name\" already exists\n\n    if (existingField) {\n      // update \"required\" status\n      if (!existingField.forceRequired() && data.forceRequired) {\n        existingField.forceRequired(true);\n      } // bail\n\n\n      return undefined;\n    } // array of choices given? convert to FieldChoice objects\n\n\n    if (data.choices) {\n      data.choices = createChoices(data.choices);\n\n      if (data.value) {\n        data.choices = data.choices.map(function (choice) {\n          if (choice.value() === data.value) {\n            choice.selected(true);\n          }\n\n          return choice;\n        });\n      }\n    } // register category\n\n\n    if (categories.indexOf(category) < 0) {\n      categories.push(category);\n    } // create Field object\n\n\n    field = new Field(data);\n    field.category = category; // add to array\n\n    fields.push(field); // redraw view\n\n    timeout && window.clearTimeout(timeout);\n    timeout = window.setTimeout(m.redraw, 200); // trigger event\n\n    events.trigger('fields.change');\n    return field;\n  }\n  /**\n   * @api\n   *\n   * @param field\n   */\n\n\n  function deregister(field) {\n    var index = fields.indexOf(field);\n\n    if (index > -1) {\n      delete fields[index];\n      m.redraw();\n    }\n  }\n  /**\n   * Get a field config object\n   *\n   * @param name\n   * @returns {*}\n   */\n\n\n  function get(name) {\n    return fields[name];\n  }\n  /**\n   * Get all field config objects\n   *\n   * @returns {Array|*}\n   */\n\n\n  function getAll() {\n    // rebuild index property on all fields\n    fields = fields.map(function (f, i) {\n      f.index = i;\n      return f;\n    });\n    return fields;\n  }\n\n  function getCategories() {\n    return categories;\n  }\n  /**\n   * Get all fields where a property matches the given value\n   *\n   * @param searchKey\n   * @param searchValue\n   * @returns {Array|*}\n   */\n\n\n  function getAllWhere(searchKey, searchValue) {\n    return fields.filter(function (field) {\n      return field[searchKey]() === searchValue;\n    });\n  }\n  /**\n   * Exposed methods\n   */\n\n\n  return {\n    'get': get,\n    'getAll': getAll,\n    'getCategories': getCategories,\n    'deregister': deregister,\n    'register': register,\n    'getAllWhere': getAllWhere\n  };\n};\n\n},{\"mithril/stream\":23}],7:[function(require,module,exports){\n'use strict'; // load CodeMirror & plugins\n\nvar CodeMirror = require('codemirror');\n\nrequire('codemirror/mode/xml/xml');\n\nrequire('codemirror/mode/javascript/javascript');\n\nrequire('codemirror/mode/css/css');\n\nrequire('codemirror/mode/htmlmixed/htmlmixed');\n\nrequire('codemirror/addon/fold/xml-fold.js');\n\nrequire('codemirror/addon/edit/matchtags.js');\n\nrequire('codemirror/addon/edit/closetag.js');\n\nrequire('codemirror/addon/selection/active-line.js');\n\nrequire('codemirror/addon/edit/matchbrackets.js');\n/* variables */\n\n\nvar FormEditor = {};\n\nvar _dom = document.createElement('form');\n\nvar domDirty = false;\nvar editor;\nvar element = document.getElementById('nl4wp-form-content');\nvar previewFrame = document.getElementById('nl4wp-form-preview');\nvar previewDom;\nvar templateRegex = /\\{[^{}]+\\}/g;\n/* functions */\n\nfunction setPreviewDom() {\n  var frameContent = previewFrame.contentDocument || previewFrame.contentWindow.document;\n  previewDom = frameContent.querySelector('.nl4wp-form-fields');\n\n  if (previewDom) {\n    updatePreview();\n  }\n}\n\nfunction updatePreview() {\n  var markup = FormEditor.getValue(); // replace template tags (twice, to allow for nested tags)\n\n  markup = markup.replace(templateRegex, '').replace(templateRegex, ''); // update dom\n\n  previewDom.innerHTML = markup;\n  previewDom.dispatchEvent(new Event('nl4wp-refresh'));\n}\n\nwindow.addEventListener('load', function () {\n  CodeMirror.signal(editor, \"change\");\n}); // set domDirty to true everytime the \"change\" event fires (a lot..)\n\nelement.addEventListener('change', function () {\n  domDirty = true;\n  updatePreview();\n});\n\nfunction dom() {\n  if (domDirty) {\n    _dom.innerHTML = FormEditor.getValue().toLowerCase();\n    domDirty = false;\n  }\n\n  return _dom;\n}\n\nFormEditor.getValue = function () {\n  return editor ? editor.getValue() : element.value;\n};\n\nFormEditor.query = function (query) {\n  return dom().querySelectorAll(query.toLowerCase());\n};\n\nFormEditor.containsField = function (fieldName) {\n  return dom().elements.namedItem(fieldName.toLowerCase()) !== null;\n};\n\nFormEditor.insert = function (html) {\n  if (editor) {\n    editor.replaceSelection(html);\n    editor.focus();\n  } else {\n    element.value += html;\n  }\n};\n\nFormEditor.on = function (event, callback) {\n  if (editor) {\n    // translate \"input\" event for CodeMirror\n    event = event === 'input' ? 'changes' : event;\n    return editor.on(event, callback);\n  }\n\n  return element.addEventListener(event, callback);\n};\n\nFormEditor.refresh = function () {\n  editor && editor.refresh();\n};\n/* bootstrap */\n\n\n_dom.innerHTML = element.value.toLowerCase();\n\nif (CodeMirror) {\n  editor = CodeMirror.fromTextArea(element, {\n    selectionPointer: true,\n    mode: \"htmlmixed\",\n    htmlMode: true,\n    autoCloseTags: true,\n    autoRefresh: true,\n    styleActiveLine: true,\n    matchBrackets: true,\n    matchTags: {\n      bothTags: true\n    }\n  }); // dispatch regular \"change\" on element event every time editor changes (IE9+ only)\n\n  window.dispatchEvent && editor.on('change', function () {\n    if (typeof Event === \"function\") {\n      // Create a new 'change' event\n      var event = new Event('change', {\n        bubbles: true\n      });\n      element.dispatchEvent(event);\n    }\n  });\n}\n\npreviewFrame.addEventListener('load', setPreviewDom);\nsetPreviewDom.call();\n/* exports */\n\nmodule.exports = FormEditor;\n\n},{\"codemirror\":17,\"codemirror/addon/edit/closetag.js\":12,\"codemirror/addon/edit/matchbrackets.js\":13,\"codemirror/addon/edit/matchtags.js\":14,\"codemirror/addon/fold/xml-fold.js\":15,\"codemirror/addon/selection/active-line.js\":16,\"codemirror/mode/css/css\":18,\"codemirror/mode/htmlmixed/htmlmixed\":19,\"codemirror/mode/javascript/javascript\":20,\"codemirror/mode/xml/xml\":21}],8:[function(require,module,exports){\n\"use strict\";\n\nvar FormWatcher = function FormWatcher(m, editor, settings, fields, events, helpers) {\n  'use strict';\n\n  var requiredFieldsInput = document.getElementById('required-fields');\n\n  function updateFields() {\n    fields.getAll().forEach(function (field) {\n      // don't run for empty field names\n      if (field.name().length <= 0) return;\n      var fieldName = field.name();\n\n      if (field.type() === 'checkbox') {\n        fieldName += '[]';\n      }\n\n      var inForm = editor.containsField(fieldName);\n      field.inFormContent(inForm); // if form contains 1 address field of group, mark all fields in this group as \"required\"\n\n      if (field.newsletterType() === 'address') {\n        field.originalRequiredValue = field.originalRequiredValue === undefined ? field.forceRequired() : field.originalRequiredValue; // query other fields for this address group\n\n        var nameGroup = field.name().replace(/\\[(\\w+)\\]/g, '');\n\n        if (editor.query('[name^=\"' + nameGroup + '\"]').length > 0) {\n          if (field.originalRequiredValue === undefined) {\n            field.originalRequiredValue = field.forceRequired();\n          }\n\n          field.forceRequired(true);\n        } else {\n          field.forceRequired(field.originalRequiredValue);\n        }\n      }\n    });\n    findRequiredFields();\n    m.redraw();\n  }\n\n  function findRequiredFields() {\n    // query fields required by Newsletter\n    var requiredFields = fields.getAllWhere('forceRequired', true).map(function (f) {\n      return f.name().toUpperCase().replace(/\\[(\\w+)\\]/g, '.$1');\n    }); // query fields in form with [required] attribute\n\n    var requiredFieldElements = editor.query('[required]');\n    Array.prototype.forEach.call(requiredFieldElements, function (el) {\n      var name = el.name; // bail if name attr empty or starts with underscore\n\n      if (!name || name.length < 0 || name[0] === '_') {\n        return;\n      } // replace array brackets with dot style notation\n\n\n      name = name.replace(/\\[(\\w+)\\]/g, '.$1'); // replace array-style fields\n\n      name = name.replace(/\\[\\]$/, ''); // uppercase everything before the .\n\n      var pos = name.indexOf('.');\n      pos = pos > 0 ? pos : name.length;\n      name = name.substr(0, pos).toUpperCase() + name.substr(pos); // only add field if it's not already in it\n\n      if (requiredFields.indexOf(name) === -1) {\n        requiredFields.push(name);\n      }\n    }); // update meta\n\n    requiredFieldsInput.value = requiredFields.join(',');\n  } // events\n\n\n  editor.on('change', helpers.debounce(updateFields, 500));\n  events.on('fields.change', helpers.debounce(updateFields, 500));\n};\n\nmodule.exports = FormWatcher;\n\n},{}],9:[function(require,module,exports){\n'use strict';\n\nvar notices = {};\n\nfunction show(id, text) {\n  notices[id] = text;\n  render();\n}\n\nfunction hide(id) {\n  delete notices[id];\n  render();\n}\n\nfunction render() {\n  var html = '';\n\n  for (var key in notices) {\n    html += '

' + notices[key] + '

';\n }\n\n var container = document.querySelector('.nl4wp-notices');\n\n if (!container) {\n container = document.createElement('div');\n container.className = 'nl4wp-notices';\n var heading = document.querySelector('h1, h2');\n heading.parentNode.insertBefore(container, heading.nextSibling);\n }\n\n container.innerHTML = html;\n}\n\nfunction init(editor, fields) {\n var groupingsNotice = function groupingsNotice() {\n var text = \"Your form contains old style GROUPINGS fields.

Please remove these fields from your form and then re-add them through the available field buttons to make sure your data is getting through to Newsletter correctly.\";\n var formCode = editor.getValue().toLowerCase();\n formCode.indexOf('name=\"groupings') > -1 ? show('deprecated_groupings', text) : hide('deprecated_groupings');\n };\n\n var requiredFieldsNotice = function requiredFieldsNotice() {\n var requiredFields = fields.getAllWhere('forceRequired', true);\n var missingFields = requiredFields.filter(function (f) {\n return !editor.containsField(f.name().toUpperCase());\n });\n var text = 'Heads up! Your form is missing list fields that are required in Newsletter. Either add these fields to your form or mark them as optional in Newsletter.';\n text += \"
  • \" + missingFields.map(function (f) {\n return f.title();\n }).join('
  • ') + '
';\n missingFields.length > 0 ? show('required_fields_missing', text) : hide('required_fields_missing');\n }; // old groupings\n\n\n groupingsNotice();\n editor.on('focus', groupingsNotice);\n editor.on('blur', groupingsNotice); // missing required fields\n\n requiredFieldsNotice();\n editor.on('blur', requiredFieldsNotice);\n editor.on('focus', requiredFieldsNotice);\n}\n\nmodule.exports = {\n \"init\": init\n};\n\n},{}],10:[function(require,module,exports){\n\"use strict\";\n\nvar overlay = function overlay(m, i18n) {\n 'use strict';\n\n var _element, _onCloseCallback;\n\n function close() {\n document.removeEventListener('keydown', onKeyDown);\n window.removeEventListener('resize', position);\n\n _onCloseCallback();\n }\n\n function onKeyDown(e) {\n e = e || window.event; // close overlay when pressing ESC\n\n if (e.keyCode == 27) {\n close();\n } // prevent ENTER\n\n\n if (e.keyCode == 13) {\n e.preventDefault();\n }\n }\n\n function position() {\n if (!_element) return; // fix for window width in IE8\n\n var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;\n var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;\n var marginLeft = (windowWidth - _element.clientWidth - 40) / 2;\n var marginTop = (windowHeight - _element.clientHeight - 40) / 2;\n _element.style.left = (marginLeft > 0 ? marginLeft : 0) + \"px\";\n _element.style.top = (marginTop > 0 ? marginTop : 0) + \"px\";\n }\n\n function storeElementReference(vnode) {\n _element = vnode.dom;\n position();\n }\n\n return function (content, onCloseCallback) {\n _onCloseCallback = onCloseCallback;\n return {\n oncreate: function oncreate() {\n document.addEventListener('keydown', onKeyDown);\n window.addEventListener('resize', position);\n },\n onremove: function onremove() {\n document.removeEventListener('keydown', onKeyDown);\n window.removeEventListener('resize', position);\n },\n view: function view() {\n return [m('div.overlay-wrap', m(\"div.overlay\", {\n oncreate: storeElementReference\n }, [// close icon\n m('span', {\n \"class\": 'close dashicons dashicons-no',\n title: i18n.close,\n onclick: close\n }), content])), m('div.overlay-background', {\n title: i18n.close,\n onclick: close\n })];\n }\n };\n };\n};\n\nmodule.exports = overlay;\n\n},{}],11:[function(require,module,exports){\n'use strict'; // deps\n\nvar i18n = window.nl4wp_forms_i18n;\nvar m = window.nl4wp.deps.mithril;\nvar events = nl4wp.events;\nvar settings = nl4wp.settings;\nvar helpers = nl4wp.helpers;\nvar tabs = nl4wp.tabs;\n\nvar FormWatcher = require('./admin/form-editor/form-watcher.js');\n\nvar FormEditor = require('./admin/form-editor/form-editor.js');\n\nvar FieldHelper = require('./admin/form-editor/field-helper.js');\n\nvar FieldsFactory = require('./admin/form-editor/fields-factory.js');\n\nvar fields = require('./admin/form-editor/fields.js')(m, events); // vars\n\n\nvar editor = window.formEditor = FormEditor;\nvar watcher = new FormWatcher(m, formEditor, settings, fields, events, helpers);\nvar fieldHelper = new FieldHelper(m, tabs, formEditor, fields, events, i18n);\n\nvar notices = require('./admin/notices'); // mount field helper on element\n\n\nm.mount(document.getElementById('nl4wp-field-wizard'), fieldHelper); // register fields and redraw screen in 2 seconds (fixes IE8 bug)\n\nvar fieldsFactory = new FieldsFactory(fields, i18n);\nevents.on('selectedLists.change', fieldsFactory.registerListsFields);\nfieldsFactory.registerListsFields(settings.getSelectedLists());\nfieldsFactory.registerCustomFields(nl4wp_vars.newsletter.lists);\nwindow.setTimeout(function () {\n m.redraw();\n}, 2000); // init notices\n\nnotices.init(editor, fields); // expose some methods\n\nwindow.nl4wp = window.nl4wp || {};\nwindow.nl4wp.forms = window.nl4wp.forms || {};\nwindow.nl4wp.forms.editor = editor;\nwindow.nl4wp.forms.fields = fields;\n\n},{\"./admin/form-editor/field-helper.js\":4,\"./admin/form-editor/fields-factory.js\":5,\"./admin/form-editor/fields.js\":6,\"./admin/form-editor/form-editor.js\":7,\"./admin/form-editor/form-watcher.js\":8,\"./admin/notices\":9}],12:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n/**\n * Tag-closer extension for CodeMirror.\n *\n * This extension adds an \"autoCloseTags\" option that can be set to\n * either true to get the default behavior, or an object to further\n * configure its behavior.\n *\n * These are supported options:\n *\n * `whenClosing` (default true)\n * Whether to autoclose when the '/' of a closing tag is typed.\n * `whenOpening` (default true)\n * Whether to autoclose the tag when the final '>' of an opening\n * tag is typed.\n * `dontCloseTags` (default is empty tags for HTML, none for XML)\n * An array of tag names that should not be autoclosed.\n * `indentTags` (default is block tags for HTML, none for XML)\n * An array of tag names that should, when opened, cause a\n * blank line to be added inside the tag, and the blank line and\n * closing line to be indented.\n *\n * See demos/closetag.html for a usage example.\n */\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"), require(\"../fold/xml-fold\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\", \"../fold/xml-fold\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n CodeMirror.defineOption(\"autoCloseTags\", false, function(cm, val, old) {\n if (old != CodeMirror.Init && old)\n cm.removeKeyMap(\"autoCloseTags\");\n if (!val) return;\n var map = {name: \"autoCloseTags\"};\n if (typeof val != \"object\" || val.whenClosing)\n map[\"'/'\"] = function(cm) { return autoCloseSlash(cm); };\n if (typeof val != \"object\" || val.whenOpening)\n map[\"'>'\"] = function(cm) { return autoCloseGT(cm); };\n cm.addKeyMap(map);\n });\n\n var htmlDontClose = [\"area\", \"base\", \"br\", \"col\", \"command\", \"embed\", \"hr\", \"img\", \"input\", \"keygen\", \"link\", \"meta\", \"param\",\n \"source\", \"track\", \"wbr\"];\n var htmlIndent = [\"applet\", \"blockquote\", \"body\", \"button\", \"div\", \"dl\", \"fieldset\", \"form\", \"frameset\", \"h1\", \"h2\", \"h3\", \"h4\",\n \"h5\", \"h6\", \"head\", \"html\", \"iframe\", \"layer\", \"legend\", \"object\", \"ol\", \"p\", \"select\", \"table\", \"ul\"];\n\n function autoCloseGT(cm) {\n if (cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n var ranges = cm.listSelections(), replacements = [];\n var opt = cm.getOption(\"autoCloseTags\");\n for (var i = 0; i < ranges.length; i++) {\n if (!ranges[i].empty()) return CodeMirror.Pass;\n var pos = ranges[i].head, tok = cm.getTokenAt(pos);\n var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;\n if (inner.mode.name != \"xml\" || !state.tagName) return CodeMirror.Pass;\n\n var html = inner.mode.configuration == \"html\";\n var dontCloseTags = (typeof opt == \"object\" && opt.dontCloseTags) || (html && htmlDontClose);\n var indentTags = (typeof opt == \"object\" && opt.indentTags) || (html && htmlIndent);\n\n var tagName = state.tagName;\n if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);\n var lowerTagName = tagName.toLowerCase();\n // Don't process the '>' at the end of an end-tag or self-closing tag\n if (!tagName ||\n tok.type == \"string\" && (tok.end != pos.ch || !/[\\\"\\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||\n tok.type == \"tag\" && state.type == \"closeTag\" ||\n tok.string.indexOf(\"/\") == (tok.string.length - 1) || // match something like \n dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||\n closingTagExists(cm, tagName, pos, state, true))\n return CodeMirror.Pass;\n\n var indent = indentTags && indexOf(indentTags, lowerTagName) > -1;\n replacements[i] = {indent: indent,\n text: \">\" + (indent ? \"\\n\\n\" : \"\") + \"\",\n newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)};\n }\n\n var dontIndentOnAutoClose = (typeof opt == \"object\" && opt.dontIndentOnAutoClose);\n for (var i = ranges.length - 1; i >= 0; i--) {\n var info = replacements[i];\n cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, \"+insert\");\n var sel = cm.listSelections().slice(0);\n sel[i] = {head: info.newPos, anchor: info.newPos};\n cm.setSelections(sel);\n if (!dontIndentOnAutoClose && info.indent) {\n cm.indentLine(info.newPos.line, null, true);\n cm.indentLine(info.newPos.line + 1, null, true);\n }\n }\n }\n\n function autoCloseCurrent(cm, typingSlash) {\n var ranges = cm.listSelections(), replacements = [];\n var head = typingSlash ? \"/\" : \"\") replacement += \">\";\n replacements[i] = replacement;\n }\n cm.replaceSelections(replacements);\n ranges = cm.listSelections();\n if (!dontIndentOnAutoClose) {\n for (var i = 0; i < ranges.length; i++)\n if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line)\n cm.indentLine(ranges[i].head.line);\n }\n }\n\n function autoCloseSlash(cm) {\n if (cm.getOption(\"disableInput\")) return CodeMirror.Pass;\n return autoCloseCurrent(cm, true);\n }\n\n CodeMirror.commands.closeTag = function(cm) { return autoCloseCurrent(cm); };\n\n function indexOf(collection, elt) {\n if (collection.indexOf) return collection.indexOf(elt);\n for (var i = 0, e = collection.length; i < e; ++i)\n if (collection[i] == elt) return i;\n return -1;\n }\n\n // If xml-fold is loaded, we use its functionality to try and verify\n // whether a given tag is actually unclosed.\n function closingTagExists(cm, tagName, pos, state, newTag) {\n if (!CodeMirror.scanForClosingTag) return false;\n var end = Math.min(cm.lastLine() + 1, pos.line + 500);\n var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);\n if (!nextClose || nextClose.tag != tagName) return false;\n var cx = state.context;\n // If the immediate wrapping context contains onCx instances of\n // the same tag, a closing tag only exists if there are at least\n // that many closing tags of that type following.\n for (var onCx = newTag ? 1 : 0; cx && cx.tagName == tagName; cx = cx.prev) ++onCx;\n pos = nextClose.to;\n for (var i = 1; i < onCx; i++) {\n var next = CodeMirror.scanForClosingTag(cm, pos, null, end);\n if (!next || next.tag != tagName) return false;\n pos = next.to;\n }\n return true;\n }\n});\n\n},{\"../../lib/codemirror\":17,\"../fold/xml-fold\":15}],13:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n var ie_lt8 = /MSIE \\d/.test(navigator.userAgent) &&\n (document.documentMode == null || document.documentMode < 8);\n\n var Pos = CodeMirror.Pos;\n\n var matching = {\"(\": \")>\", \")\": \"(<\", \"[\": \"]>\", \"]\": \"[<\", \"{\": \"}>\", \"}\": \"{<\"};\n\n function findMatchingBracket(cm, where, config) {\n var line = cm.getLineHandle(where.line), pos = where.ch - 1;\n var afterCursor = config && config.afterCursor\n if (afterCursor == null)\n afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)\n\n // A cursor is defined as between two characters, but in in vim command mode\n // (i.e. not insert mode), the cursor is visually represented as a\n // highlighted box on top of the 2nd character. Otherwise, we allow matches\n // from before or after the cursor.\n var match = (!afterCursor && pos >= 0 && matching[line.text.charAt(pos)]) ||\n matching[line.text.charAt(++pos)];\n if (!match) return null;\n var dir = match.charAt(1) == \">\" ? 1 : -1;\n if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;\n var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));\n\n var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);\n if (found == null) return null;\n return {from: Pos(where.line, pos), to: found && found.pos,\n match: found && found.ch == match.charAt(0), forward: dir > 0};\n }\n\n // bracketRegex is used to specify which type of bracket to scan\n // should be a regexp, e.g. /[[\\]]/\n //\n // Note: If \"where\" is on an open bracket, then this bracket is ignored.\n //\n // Returns false when no bracket was found, null when it reached\n // maxScanLines and gave up\n function scanForBracket(cm, where, dir, style, config) {\n var maxScanLen = (config && config.maxScanLineLength) || 10000;\n var maxScanLines = (config && config.maxScanLines) || 1000;\n\n var stack = [];\n var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\\]]/;\n var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)\n : Math.max(cm.firstLine() - 1, where.line - maxScanLines);\n for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {\n var line = cm.getLine(lineNo);\n if (!line) continue;\n var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;\n if (line.length > maxScanLen) continue;\n if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);\n for (; pos != end; pos += dir) {\n var ch = line.charAt(pos);\n if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {\n var match = matching[ch];\n if ((match.charAt(1) == \">\") == (dir > 0)) stack.push(ch);\n else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};\n else stack.pop();\n }\n }\n }\n return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;\n }\n\n function matchBrackets(cm, autoclear, config) {\n // Disable brace matching in long lines, since it'll cause hugely slow updates\n var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;\n var marks = [], ranges = cm.listSelections();\n for (var i = 0; i < ranges.length; i++) {\n var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);\n if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {\n var style = match.match ? \"CodeMirror-matchingbracket\" : \"CodeMirror-nonmatchingbracket\";\n marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));\n if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)\n marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));\n }\n }\n\n if (marks.length) {\n // Kludge to work around the IE bug from issue #1193, where text\n // input stops going to the textare whever this fires.\n if (ie_lt8 && cm.state.focused) cm.focus();\n\n var clear = function() {\n cm.operation(function() {\n for (var i = 0; i < marks.length; i++) marks[i].clear();\n });\n };\n if (autoclear) setTimeout(clear, 800);\n else return clear;\n }\n }\n\n function doMatchBrackets(cm) {\n cm.operation(function() {\n if (cm.state.matchBrackets.currentlyHighlighted) {\n cm.state.matchBrackets.currentlyHighlighted();\n cm.state.matchBrackets.currentlyHighlighted = null;\n }\n cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);\n });\n }\n\n CodeMirror.defineOption(\"matchBrackets\", false, function(cm, val, old) {\n if (old && old != CodeMirror.Init) {\n cm.off(\"cursorActivity\", doMatchBrackets);\n if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {\n cm.state.matchBrackets.currentlyHighlighted();\n cm.state.matchBrackets.currentlyHighlighted = null;\n }\n }\n if (val) {\n cm.state.matchBrackets = typeof val == \"object\" ? val : {};\n cm.on(\"cursorActivity\", doMatchBrackets);\n }\n });\n\n CodeMirror.defineExtension(\"matchBrackets\", function() {matchBrackets(this, true);});\n CodeMirror.defineExtension(\"findMatchingBracket\", function(pos, config, oldConfig){\n // Backwards-compatibility kludge\n if (oldConfig || typeof config == \"boolean\") {\n if (!oldConfig) {\n config = config ? {strict: true} : null\n } else {\n oldConfig.strict = config\n config = oldConfig\n }\n }\n return findMatchingBracket(this, pos, config)\n });\n CodeMirror.defineExtension(\"scanForBracket\", function(pos, dir, style, config){\n return scanForBracket(this, pos, dir, style, config);\n });\n});\n\n},{\"../../lib/codemirror\":17}],14:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"), require(\"../fold/xml-fold\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\", \"../fold/xml-fold\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n\n CodeMirror.defineOption(\"matchTags\", false, function(cm, val, old) {\n if (old && old != CodeMirror.Init) {\n cm.off(\"cursorActivity\", doMatchTags);\n cm.off(\"viewportChange\", maybeUpdateMatch);\n clear(cm);\n }\n if (val) {\n cm.state.matchBothTags = typeof val == \"object\" && val.bothTags;\n cm.on(\"cursorActivity\", doMatchTags);\n cm.on(\"viewportChange\", maybeUpdateMatch);\n doMatchTags(cm);\n }\n });\n\n function clear(cm) {\n if (cm.state.tagHit) cm.state.tagHit.clear();\n if (cm.state.tagOther) cm.state.tagOther.clear();\n cm.state.tagHit = cm.state.tagOther = null;\n }\n\n function doMatchTags(cm) {\n cm.state.failedTagMatch = false;\n cm.operation(function() {\n clear(cm);\n if (cm.somethingSelected()) return;\n var cur = cm.getCursor(), range = cm.getViewport();\n range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);\n var match = CodeMirror.findMatchingTag(cm, cur, range);\n if (!match) return;\n if (cm.state.matchBothTags) {\n var hit = match.at == \"open\" ? match.open : match.close;\n if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: \"CodeMirror-matchingtag\"});\n }\n var other = match.at == \"close\" ? match.open : match.close;\n if (other)\n cm.state.tagOther = cm.markText(other.from, other.to, {className: \"CodeMirror-matchingtag\"});\n else\n cm.state.failedTagMatch = true;\n });\n }\n\n function maybeUpdateMatch(cm) {\n if (cm.state.failedTagMatch) doMatchTags(cm);\n }\n\n CodeMirror.commands.toMatchingTag = function(cm) {\n var found = CodeMirror.findMatchingTag(cm, cm.getCursor());\n if (found) {\n var other = found.at == \"close\" ? found.open : found.close;\n if (other) cm.extendSelection(other.to, other.from);\n }\n };\n});\n\n},{\"../../lib/codemirror\":17,\"../fold/xml-fold\":15}],15:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n\n var Pos = CodeMirror.Pos;\n function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }\n\n var nameStartChar = \"A-Z_a-z\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD\";\n var nameChar = nameStartChar + \"\\-\\:\\.0-9\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040\";\n var xmlTagStart = new RegExp(\"<(/?)([\" + nameStartChar + \"][\" + nameChar + \"]*)\", \"g\");\n\n function Iter(cm, line, ch, range) {\n this.line = line; this.ch = ch;\n this.cm = cm; this.text = cm.getLine(line);\n this.min = range ? Math.max(range.from, cm.firstLine()) : cm.firstLine();\n this.max = range ? Math.min(range.to - 1, cm.lastLine()) : cm.lastLine();\n }\n\n function tagAt(iter, ch) {\n var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));\n return type && /\\btag\\b/.test(type);\n }\n\n function nextLine(iter) {\n if (iter.line >= iter.max) return;\n iter.ch = 0;\n iter.text = iter.cm.getLine(++iter.line);\n return true;\n }\n function prevLine(iter) {\n if (iter.line <= iter.min) return;\n iter.text = iter.cm.getLine(--iter.line);\n iter.ch = iter.text.length;\n return true;\n }\n\n function toTagEnd(iter) {\n for (;;) {\n var gt = iter.text.indexOf(\">\", iter.ch);\n if (gt == -1) { if (nextLine(iter)) continue; else return; }\n if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }\n var lastSlash = iter.text.lastIndexOf(\"/\", gt);\n var selfClose = lastSlash > -1 && !/\\S/.test(iter.text.slice(lastSlash + 1, gt));\n iter.ch = gt + 1;\n return selfClose ? \"selfClose\" : \"regular\";\n }\n }\n function toTagStart(iter) {\n for (;;) {\n var lt = iter.ch ? iter.text.lastIndexOf(\"<\", iter.ch - 1) : -1;\n if (lt == -1) { if (prevLine(iter)) continue; else return; }\n if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }\n xmlTagStart.lastIndex = lt;\n iter.ch = lt;\n var match = xmlTagStart.exec(iter.text);\n if (match && match.index == lt) return match;\n }\n }\n\n function toNextTag(iter) {\n for (;;) {\n xmlTagStart.lastIndex = iter.ch;\n var found = xmlTagStart.exec(iter.text);\n if (!found) { if (nextLine(iter)) continue; else return; }\n if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }\n iter.ch = found.index + found[0].length;\n return found;\n }\n }\n function toPrevTag(iter) {\n for (;;) {\n var gt = iter.ch ? iter.text.lastIndexOf(\">\", iter.ch - 1) : -1;\n if (gt == -1) { if (prevLine(iter)) continue; else return; }\n if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }\n var lastSlash = iter.text.lastIndexOf(\"/\", gt);\n var selfClose = lastSlash > -1 && !/\\S/.test(iter.text.slice(lastSlash + 1, gt));\n iter.ch = gt + 1;\n return selfClose ? \"selfClose\" : \"regular\";\n }\n }\n\n function findMatchingClose(iter, tag) {\n var stack = [];\n for (;;) {\n var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);\n if (!next || !(end = toTagEnd(iter))) return;\n if (end == \"selfClose\") continue;\n if (next[1]) { // closing tag\n for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {\n stack.length = i;\n break;\n }\n if (i < 0 && (!tag || tag == next[2])) return {\n tag: next[2],\n from: Pos(startLine, startCh),\n to: Pos(iter.line, iter.ch)\n };\n } else { // opening tag\n stack.push(next[2]);\n }\n }\n }\n function findMatchingOpen(iter, tag) {\n var stack = [];\n for (;;) {\n var prev = toPrevTag(iter);\n if (!prev) return;\n if (prev == \"selfClose\") { toTagStart(iter); continue; }\n var endLine = iter.line, endCh = iter.ch;\n var start = toTagStart(iter);\n if (!start) return;\n if (start[1]) { // closing tag\n stack.push(start[2]);\n } else { // opening tag\n for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {\n stack.length = i;\n break;\n }\n if (i < 0 && (!tag || tag == start[2])) return {\n tag: start[2],\n from: Pos(iter.line, iter.ch),\n to: Pos(endLine, endCh)\n };\n }\n }\n }\n\n CodeMirror.registerHelper(\"fold\", \"xml\", function(cm, start) {\n var iter = new Iter(cm, start.line, 0);\n for (;;) {\n var openTag = toNextTag(iter)\n if (!openTag || iter.line != start.line) return\n var end = toTagEnd(iter)\n if (!end) return\n if (!openTag[1] && end != \"selfClose\") {\n var startPos = Pos(iter.line, iter.ch);\n var endPos = findMatchingClose(iter, openTag[2]);\n return endPos && cmp(endPos.from, startPos) > 0 ? {from: startPos, to: endPos.from} : null\n }\n }\n });\n CodeMirror.findMatchingTag = function(cm, pos, range) {\n var iter = new Iter(cm, pos.line, pos.ch, range);\n if (iter.text.indexOf(\">\") == -1 && iter.text.indexOf(\"<\") == -1) return;\n var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);\n var start = end && toTagStart(iter);\n if (!end || !start || cmp(iter, pos) > 0) return;\n var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};\n if (end == \"selfClose\") return {open: here, close: null, at: \"open\"};\n\n if (start[1]) { // closing tag\n return {open: findMatchingOpen(iter, start[2]), close: here, at: \"close\"};\n } else { // opening tag\n iter = new Iter(cm, to.line, to.ch, range);\n return {open: here, close: findMatchingClose(iter, start[2]), at: \"open\"};\n }\n };\n\n CodeMirror.findEnclosingTag = function(cm, pos, range, tag) {\n var iter = new Iter(cm, pos.line, pos.ch, range);\n for (;;) {\n var open = findMatchingOpen(iter, tag);\n if (!open) break;\n var forward = new Iter(cm, pos.line, pos.ch, range);\n var close = findMatchingClose(forward, open.tag);\n if (close) return {open: open, close: close};\n }\n };\n\n // Used by addon/edit/closetag.js\n CodeMirror.scanForClosingTag = function(cm, pos, name, end) {\n var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);\n return findMatchingClose(iter, name);\n };\n});\n\n},{\"../../lib/codemirror\":17}],16:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n var WRAP_CLASS = \"CodeMirror-activeline\";\n var BACK_CLASS = \"CodeMirror-activeline-background\";\n var GUTT_CLASS = \"CodeMirror-activeline-gutter\";\n\n CodeMirror.defineOption(\"styleActiveLine\", false, function(cm, val, old) {\n var prev = old == CodeMirror.Init ? false : old;\n if (val == prev) return\n if (prev) {\n cm.off(\"beforeSelectionChange\", selectionChange);\n clearActiveLines(cm);\n delete cm.state.activeLines;\n }\n if (val) {\n cm.state.activeLines = [];\n updateActiveLines(cm, cm.listSelections());\n cm.on(\"beforeSelectionChange\", selectionChange);\n }\n });\n\n function clearActiveLines(cm) {\n for (var i = 0; i < cm.state.activeLines.length; i++) {\n cm.removeLineClass(cm.state.activeLines[i], \"wrap\", WRAP_CLASS);\n cm.removeLineClass(cm.state.activeLines[i], \"background\", BACK_CLASS);\n cm.removeLineClass(cm.state.activeLines[i], \"gutter\", GUTT_CLASS);\n }\n }\n\n function sameArray(a, b) {\n if (a.length != b.length) return false;\n for (var i = 0; i < a.length; i++)\n if (a[i] != b[i]) return false;\n return true;\n }\n\n function updateActiveLines(cm, ranges) {\n var active = [];\n for (var i = 0; i < ranges.length; i++) {\n var range = ranges[i];\n var option = cm.getOption(\"styleActiveLine\");\n if (typeof option == \"object\" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())\n continue\n var line = cm.getLineHandleVisualStart(range.head.line);\n if (active[active.length - 1] != line) active.push(line);\n }\n if (sameArray(cm.state.activeLines, active)) return;\n cm.operation(function() {\n clearActiveLines(cm);\n for (var i = 0; i < active.length; i++) {\n cm.addLineClass(active[i], \"wrap\", WRAP_CLASS);\n cm.addLineClass(active[i], \"background\", BACK_CLASS);\n cm.addLineClass(active[i], \"gutter\", GUTT_CLASS);\n }\n cm.state.activeLines = active;\n });\n }\n\n function selectionChange(cm, sel) {\n updateActiveLines(cm, sel.ranges);\n }\n});\n\n},{\"../../lib/codemirror\":17}],17:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n// This is CodeMirror (https://codemirror.net), a code editor\n// implemented in JavaScript on top of the browser's DOM.\n//\n// You can find some technical background for some of the code below\n// at http://marijnhaverbeke.nl/blog/#cm-internals .\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.CodeMirror = factory());\n}(this, (function () { 'use strict';\n\n // Kludges for bugs and behavior differences that can't be feature\n // detected are enabled based on userAgent etc sniffing.\n var userAgent = navigator.userAgent;\n var platform = navigator.platform;\n\n var gecko = /gecko\\/\\d/i.test(userAgent);\n var ie_upto10 = /MSIE \\d/.test(userAgent);\n var ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(userAgent);\n var edge = /Edge\\/(\\d+)/.exec(userAgent);\n var ie = ie_upto10 || ie_11up || edge;\n var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);\n var webkit = !edge && /WebKit\\//.test(userAgent);\n var qtwebkit = webkit && /Qt\\/\\d+\\.\\d+/.test(userAgent);\n var chrome = !edge && /Chrome\\//.test(userAgent);\n var presto = /Opera\\//.test(userAgent);\n var safari = /Apple Computer/.test(navigator.vendor);\n var mac_geMountainLion = /Mac OS X 1\\d\\D([8-9]|\\d\\d)\\D/.test(userAgent);\n var phantom = /PhantomJS/.test(userAgent);\n\n var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\\/\\w+/.test(userAgent);\n var android = /Android/.test(userAgent);\n // This is woefully incomplete. Suggestions for alternative methods welcome.\n var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);\n var mac = ios || /Mac/.test(platform);\n var chromeOS = /\\bCrOS\\b/.test(userAgent);\n var windows = /win/i.test(platform);\n\n var presto_version = presto && userAgent.match(/Version\\/(\\d*\\.\\d*)/);\n if (presto_version) { presto_version = Number(presto_version[1]); }\n if (presto_version && presto_version >= 15) { presto = false; webkit = true; }\n // Some browsers use the wrong event properties to signal cmd/ctrl on OS X\n var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));\n var captureRightClick = gecko || (ie && ie_version >= 9);\n\n function classTest(cls) { return new RegExp(\"(^|\\\\s)\" + cls + \"(?:$|\\\\s)\\\\s*\") }\n\n var rmClass = function(node, cls) {\n var current = node.className;\n var match = classTest(cls).exec(current);\n if (match) {\n var after = current.slice(match.index + match[0].length);\n node.className = current.slice(0, match.index) + (after ? match[1] + after : \"\");\n }\n };\n\n function removeChildren(e) {\n for (var count = e.childNodes.length; count > 0; --count)\n { e.removeChild(e.firstChild); }\n return e\n }\n\n function removeChildrenAndAdd(parent, e) {\n return removeChildren(parent).appendChild(e)\n }\n\n function elt(tag, content, className, style) {\n var e = document.createElement(tag);\n if (className) { e.className = className; }\n if (style) { e.style.cssText = style; }\n if (typeof content == \"string\") { e.appendChild(document.createTextNode(content)); }\n else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }\n return e\n }\n // wrapper for elt, which removes the elt from the accessibility tree\n function eltP(tag, content, className, style) {\n var e = elt(tag, content, className, style);\n e.setAttribute(\"role\", \"presentation\");\n return e\n }\n\n var range;\n if (document.createRange) { range = function(node, start, end, endNode) {\n var r = document.createRange();\n r.setEnd(endNode || node, end);\n r.setStart(node, start);\n return r\n }; }\n else { range = function(node, start, end) {\n var r = document.body.createTextRange();\n try { r.moveToElementText(node.parentNode); }\n catch(e) { return r }\n r.collapse(true);\n r.moveEnd(\"character\", end);\n r.moveStart(\"character\", start);\n return r\n }; }\n\n function contains(parent, child) {\n if (child.nodeType == 3) // Android browser always returns false when child is a textnode\n { child = child.parentNode; }\n if (parent.contains)\n { return parent.contains(child) }\n do {\n if (child.nodeType == 11) { child = child.host; }\n if (child == parent) { return true }\n } while (child = child.parentNode)\n }\n\n function activeElt() {\n // IE and Edge may throw an \"Unspecified Error\" when accessing document.activeElement.\n // IE < 10 will throw when accessed while the page is loading or in an iframe.\n // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.\n var activeElement;\n try {\n activeElement = document.activeElement;\n } catch(e) {\n activeElement = document.body || null;\n }\n while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)\n { activeElement = activeElement.shadowRoot.activeElement; }\n return activeElement\n }\n\n function addClass(node, cls) {\n var current = node.className;\n if (!classTest(cls).test(current)) { node.className += (current ? \" \" : \"\") + cls; }\n }\n function joinClasses(a, b) {\n var as = a.split(\" \");\n for (var i = 0; i < as.length; i++)\n { if (as[i] && !classTest(as[i]).test(b)) { b += \" \" + as[i]; } }\n return b\n }\n\n var selectInput = function(node) { node.select(); };\n if (ios) // Mobile Safari apparently has a bug where select() is broken.\n { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }\n else if (ie) // Suppress mysterious IE10 errors\n { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }\n\n function bind(f) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function(){return f.apply(null, args)}\n }\n\n function copyObj(obj, target, overwrite) {\n if (!target) { target = {}; }\n for (var prop in obj)\n { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))\n { target[prop] = obj[prop]; } }\n return target\n }\n\n // Counts the column offset in a string, taking tabs into account.\n // Used mostly to find indentation.\n function countColumn(string, end, tabSize, startIndex, startValue) {\n if (end == null) {\n end = string.search(/[^\\s\\u00a0]/);\n if (end == -1) { end = string.length; }\n }\n for (var i = startIndex || 0, n = startValue || 0;;) {\n var nextTab = string.indexOf(\"\\t\", i);\n if (nextTab < 0 || nextTab >= end)\n { return n + (end - i) }\n n += nextTab - i;\n n += tabSize - (n % tabSize);\n i = nextTab + 1;\n }\n }\n\n var Delayed = function() {this.id = null;};\n Delayed.prototype.set = function (ms, f) {\n clearTimeout(this.id);\n this.id = setTimeout(f, ms);\n };\n\n function indexOf(array, elt) {\n for (var i = 0; i < array.length; ++i)\n { if (array[i] == elt) { return i } }\n return -1\n }\n\n // Number of pixels added to scroller and sizer to hide scrollbar\n var scrollerGap = 30;\n\n // Returned or thrown by various protocols to signal 'I'm not\n // handling this'.\n var Pass = {toString: function(){return \"CodeMirror.Pass\"}};\n\n // Reused option objects for setSelection & friends\n var sel_dontScroll = {scroll: false}, sel_mouse = {origin: \"*mouse\"}, sel_move = {origin: \"+move\"};\n\n // The inverse of countColumn -- find the offset that corresponds to\n // a particular column.\n function findColumn(string, goal, tabSize) {\n for (var pos = 0, col = 0;;) {\n var nextTab = string.indexOf(\"\\t\", pos);\n if (nextTab == -1) { nextTab = string.length; }\n var skipped = nextTab - pos;\n if (nextTab == string.length || col + skipped >= goal)\n { return pos + Math.min(skipped, goal - col) }\n col += nextTab - pos;\n col += tabSize - (col % tabSize);\n pos = nextTab + 1;\n if (col >= goal) { return pos }\n }\n }\n\n var spaceStrs = [\"\"];\n function spaceStr(n) {\n while (spaceStrs.length <= n)\n { spaceStrs.push(lst(spaceStrs) + \" \"); }\n return spaceStrs[n]\n }\n\n function lst(arr) { return arr[arr.length-1] }\n\n function map(array, f) {\n var out = [];\n for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }\n return out\n }\n\n function insertSorted(array, value, score) {\n var pos = 0, priority = score(value);\n while (pos < array.length && score(array[pos]) <= priority) { pos++; }\n array.splice(pos, 0, value);\n }\n\n function nothing() {}\n\n function createObj(base, props) {\n var inst;\n if (Object.create) {\n inst = Object.create(base);\n } else {\n nothing.prototype = base;\n inst = new nothing();\n }\n if (props) { copyObj(props, inst); }\n return inst\n }\n\n var nonASCIISingleCaseWordChar = /[\\u00df\\u0587\\u0590-\\u05f4\\u0600-\\u06ff\\u3040-\\u309f\\u30a0-\\u30ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\uac00-\\ud7af]/;\n function isWordCharBasic(ch) {\n return /\\w/.test(ch) || ch > \"\\x80\" &&\n (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))\n }\n function isWordChar(ch, helper) {\n if (!helper) { return isWordCharBasic(ch) }\n if (helper.source.indexOf(\"\\\\w\") > -1 && isWordCharBasic(ch)) { return true }\n return helper.test(ch)\n }\n\n function isEmpty(obj) {\n for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }\n return true\n }\n\n // Extending unicode characters. A series of a non-extending char +\n // any number of extending chars is treated as a single unit as far\n // as editing and measuring is concerned. This is not fully correct,\n // since some scripts/fonts/browsers also treat other configurations\n // of code points as a group.\n var extendingChars = /[\\u0300-\\u036f\\u0483-\\u0489\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u065e\\u0670\\u06d6-\\u06dc\\u06de-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07eb-\\u07f3\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0900-\\u0902\\u093c\\u0941-\\u0948\\u094d\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09bc\\u09be\\u09c1-\\u09c4\\u09cd\\u09d7\\u09e2\\u09e3\\u0a01\\u0a02\\u0a3c\\u0a41\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a70\\u0a71\\u0a75\\u0a81\\u0a82\\u0abc\\u0ac1-\\u0ac5\\u0ac7\\u0ac8\\u0acd\\u0ae2\\u0ae3\\u0b01\\u0b3c\\u0b3e\\u0b3f\\u0b41-\\u0b44\\u0b4d\\u0b56\\u0b57\\u0b62\\u0b63\\u0b82\\u0bbe\\u0bc0\\u0bcd\\u0bd7\\u0c3e-\\u0c40\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0cbc\\u0cbf\\u0cc2\\u0cc6\\u0ccc\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0d3e\\u0d41-\\u0d44\\u0d4d\\u0d57\\u0d62\\u0d63\\u0dca\\u0dcf\\u0dd2-\\u0dd4\\u0dd6\\u0ddf\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0eb1\\u0eb4-\\u0eb9\\u0ebb\\u0ebc\\u0ec8-\\u0ecd\\u0f18\\u0f19\\u0f35\\u0f37\\u0f39\\u0f71-\\u0f7e\\u0f80-\\u0f84\\u0f86\\u0f87\\u0f90-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102d-\\u1030\\u1032-\\u1037\\u1039\\u103a\\u103d\\u103e\\u1058\\u1059\\u105e-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108d\\u109d\\u135f\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b7-\\u17bd\\u17c6\\u17c9-\\u17d3\\u17dd\\u180b-\\u180d\\u18a9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193b\\u1a17\\u1a18\\u1a56\\u1a58-\\u1a5e\\u1a60\\u1a62\\u1a65-\\u1a6c\\u1a73-\\u1a7c\\u1a7f\\u1b00-\\u1b03\\u1b34\\u1b36-\\u1b3a\\u1b3c\\u1b42\\u1b6b-\\u1b73\\u1b80\\u1b81\\u1ba2-\\u1ba5\\u1ba8\\u1ba9\\u1c2c-\\u1c33\\u1c36\\u1c37\\u1cd0-\\u1cd2\\u1cd4-\\u1ce0\\u1ce2-\\u1ce8\\u1ced\\u1dc0-\\u1de6\\u1dfd-\\u1dff\\u200c\\u200d\\u20d0-\\u20f0\\u2cef-\\u2cf1\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua66f-\\ua672\\ua67c\\ua67d\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua825\\ua826\\ua8c4\\ua8e0-\\ua8f1\\ua926-\\ua92d\\ua947-\\ua951\\ua980-\\ua982\\ua9b3\\ua9b6-\\ua9b9\\ua9bc\\uaa29-\\uaa2e\\uaa31\\uaa32\\uaa35\\uaa36\\uaa43\\uaa4c\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uabe5\\uabe8\\uabed\\udc00-\\udfff\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe26\\uff9e\\uff9f]/;\n function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }\n\n // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.\n function skipExtendingChars(str, pos, dir) {\n while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }\n return pos\n }\n\n // Returns the value from the range [`from`; `to`] that satisfies\n // `pred` and is closest to `from`. Assumes that at least `to`\n // satisfies `pred`. Supports `from` being greater than `to`.\n function findFirst(pred, from, to) {\n // At any point we are certain `to` satisfies `pred`, don't know\n // whether `from` does.\n var dir = from > to ? -1 : 1;\n for (;;) {\n if (from == to) { return from }\n var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);\n if (mid == from) { return pred(mid) ? from : to }\n if (pred(mid)) { to = mid; }\n else { from = mid + dir; }\n }\n }\n\n // The display handles the DOM integration, both for input reading\n // and content drawing. It holds references to DOM nodes and\n // display-related state.\n\n function Display(place, doc, input) {\n var d = this;\n this.input = input;\n\n // Covers bottom-right square when both scrollbars are present.\n d.scrollbarFiller = elt(\"div\", null, \"CodeMirror-scrollbar-filler\");\n d.scrollbarFiller.setAttribute(\"cm-not-content\", \"true\");\n // Covers bottom of gutter when coverGutterNextToScrollbar is on\n // and h scrollbar is present.\n d.gutterFiller = elt(\"div\", null, \"CodeMirror-gutter-filler\");\n d.gutterFiller.setAttribute(\"cm-not-content\", \"true\");\n // Will contain the actual code, positioned to cover the viewport.\n d.lineDiv = eltP(\"div\", null, \"CodeMirror-code\");\n // Elements are added to these to represent selection and cursors.\n d.selectionDiv = elt(\"div\", null, null, \"position: relative; z-index: 1\");\n d.cursorDiv = elt(\"div\", null, \"CodeMirror-cursors\");\n // A visibility: hidden element used to find the size of things.\n d.measure = elt(\"div\", null, \"CodeMirror-measure\");\n // When lines outside of the viewport are measured, they are drawn in this.\n d.lineMeasure = elt(\"div\", null, \"CodeMirror-measure\");\n // Wraps everything that needs to exist inside the vertically-padded coordinate system\n d.lineSpace = eltP(\"div\", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],\n null, \"position: relative; outline: none\");\n var lines = eltP(\"div\", [d.lineSpace], \"CodeMirror-lines\");\n // Moved around its parent to cover visible view.\n d.mover = elt(\"div\", [lines], null, \"position: relative\");\n // Set to the height of the document, allowing scrolling.\n d.sizer = elt(\"div\", [d.mover], \"CodeMirror-sizer\");\n d.sizerWidth = null;\n // Behavior of elts with overflow: auto and padding is\n // inconsistent across browsers. This is used to ensure the\n // scrollable area is big enough.\n d.heightForcer = elt(\"div\", null, null, \"position: absolute; height: \" + scrollerGap + \"px; width: 1px;\");\n // Will contain the gutters, if any.\n d.gutters = elt(\"div\", null, \"CodeMirror-gutters\");\n d.lineGutter = null;\n // Actual scrollable element.\n d.scroller = elt(\"div\", [d.sizer, d.heightForcer, d.gutters], \"CodeMirror-scroll\");\n d.scroller.setAttribute(\"tabIndex\", \"-1\");\n // The element in which the editor lives.\n d.wrapper = elt(\"div\", [d.scrollbarFiller, d.gutterFiller, d.scroller], \"CodeMirror\");\n\n // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)\n if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }\n if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }\n\n if (place) {\n if (place.appendChild) { place.appendChild(d.wrapper); }\n else { place(d.wrapper); }\n }\n\n // Current rendered range (may be bigger than the view window).\n d.viewFrom = d.viewTo = doc.first;\n d.reportedViewFrom = d.reportedViewTo = doc.first;\n // Information about the rendered lines.\n d.view = [];\n d.renderedView = null;\n // Holds info about a single rendered line when it was rendered\n // for measurement, while not in view.\n d.externalMeasured = null;\n // Empty space (in pixels) above the view\n d.viewOffset = 0;\n d.lastWrapHeight = d.lastWrapWidth = 0;\n d.updateLineNumbers = null;\n\n d.nativeBarWidth = d.barHeight = d.barWidth = 0;\n d.scrollbarsClipped = false;\n\n // Used to only resize the line number gutter when necessary (when\n // the amount of lines crosses a boundary that makes its width change)\n d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;\n // Set to true when a non-horizontal-scrolling line widget is\n // added. As an optimization, line widget aligning is skipped when\n // this is false.\n d.alignWidgets = false;\n\n d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n\n // Tracks the maximum line length so that the horizontal scrollbar\n // can be kept static when scrolling.\n d.maxLine = null;\n d.maxLineLength = 0;\n d.maxLineChanged = false;\n\n // Used for measuring wheel scrolling granularity\n d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;\n\n // True when shift is held down.\n d.shift = false;\n\n // Used to track whether anything happened since the context menu\n // was opened.\n d.selForContextMenu = null;\n\n d.activeTouch = null;\n\n input.init(d);\n }\n\n // Find the line object corresponding to the given line number.\n function getLine(doc, n) {\n n -= doc.first;\n if (n < 0 || n >= doc.size) { throw new Error(\"There is no line \" + (n + doc.first) + \" in the document.\") }\n var chunk = doc;\n while (!chunk.lines) {\n for (var i = 0;; ++i) {\n var child = chunk.children[i], sz = child.chunkSize();\n if (n < sz) { chunk = child; break }\n n -= sz;\n }\n }\n return chunk.lines[n]\n }\n\n // Get the part of a document between two positions, as an array of\n // strings.\n function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }\n // Get the lines between from and to, as array of strings.\n function getLines(doc, from, to) {\n var out = [];\n doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value\n return out\n }\n\n // Update the height of a line, propagating the height change\n // upwards to parent nodes.\n function updateLineHeight(line, height) {\n var diff = height - line.height;\n if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }\n }\n\n // Given a line object, find its line number by walking up through\n // its parent links.\n function lineNo(line) {\n if (line.parent == null) { return null }\n var cur = line.parent, no = indexOf(cur.lines, line);\n for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {\n for (var i = 0;; ++i) {\n if (chunk.children[i] == cur) { break }\n no += chunk.children[i].chunkSize();\n }\n }\n return no + cur.first\n }\n\n // Find the line at the given vertical position, using the height\n // information in the document tree.\n function lineAtHeight(chunk, h) {\n var n = chunk.first;\n outer: do {\n for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {\n var child = chunk.children[i$1], ch = child.height;\n if (h < ch) { chunk = child; continue outer }\n h -= ch;\n n += child.chunkSize();\n }\n return n\n } while (!chunk.lines)\n var i = 0;\n for (; i < chunk.lines.length; ++i) {\n var line = chunk.lines[i], lh = line.height;\n if (h < lh) { break }\n h -= lh;\n }\n return n + i\n }\n\n function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}\n\n function lineNumberFor(options, i) {\n return String(options.lineNumberFormatter(i + options.firstLineNumber))\n }\n\n // A Pos instance represents a position within the text.\n function Pos(line, ch, sticky) {\n if ( sticky === void 0 ) sticky = null;\n\n if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }\n this.line = line;\n this.ch = ch;\n this.sticky = sticky;\n }\n\n // Compare two positions, return 0 if they are the same, a negative\n // number when a is less, and a positive number otherwise.\n function cmp(a, b) { return a.line - b.line || a.ch - b.ch }\n\n function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }\n\n function copyPos(x) {return Pos(x.line, x.ch)}\n function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }\n function minPos(a, b) { return cmp(a, b) < 0 ? a : b }\n\n // Most of the external API clips given positions to make sure they\n // actually exist within the document.\n function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}\n function clipPos(doc, pos) {\n if (pos.line < doc.first) { return Pos(doc.first, 0) }\n var last = doc.first + doc.size - 1;\n if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }\n return clipToLen(pos, getLine(doc, pos.line).text.length)\n }\n function clipToLen(pos, linelen) {\n var ch = pos.ch;\n if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }\n else if (ch < 0) { return Pos(pos.line, 0) }\n else { return pos }\n }\n function clipPosArray(doc, array) {\n var out = [];\n for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }\n return out\n }\n\n // Optimize some code when these features are not used.\n var sawReadOnlySpans = false, sawCollapsedSpans = false;\n\n function seeReadOnlySpans() {\n sawReadOnlySpans = true;\n }\n\n function seeCollapsedSpans() {\n sawCollapsedSpans = true;\n }\n\n // TEXTMARKER SPANS\n\n function MarkedSpan(marker, from, to) {\n this.marker = marker;\n this.from = from; this.to = to;\n }\n\n // Search an array of spans for a span matching the given marker.\n function getMarkedSpanFor(spans, marker) {\n if (spans) { for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if (span.marker == marker) { return span }\n } }\n }\n // Remove a span from an array, returning undefined if no spans are\n // left (we don't store arrays for lines without spans).\n function removeMarkedSpan(spans, span) {\n var r;\n for (var i = 0; i < spans.length; ++i)\n { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }\n return r\n }\n // Add a span to a line.\n function addMarkedSpan(line, span) {\n line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];\n span.marker.attachLine(line);\n }\n\n // Used for the algorithm that adjusts markers for a change in the\n // document. These functions cut an array of spans at a given\n // character position, returning an array of remaining chunks (or\n // undefined if nothing remains).\n function markedSpansBefore(old, startCh, isInsert) {\n var nw;\n if (old) { for (var i = 0; i < old.length; ++i) {\n var span = old[i], marker = span.marker;\n var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);\n if (startsBefore || span.from == startCh && marker.type == \"bookmark\" && (!isInsert || !span.marker.insertLeft)) {\n var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)\n ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));\n }\n } }\n return nw\n }\n function markedSpansAfter(old, endCh, isInsert) {\n var nw;\n if (old) { for (var i = 0; i < old.length; ++i) {\n var span = old[i], marker = span.marker;\n var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);\n if (endsAfter || span.from == endCh && marker.type == \"bookmark\" && (!isInsert || span.marker.insertLeft)) {\n var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)\n ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,\n span.to == null ? null : span.to - endCh));\n }\n } }\n return nw\n }\n\n // Given a change object, compute the new set of marker spans that\n // cover the line in which the change took place. Removes spans\n // entirely within the change, reconnects spans belonging to the\n // same marker that appear on both sides of the change, and cuts off\n // spans partially within the change. Returns an array of span\n // arrays with one element for each line in (after) the change.\n function stretchSpansOverChange(doc, change) {\n if (change.full) { return null }\n var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;\n var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;\n if (!oldFirst && !oldLast) { return null }\n\n var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;\n // Get the spans that 'stick out' on both sides\n var first = markedSpansBefore(oldFirst, startCh, isInsert);\n var last = markedSpansAfter(oldLast, endCh, isInsert);\n\n // Next, merge those two ends\n var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);\n if (first) {\n // Fix up .to properties of first\n for (var i = 0; i < first.length; ++i) {\n var span = first[i];\n if (span.to == null) {\n var found = getMarkedSpanFor(last, span.marker);\n if (!found) { span.to = startCh; }\n else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }\n }\n }\n }\n if (last) {\n // Fix up .from in last (or move them into first in case of sameLine)\n for (var i$1 = 0; i$1 < last.length; ++i$1) {\n var span$1 = last[i$1];\n if (span$1.to != null) { span$1.to += offset; }\n if (span$1.from == null) {\n var found$1 = getMarkedSpanFor(first, span$1.marker);\n if (!found$1) {\n span$1.from = offset;\n if (sameLine) { (first || (first = [])).push(span$1); }\n }\n } else {\n span$1.from += offset;\n if (sameLine) { (first || (first = [])).push(span$1); }\n }\n }\n }\n // Make sure we didn't create any zero-length spans\n if (first) { first = clearEmptySpans(first); }\n if (last && last != first) { last = clearEmptySpans(last); }\n\n var newMarkers = [first];\n if (!sameLine) {\n // Fill gap with whole-line-spans\n var gap = change.text.length - 2, gapMarkers;\n if (gap > 0 && first)\n { for (var i$2 = 0; i$2 < first.length; ++i$2)\n { if (first[i$2].to == null)\n { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }\n for (var i$3 = 0; i$3 < gap; ++i$3)\n { newMarkers.push(gapMarkers); }\n newMarkers.push(last);\n }\n return newMarkers\n }\n\n // Remove spans that are empty and don't have a clearWhenEmpty\n // option of false.\n function clearEmptySpans(spans) {\n for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)\n { spans.splice(i--, 1); }\n }\n if (!spans.length) { return null }\n return spans\n }\n\n // Used to 'clip' out readOnly ranges when making a change.\n function removeReadOnlyRanges(doc, from, to) {\n var markers = null;\n doc.iter(from.line, to.line + 1, function (line) {\n if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {\n var mark = line.markedSpans[i].marker;\n if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))\n { (markers || (markers = [])).push(mark); }\n } }\n });\n if (!markers) { return null }\n var parts = [{from: from, to: to}];\n for (var i = 0; i < markers.length; ++i) {\n var mk = markers[i], m = mk.find(0);\n for (var j = 0; j < parts.length; ++j) {\n var p = parts[j];\n if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }\n var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);\n if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)\n { newParts.push({from: p.from, to: m.from}); }\n if (dto > 0 || !mk.inclusiveRight && !dto)\n { newParts.push({from: m.to, to: p.to}); }\n parts.splice.apply(parts, newParts);\n j += newParts.length - 3;\n }\n }\n return parts\n }\n\n // Connect or disconnect spans from a line.\n function detachMarkedSpans(line) {\n var spans = line.markedSpans;\n if (!spans) { return }\n for (var i = 0; i < spans.length; ++i)\n { spans[i].marker.detachLine(line); }\n line.markedSpans = null;\n }\n function attachMarkedSpans(line, spans) {\n if (!spans) { return }\n for (var i = 0; i < spans.length; ++i)\n { spans[i].marker.attachLine(line); }\n line.markedSpans = spans;\n }\n\n // Helpers used when computing which overlapping collapsed span\n // counts as the larger one.\n function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }\n function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }\n\n // Returns a number indicating which of two overlapping collapsed\n // spans is larger (and thus includes the other). Falls back to\n // comparing ids when the spans cover exactly the same range.\n function compareCollapsedMarkers(a, b) {\n var lenDiff = a.lines.length - b.lines.length;\n if (lenDiff != 0) { return lenDiff }\n var aPos = a.find(), bPos = b.find();\n var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);\n if (fromCmp) { return -fromCmp }\n var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);\n if (toCmp) { return toCmp }\n return b.id - a.id\n }\n\n // Find out whether a line ends or starts in a collapsed span. If\n // so, return the marker for that span.\n function collapsedSpanAtSide(line, start) {\n var sps = sawCollapsedSpans && line.markedSpans, found;\n if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {\n sp = sps[i];\n if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&\n (!found || compareCollapsedMarkers(found, sp.marker) < 0))\n { found = sp.marker; }\n } }\n return found\n }\n function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }\n function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }\n\n function collapsedSpanAround(line, ch) {\n var sps = sawCollapsedSpans && line.markedSpans, found;\n if (sps) { for (var i = 0; i < sps.length; ++i) {\n var sp = sps[i];\n if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&\n (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }\n } }\n return found\n }\n\n // Test whether there exists a collapsed span that partially\n // overlaps (covers the start or end, but not both) of a new span.\n // Such overlap is not allowed.\n function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {\n var line = getLine(doc, lineNo$$1);\n var sps = sawCollapsedSpans && line.markedSpans;\n if (sps) { for (var i = 0; i < sps.length; ++i) {\n var sp = sps[i];\n if (!sp.marker.collapsed) { continue }\n var found = sp.marker.find(0);\n var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);\n var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);\n if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }\n if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||\n fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))\n { return true }\n } }\n }\n\n // A visual line is a line as drawn on the screen. Folding, for\n // example, can cause multiple logical lines to appear on the same\n // visual line. This finds the start of the visual line that the\n // given line is part of (usually that is the line itself).\n function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }\n\n function visualLineEnd(line) {\n var merged;\n while (merged = collapsedSpanAtEnd(line))\n { line = merged.find(1, true).line; }\n return line\n }\n\n // Returns an array of logical lines that continue the visual line\n // started by the argument, or undefined if there are no such lines.\n function visualLineContinued(line) {\n var merged, lines;\n while (merged = collapsedSpanAtEnd(line)) {\n line = merged.find(1, true).line\n ;(lines || (lines = [])).push(line);\n }\n return lines\n }\n\n // Get the line number of the start of the visual line that the\n // given line number is part of.\n function visualLineNo(doc, lineN) {\n var line = getLine(doc, lineN), vis = visualLine(line);\n if (line == vis) { return lineN }\n return lineNo(vis)\n }\n\n // Get the line number of the start of the next visual line after\n // the given line.\n function visualLineEndNo(doc, lineN) {\n if (lineN > doc.lastLine()) { return lineN }\n var line = getLine(doc, lineN), merged;\n if (!lineIsHidden(doc, line)) { return lineN }\n while (merged = collapsedSpanAtEnd(line))\n { line = merged.find(1, true).line; }\n return lineNo(line) + 1\n }\n\n // Compute whether a line is hidden. Lines count as hidden when they\n // are part of a visual line that starts with another line, or when\n // they are entirely covered by collapsed, non-widget span.\n function lineIsHidden(doc, line) {\n var sps = sawCollapsedSpans && line.markedSpans;\n if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {\n sp = sps[i];\n if (!sp.marker.collapsed) { continue }\n if (sp.from == null) { return true }\n if (sp.marker.widgetNode) { continue }\n if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))\n { return true }\n } }\n }\n function lineIsHiddenInner(doc, line, span) {\n if (span.to == null) {\n var end = span.marker.find(1, true);\n return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))\n }\n if (span.marker.inclusiveRight && span.to == line.text.length)\n { return true }\n for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {\n sp = line.markedSpans[i];\n if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&\n (sp.to == null || sp.to != span.from) &&\n (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&\n lineIsHiddenInner(doc, line, sp)) { return true }\n }\n }\n\n // Find the height above the given line.\n function heightAtLine(lineObj) {\n lineObj = visualLine(lineObj);\n\n var h = 0, chunk = lineObj.parent;\n for (var i = 0; i < chunk.lines.length; ++i) {\n var line = chunk.lines[i];\n if (line == lineObj) { break }\n else { h += line.height; }\n }\n for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n for (var i$1 = 0; i$1 < p.children.length; ++i$1) {\n var cur = p.children[i$1];\n if (cur == chunk) { break }\n else { h += cur.height; }\n }\n }\n return h\n }\n\n // Compute the character length of a line, taking into account\n // collapsed ranges (see markText) that might hide parts, and join\n // other lines onto it.\n function lineLength(line) {\n if (line.height == 0) { return 0 }\n var len = line.text.length, merged, cur = line;\n while (merged = collapsedSpanAtStart(cur)) {\n var found = merged.find(0, true);\n cur = found.from.line;\n len += found.from.ch - found.to.ch;\n }\n cur = line;\n while (merged = collapsedSpanAtEnd(cur)) {\n var found$1 = merged.find(0, true);\n len -= cur.text.length - found$1.from.ch;\n cur = found$1.to.line;\n len += cur.text.length - found$1.to.ch;\n }\n return len\n }\n\n // Find the longest line in the document.\n function findMaxLine(cm) {\n var d = cm.display, doc = cm.doc;\n d.maxLine = getLine(doc, doc.first);\n d.maxLineLength = lineLength(d.maxLine);\n d.maxLineChanged = true;\n doc.iter(function (line) {\n var len = lineLength(line);\n if (len > d.maxLineLength) {\n d.maxLineLength = len;\n d.maxLine = line;\n }\n });\n }\n\n // BIDI HELPERS\n\n function iterateBidiSections(order, from, to, f) {\n if (!order) { return f(from, to, \"ltr\", 0) }\n var found = false;\n for (var i = 0; i < order.length; ++i) {\n var part = order[i];\n if (part.from < to && part.to > from || from == to && part.to == from) {\n f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? \"rtl\" : \"ltr\", i);\n found = true;\n }\n }\n if (!found) { f(from, to, \"ltr\"); }\n }\n\n var bidiOther = null;\n function getBidiPartAt(order, ch, sticky) {\n var found;\n bidiOther = null;\n for (var i = 0; i < order.length; ++i) {\n var cur = order[i];\n if (cur.from < ch && cur.to > ch) { return i }\n if (cur.to == ch) {\n if (cur.from != cur.to && sticky == \"before\") { found = i; }\n else { bidiOther = i; }\n }\n if (cur.from == ch) {\n if (cur.from != cur.to && sticky != \"before\") { found = i; }\n else { bidiOther = i; }\n }\n }\n return found != null ? found : bidiOther\n }\n\n // Bidirectional ordering algorithm\n // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm\n // that this (partially) implements.\n\n // One-char codes used for character types:\n // L (L): Left-to-Right\n // R (R): Right-to-Left\n // r (AL): Right-to-Left Arabic\n // 1 (EN): European Number\n // + (ES): European Number Separator\n // % (ET): European Number Terminator\n // n (AN): Arabic Number\n // , (CS): Common Number Separator\n // m (NSM): Non-Spacing Mark\n // b (BN): Boundary Neutral\n // s (B): Paragraph Separator\n // t (S): Segment Separator\n // w (WS): Whitespace\n // N (ON): Other Neutrals\n\n // Returns null if characters are ordered as they appear\n // (left-to-right), or an array of sections ({from, to, level}\n // objects) in the order in which they occur visually.\n var bidiOrdering = (function() {\n // Character types for codepoints 0 to 0xff\n var lowTypes = \"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN\";\n // Character types for codepoints 0x600 to 0x6f9\n var arabicTypes = \"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111\";\n function charType(code) {\n if (code <= 0xf7) { return lowTypes.charAt(code) }\n else if (0x590 <= code && code <= 0x5f4) { return \"R\" }\n else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }\n else if (0x6ee <= code && code <= 0x8ac) { return \"r\" }\n else if (0x2000 <= code && code <= 0x200b) { return \"w\" }\n else if (code == 0x200c) { return \"b\" }\n else { return \"L\" }\n }\n\n var bidiRE = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;\n\n function BidiSpan(level, from, to) {\n this.level = level;\n this.from = from; this.to = to;\n }\n\n return function(str, direction) {\n var outerType = direction == \"ltr\" ? \"L\" : \"R\";\n\n if (str.length == 0 || direction == \"ltr\" && !bidiRE.test(str)) { return false }\n var len = str.length, types = [];\n for (var i = 0; i < len; ++i)\n { types.push(charType(str.charCodeAt(i))); }\n\n // W1. Examine each non-spacing mark (NSM) in the level run, and\n // change the type of the NSM to the type of the previous\n // character. If the NSM is at the start of the level run, it will\n // get the type of sor.\n for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {\n var type = types[i$1];\n if (type == \"m\") { types[i$1] = prev; }\n else { prev = type; }\n }\n\n // W2. Search backwards from each instance of a European number\n // until the first strong type (R, L, AL, or sor) is found. If an\n // AL is found, change the type of the European number to Arabic\n // number.\n // W3. Change all ALs to R.\n for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {\n var type$1 = types[i$2];\n if (type$1 == \"1\" && cur == \"r\") { types[i$2] = \"n\"; }\n else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == \"r\") { types[i$2] = \"R\"; } }\n }\n\n // W4. A single European separator between two European numbers\n // changes to a European number. A single common separator between\n // two numbers of the same type changes to that type.\n for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {\n var type$2 = types[i$3];\n if (type$2 == \"+\" && prev$1 == \"1\" && types[i$3+1] == \"1\") { types[i$3] = \"1\"; }\n else if (type$2 == \",\" && prev$1 == types[i$3+1] &&\n (prev$1 == \"1\" || prev$1 == \"n\")) { types[i$3] = prev$1; }\n prev$1 = type$2;\n }\n\n // W5. A sequence of European terminators adjacent to European\n // numbers changes to all European numbers.\n // W6. Otherwise, separators and terminators change to Other\n // Neutral.\n for (var i$4 = 0; i$4 < len; ++i$4) {\n var type$3 = types[i$4];\n if (type$3 == \",\") { types[i$4] = \"N\"; }\n else if (type$3 == \"%\") {\n var end = (void 0);\n for (end = i$4 + 1; end < len && types[end] == \"%\"; ++end) {}\n var replace = (i$4 && types[i$4-1] == \"!\") || (end < len && types[end] == \"1\") ? \"1\" : \"N\";\n for (var j = i$4; j < end; ++j) { types[j] = replace; }\n i$4 = end - 1;\n }\n }\n\n // W7. Search backwards from each instance of a European number\n // until the first strong type (R, L, or sor) is found. If an L is\n // found, then change the type of the European number to L.\n for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {\n var type$4 = types[i$5];\n if (cur$1 == \"L\" && type$4 == \"1\") { types[i$5] = \"L\"; }\n else if (isStrong.test(type$4)) { cur$1 = type$4; }\n }\n\n // N1. A sequence of neutrals takes the direction of the\n // surrounding strong text if the text on both sides has the same\n // direction. European and Arabic numbers act as if they were R in\n // terms of their influence on neutrals. Start-of-level-run (sor)\n // and end-of-level-run (eor) are used at level run boundaries.\n // N2. Any remaining neutrals take the embedding direction.\n for (var i$6 = 0; i$6 < len; ++i$6) {\n if (isNeutral.test(types[i$6])) {\n var end$1 = (void 0);\n for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}\n var before = (i$6 ? types[i$6-1] : outerType) == \"L\";\n var after = (end$1 < len ? types[end$1] : outerType) == \"L\";\n var replace$1 = before == after ? (before ? \"L\" : \"R\") : outerType;\n for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }\n i$6 = end$1 - 1;\n }\n }\n\n // Here we depart from the documented algorithm, in order to avoid\n // building up an actual levels array. Since there are only three\n // levels (0, 1, 2) in an implementation that doesn't take\n // explicit embedding into account, we can build up the order on\n // the fly, without following the level-based algorithm.\n var order = [], m;\n for (var i$7 = 0; i$7 < len;) {\n if (countsAsLeft.test(types[i$7])) {\n var start = i$7;\n for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}\n order.push(new BidiSpan(0, start, i$7));\n } else {\n var pos = i$7, at = order.length;\n for (++i$7; i$7 < len && types[i$7] != \"L\"; ++i$7) {}\n for (var j$2 = pos; j$2 < i$7;) {\n if (countsAsNum.test(types[j$2])) {\n if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }\n var nstart = j$2;\n for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}\n order.splice(at, 0, new BidiSpan(2, nstart, j$2));\n pos = j$2;\n } else { ++j$2; }\n }\n if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }\n }\n }\n if (direction == \"ltr\") {\n if (order[0].level == 1 && (m = str.match(/^\\s+/))) {\n order[0].from = m[0].length;\n order.unshift(new BidiSpan(0, 0, m[0].length));\n }\n if (lst(order).level == 1 && (m = str.match(/\\s+$/))) {\n lst(order).to -= m[0].length;\n order.push(new BidiSpan(0, len - m[0].length, len));\n }\n }\n\n return direction == \"rtl\" ? order.reverse() : order\n }\n })();\n\n // Get the bidi ordering for the given line (and cache it). Returns\n // false for lines that are fully left-to-right, and an array of\n // BidiSpan objects otherwise.\n function getOrder(line, direction) {\n var order = line.order;\n if (order == null) { order = line.order = bidiOrdering(line.text, direction); }\n return order\n }\n\n // EVENT HANDLING\n\n // Lightweight event framework. on/off also work on DOM nodes,\n // registering native DOM handlers.\n\n var noHandlers = [];\n\n var on = function(emitter, type, f) {\n if (emitter.addEventListener) {\n emitter.addEventListener(type, f, false);\n } else if (emitter.attachEvent) {\n emitter.attachEvent(\"on\" + type, f);\n } else {\n var map$$1 = emitter._handlers || (emitter._handlers = {});\n map$$1[type] = (map$$1[type] || noHandlers).concat(f);\n }\n };\n\n function getHandlers(emitter, type) {\n return emitter._handlers && emitter._handlers[type] || noHandlers\n }\n\n function off(emitter, type, f) {\n if (emitter.removeEventListener) {\n emitter.removeEventListener(type, f, false);\n } else if (emitter.detachEvent) {\n emitter.detachEvent(\"on\" + type, f);\n } else {\n var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];\n if (arr) {\n var index = indexOf(arr, f);\n if (index > -1)\n { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }\n }\n }\n }\n\n function signal(emitter, type /*, values...*/) {\n var handlers = getHandlers(emitter, type);\n if (!handlers.length) { return }\n var args = Array.prototype.slice.call(arguments, 2);\n for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }\n }\n\n // The DOM events that CodeMirror handles can be overridden by\n // registering a (non-DOM) handler on the editor for the event name,\n // and preventDefault-ing the event in that handler.\n function signalDOMEvent(cm, e, override) {\n if (typeof e == \"string\")\n { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }\n signal(cm, override || e.type, cm, e);\n return e_defaultPrevented(e) || e.codemirrorIgnore\n }\n\n function signalCursorActivity(cm) {\n var arr = cm._handlers && cm._handlers.cursorActivity;\n if (!arr) { return }\n var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);\n for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)\n { set.push(arr[i]); } }\n }\n\n function hasHandler(emitter, type) {\n return getHandlers(emitter, type).length > 0\n }\n\n // Add on and off methods to a constructor's prototype, to make\n // registering events on such objects more convenient.\n function eventMixin(ctor) {\n ctor.prototype.on = function(type, f) {on(this, type, f);};\n ctor.prototype.off = function(type, f) {off(this, type, f);};\n }\n\n // Due to the fact that we still support jurassic IE versions, some\n // compatibility wrappers are needed.\n\n function e_preventDefault(e) {\n if (e.preventDefault) { e.preventDefault(); }\n else { e.returnValue = false; }\n }\n function e_stopPropagation(e) {\n if (e.stopPropagation) { e.stopPropagation(); }\n else { e.cancelBubble = true; }\n }\n function e_defaultPrevented(e) {\n return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false\n }\n function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}\n\n function e_target(e) {return e.target || e.srcElement}\n function e_button(e) {\n var b = e.which;\n if (b == null) {\n if (e.button & 1) { b = 1; }\n else if (e.button & 2) { b = 3; }\n else if (e.button & 4) { b = 2; }\n }\n if (mac && e.ctrlKey && b == 1) { b = 3; }\n return b\n }\n\n // Detect drag-and-drop\n var dragAndDrop = function() {\n // There is *some* kind of drag-and-drop support in IE6-8, but I\n // couldn't get it to work yet.\n if (ie && ie_version < 9) { return false }\n var div = elt('div');\n return \"draggable\" in div || \"dragDrop\" in div\n }();\n\n var zwspSupported;\n function zeroWidthElement(measure) {\n if (zwspSupported == null) {\n var test = elt(\"span\", \"\\u200b\");\n removeChildrenAndAdd(measure, elt(\"span\", [test, document.createTextNode(\"x\")]));\n if (measure.firstChild.offsetHeight != 0)\n { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }\n }\n var node = zwspSupported ? elt(\"span\", \"\\u200b\") :\n elt(\"span\", \"\\u00a0\", null, \"display: inline-block; width: 1px; margin-right: -1px\");\n node.setAttribute(\"cm-text\", \"\");\n return node\n }\n\n // Feature-detect IE's crummy client rect reporting for bidi text\n var badBidiRects;\n function hasBadBidiRects(measure) {\n if (badBidiRects != null) { return badBidiRects }\n var txt = removeChildrenAndAdd(measure, document.createTextNode(\"A\\u062eA\"));\n var r0 = range(txt, 0, 1).getBoundingClientRect();\n var r1 = range(txt, 1, 2).getBoundingClientRect();\n removeChildren(measure);\n if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)\n return badBidiRects = (r1.right - r0.right < 3)\n }\n\n // See if \"\".split is the broken IE version, if so, provide an\n // alternative way to split lines.\n var splitLinesAuto = \"\\n\\nb\".split(/\\n/).length != 3 ? function (string) {\n var pos = 0, result = [], l = string.length;\n while (pos <= l) {\n var nl = string.indexOf(\"\\n\", pos);\n if (nl == -1) { nl = string.length; }\n var line = string.slice(pos, string.charAt(nl - 1) == \"\\r\" ? nl - 1 : nl);\n var rt = line.indexOf(\"\\r\");\n if (rt != -1) {\n result.push(line.slice(0, rt));\n pos += rt + 1;\n } else {\n result.push(line);\n pos = nl + 1;\n }\n }\n return result\n } : function (string) { return string.split(/\\r\\n?|\\n/); };\n\n var hasSelection = window.getSelection ? function (te) {\n try { return te.selectionStart != te.selectionEnd }\n catch(e) { return false }\n } : function (te) {\n var range$$1;\n try {range$$1 = te.ownerDocument.selection.createRange();}\n catch(e) {}\n if (!range$$1 || range$$1.parentElement() != te) { return false }\n return range$$1.compareEndPoints(\"StartToEnd\", range$$1) != 0\n };\n\n var hasCopyEvent = (function () {\n var e = elt(\"div\");\n if (\"oncopy\" in e) { return true }\n e.setAttribute(\"oncopy\", \"return;\");\n return typeof e.oncopy == \"function\"\n })();\n\n var badZoomedRects = null;\n function hasBadZoomedRects(measure) {\n if (badZoomedRects != null) { return badZoomedRects }\n var node = removeChildrenAndAdd(measure, elt(\"span\", \"x\"));\n var normal = node.getBoundingClientRect();\n var fromRange = range(node, 0, 1).getBoundingClientRect();\n return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1\n }\n\n // Known modes, by name and by MIME\n var modes = {}, mimeModes = {};\n\n // Extra arguments are stored as the mode's dependencies, which is\n // used by (legacy) mechanisms like loadmode.js to automatically\n // load a mode. (Preferred mechanism is the require/define calls.)\n function defineMode(name, mode) {\n if (arguments.length > 2)\n { mode.dependencies = Array.prototype.slice.call(arguments, 2); }\n modes[name] = mode;\n }\n\n function defineMIME(mime, spec) {\n mimeModes[mime] = spec;\n }\n\n // Given a MIME type, a {name, ...options} config object, or a name\n // string, return a mode config object.\n function resolveMode(spec) {\n if (typeof spec == \"string\" && mimeModes.hasOwnProperty(spec)) {\n spec = mimeModes[spec];\n } else if (spec && typeof spec.name == \"string\" && mimeModes.hasOwnProperty(spec.name)) {\n var found = mimeModes[spec.name];\n if (typeof found == \"string\") { found = {name: found}; }\n spec = createObj(found, spec);\n spec.name = found.name;\n } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+xml$/.test(spec)) {\n return resolveMode(\"application/xml\")\n } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+json$/.test(spec)) {\n return resolveMode(\"application/json\")\n }\n if (typeof spec == \"string\") { return {name: spec} }\n else { return spec || {name: \"null\"} }\n }\n\n // Given a mode spec (anything that resolveMode accepts), find and\n // initialize an actual mode object.\n function getMode(options, spec) {\n spec = resolveMode(spec);\n var mfactory = modes[spec.name];\n if (!mfactory) { return getMode(options, \"text/plain\") }\n var modeObj = mfactory(options, spec);\n if (modeExtensions.hasOwnProperty(spec.name)) {\n var exts = modeExtensions[spec.name];\n for (var prop in exts) {\n if (!exts.hasOwnProperty(prop)) { continue }\n if (modeObj.hasOwnProperty(prop)) { modeObj[\"_\" + prop] = modeObj[prop]; }\n modeObj[prop] = exts[prop];\n }\n }\n modeObj.name = spec.name;\n if (spec.helperType) { modeObj.helperType = spec.helperType; }\n if (spec.modeProps) { for (var prop$1 in spec.modeProps)\n { modeObj[prop$1] = spec.modeProps[prop$1]; } }\n\n return modeObj\n }\n\n // This can be used to attach properties to mode objects from\n // outside the actual mode definition.\n var modeExtensions = {};\n function extendMode(mode, properties) {\n var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});\n copyObj(properties, exts);\n }\n\n function copyState(mode, state) {\n if (state === true) { return state }\n if (mode.copyState) { return mode.copyState(state) }\n var nstate = {};\n for (var n in state) {\n var val = state[n];\n if (val instanceof Array) { val = val.concat([]); }\n nstate[n] = val;\n }\n return nstate\n }\n\n // Given a mode and a state (for that mode), find the inner mode and\n // state at the position that the state refers to.\n function innerMode(mode, state) {\n var info;\n while (mode.innerMode) {\n info = mode.innerMode(state);\n if (!info || info.mode == mode) { break }\n state = info.state;\n mode = info.mode;\n }\n return info || {mode: mode, state: state}\n }\n\n function startState(mode, a1, a2) {\n return mode.startState ? mode.startState(a1, a2) : true\n }\n\n // STRING STREAM\n\n // Fed to the mode parsers, provides helper functions to make\n // parsers more succinct.\n\n var StringStream = function(string, tabSize, lineOracle) {\n this.pos = this.start = 0;\n this.string = string;\n this.tabSize = tabSize || 8;\n this.lastColumnPos = this.lastColumnValue = 0;\n this.lineStart = 0;\n this.lineOracle = lineOracle;\n };\n\n StringStream.prototype.eol = function () {return this.pos >= this.string.length};\n StringStream.prototype.sol = function () {return this.pos == this.lineStart};\n StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};\n StringStream.prototype.next = function () {\n if (this.pos < this.string.length)\n { return this.string.charAt(this.pos++) }\n };\n StringStream.prototype.eat = function (match) {\n var ch = this.string.charAt(this.pos);\n var ok;\n if (typeof match == \"string\") { ok = ch == match; }\n else { ok = ch && (match.test ? match.test(ch) : match(ch)); }\n if (ok) {++this.pos; return ch}\n };\n StringStream.prototype.eatWhile = function (match) {\n var start = this.pos;\n while (this.eat(match)){}\n return this.pos > start\n };\n StringStream.prototype.eatSpace = function () {\n var this$1 = this;\n\n var start = this.pos;\n while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }\n return this.pos > start\n };\n StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};\n StringStream.prototype.skipTo = function (ch) {\n var found = this.string.indexOf(ch, this.pos);\n if (found > -1) {this.pos = found; return true}\n };\n StringStream.prototype.backUp = function (n) {this.pos -= n;};\n StringStream.prototype.column = function () {\n if (this.lastColumnPos < this.start) {\n this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);\n this.lastColumnPos = this.start;\n }\n return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n };\n StringStream.prototype.indentation = function () {\n return countColumn(this.string, null, this.tabSize) -\n (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n };\n StringStream.prototype.match = function (pattern, consume, caseInsensitive) {\n if (typeof pattern == \"string\") {\n var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };\n var substr = this.string.substr(this.pos, pattern.length);\n if (cased(substr) == cased(pattern)) {\n if (consume !== false) { this.pos += pattern.length; }\n return true\n }\n } else {\n var match = this.string.slice(this.pos).match(pattern);\n if (match && match.index > 0) { return null }\n if (match && consume !== false) { this.pos += match[0].length; }\n return match\n }\n };\n StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};\n StringStream.prototype.hideFirstChars = function (n, inner) {\n this.lineStart += n;\n try { return inner() }\n finally { this.lineStart -= n; }\n };\n StringStream.prototype.lookAhead = function (n) {\n var oracle = this.lineOracle;\n return oracle && oracle.lookAhead(n)\n };\n StringStream.prototype.baseToken = function () {\n var oracle = this.lineOracle;\n return oracle && oracle.baseToken(this.pos)\n };\n\n var SavedContext = function(state, lookAhead) {\n this.state = state;\n this.lookAhead = lookAhead;\n };\n\n var Context = function(doc, state, line, lookAhead) {\n this.state = state;\n this.doc = doc;\n this.line = line;\n this.maxLookAhead = lookAhead || 0;\n this.baseTokens = null;\n this.baseTokenPos = 1;\n };\n\n Context.prototype.lookAhead = function (n) {\n var line = this.doc.getLine(this.line + n);\n if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }\n return line\n };\n\n Context.prototype.baseToken = function (n) {\n var this$1 = this;\n\n if (!this.baseTokens) { return null }\n while (this.baseTokens[this.baseTokenPos] <= n)\n { this$1.baseTokenPos += 2; }\n var type = this.baseTokens[this.baseTokenPos + 1];\n return {type: type && type.replace(/( |^)overlay .*/, \"\"),\n size: this.baseTokens[this.baseTokenPos] - n}\n };\n\n Context.prototype.nextLine = function () {\n this.line++;\n if (this.maxLookAhead > 0) { this.maxLookAhead--; }\n };\n\n Context.fromSaved = function (doc, saved, line) {\n if (saved instanceof SavedContext)\n { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }\n else\n { return new Context(doc, copyState(doc.mode, saved), line) }\n };\n\n Context.prototype.save = function (copy) {\n var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;\n return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state\n };\n\n\n // Compute a style array (an array starting with a mode generation\n // -- for invalidation -- followed by pairs of end positions and\n // style strings), which is used to highlight the tokens on the\n // line.\n function highlightLine(cm, line, context, forceToEnd) {\n // A styles array always starts with a number identifying the\n // mode/overlays that it is based on (for easy invalidation).\n var st = [cm.state.modeGen], lineClasses = {};\n // Compute the base array of styles\n runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },\n lineClasses, forceToEnd);\n var state = context.state;\n\n // Run overlays, adjust style array.\n var loop = function ( o ) {\n context.baseTokens = st;\n var overlay = cm.state.overlays[o], i = 1, at = 0;\n context.state = true;\n runMode(cm, line.text, overlay.mode, context, function (end, style) {\n var start = i;\n // Ensure there's a token end at the current position, and that i points at it\n while (at < end) {\n var i_end = st[i];\n if (i_end > end)\n { st.splice(i, 1, end, st[i+1], i_end); }\n i += 2;\n at = Math.min(end, i_end);\n }\n if (!style) { return }\n if (overlay.opaque) {\n st.splice(start, i - start, end, \"overlay \" + style);\n i = start + 2;\n } else {\n for (; start < i; start += 2) {\n var cur = st[start+1];\n st[start+1] = (cur ? cur + \" \" : \"\") + \"overlay \" + style;\n }\n }\n }, lineClasses);\n context.state = state;\n context.baseTokens = null;\n context.baseTokenPos = 1;\n };\n\n for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );\n\n return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}\n }\n\n function getLineStyles(cm, line, updateFrontier) {\n if (!line.styles || line.styles[0] != cm.state.modeGen) {\n var context = getContextBefore(cm, lineNo(line));\n var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);\n var result = highlightLine(cm, line, context);\n if (resetState) { context.state = resetState; }\n line.stateAfter = context.save(!resetState);\n line.styles = result.styles;\n if (result.classes) { line.styleClasses = result.classes; }\n else if (line.styleClasses) { line.styleClasses = null; }\n if (updateFrontier === cm.doc.highlightFrontier)\n { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }\n }\n return line.styles\n }\n\n function getContextBefore(cm, n, precise) {\n var doc = cm.doc, display = cm.display;\n if (!doc.mode.startState) { return new Context(doc, true, n) }\n var start = findStartLine(cm, n, precise);\n var saved = start > doc.first && getLine(doc, start - 1).stateAfter;\n var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);\n\n doc.iter(start, n, function (line) {\n processLine(cm, line.text, context);\n var pos = context.line;\n line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;\n context.nextLine();\n });\n if (precise) { doc.modeFrontier = context.line; }\n return context\n }\n\n // Lightweight form of highlight -- proceed over this line and\n // update state, but don't save a style array. Used for lines that\n // aren't currently visible.\n function processLine(cm, text, context, startAt) {\n var mode = cm.doc.mode;\n var stream = new StringStream(text, cm.options.tabSize, context);\n stream.start = stream.pos = startAt || 0;\n if (text == \"\") { callBlankLine(mode, context.state); }\n while (!stream.eol()) {\n readToken(mode, stream, context.state);\n stream.start = stream.pos;\n }\n }\n\n function callBlankLine(mode, state) {\n if (mode.blankLine) { return mode.blankLine(state) }\n if (!mode.innerMode) { return }\n var inner = innerMode(mode, state);\n if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }\n }\n\n function readToken(mode, stream, state, inner) {\n for (var i = 0; i < 10; i++) {\n if (inner) { inner[0] = innerMode(mode, state).mode; }\n var style = mode.token(stream, state);\n if (stream.pos > stream.start) { return style }\n }\n throw new Error(\"Mode \" + mode.name + \" failed to advance stream.\")\n }\n\n var Token = function(stream, type, state) {\n this.start = stream.start; this.end = stream.pos;\n this.string = stream.current();\n this.type = type || null;\n this.state = state;\n };\n\n // Utility for getTokenAt and getLineTokens\n function takeToken(cm, pos, precise, asArray) {\n var doc = cm.doc, mode = doc.mode, style;\n pos = clipPos(doc, pos);\n var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);\n var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;\n if (asArray) { tokens = []; }\n while ((asArray || stream.pos < pos.ch) && !stream.eol()) {\n stream.start = stream.pos;\n style = readToken(mode, stream, context.state);\n if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }\n }\n return asArray ? tokens : new Token(stream, style, context.state)\n }\n\n function extractLineClasses(type, output) {\n if (type) { for (;;) {\n var lineClass = type.match(/(?:^|\\s+)line-(background-)?(\\S+)/);\n if (!lineClass) { break }\n type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);\n var prop = lineClass[1] ? \"bgClass\" : \"textClass\";\n if (output[prop] == null)\n { output[prop] = lineClass[2]; }\n else if (!(new RegExp(\"(?:^|\\s)\" + lineClass[2] + \"(?:$|\\s)\")).test(output[prop]))\n { output[prop] += \" \" + lineClass[2]; }\n } }\n return type\n }\n\n // Run the given mode's parser over a line, calling f for each token.\n function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {\n var flattenSpans = mode.flattenSpans;\n if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }\n var curStart = 0, curStyle = null;\n var stream = new StringStream(text, cm.options.tabSize, context), style;\n var inner = cm.options.addModeClass && [null];\n if (text == \"\") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }\n while (!stream.eol()) {\n if (stream.pos > cm.options.maxHighlightLength) {\n flattenSpans = false;\n if (forceToEnd) { processLine(cm, text, context, stream.pos); }\n stream.pos = text.length;\n style = null;\n } else {\n style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);\n }\n if (inner) {\n var mName = inner[0].name;\n if (mName) { style = \"m-\" + (style ? mName + \" \" + style : mName); }\n }\n if (!flattenSpans || curStyle != style) {\n while (curStart < stream.start) {\n curStart = Math.min(stream.start, curStart + 5000);\n f(curStart, curStyle);\n }\n curStyle = style;\n }\n stream.start = stream.pos;\n }\n while (curStart < stream.pos) {\n // Webkit seems to refuse to render text nodes longer than 57444\n // characters, and returns inaccurate measurements in nodes\n // starting around 5000 chars.\n var pos = Math.min(stream.pos, curStart + 5000);\n f(pos, curStyle);\n curStart = pos;\n }\n }\n\n // Finds the line to start with when starting a parse. Tries to\n // find a line with a stateAfter, so that it can start with a\n // valid state. If that fails, it returns the line with the\n // smallest indentation, which tends to need the least context to\n // parse correctly.\n function findStartLine(cm, n, precise) {\n var minindent, minline, doc = cm.doc;\n var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);\n for (var search = n; search > lim; --search) {\n if (search <= doc.first) { return doc.first }\n var line = getLine(doc, search - 1), after = line.stateAfter;\n if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))\n { return search }\n var indented = countColumn(line.text, null, cm.options.tabSize);\n if (minline == null || minindent > indented) {\n minline = search - 1;\n minindent = indented;\n }\n }\n return minline\n }\n\n function retreatFrontier(doc, n) {\n doc.modeFrontier = Math.min(doc.modeFrontier, n);\n if (doc.highlightFrontier < n - 10) { return }\n var start = doc.first;\n for (var line = n - 1; line > start; line--) {\n var saved = getLine(doc, line).stateAfter;\n // change is on 3\n // state on line 1 looked ahead 2 -- so saw 3\n // test 1 + 2 < 3 should cover this\n if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {\n start = line + 1;\n break\n }\n }\n doc.highlightFrontier = Math.min(doc.highlightFrontier, start);\n }\n\n // LINE DATA STRUCTURE\n\n // Line objects. These hold state related to a line, including\n // highlighting info (the styles array).\n var Line = function(text, markedSpans, estimateHeight) {\n this.text = text;\n attachMarkedSpans(this, markedSpans);\n this.height = estimateHeight ? estimateHeight(this) : 1;\n };\n\n Line.prototype.lineNo = function () { return lineNo(this) };\n eventMixin(Line);\n\n // Change the content (text, markers) of a line. Automatically\n // invalidates cached information and tries to re-estimate the\n // line's height.\n function updateLine(line, text, markedSpans, estimateHeight) {\n line.text = text;\n if (line.stateAfter) { line.stateAfter = null; }\n if (line.styles) { line.styles = null; }\n if (line.order != null) { line.order = null; }\n detachMarkedSpans(line);\n attachMarkedSpans(line, markedSpans);\n var estHeight = estimateHeight ? estimateHeight(line) : 1;\n if (estHeight != line.height) { updateLineHeight(line, estHeight); }\n }\n\n // Detach a line from the document tree and its markers.\n function cleanUpLine(line) {\n line.parent = null;\n detachMarkedSpans(line);\n }\n\n // Convert a style as returned by a mode (either null, or a string\n // containing one or more styles) to a CSS style. This is cached,\n // and also looks for line-wide styles.\n var styleToClassCache = {}, styleToClassCacheWithMode = {};\n function interpretTokenStyle(style, options) {\n if (!style || /^\\s*$/.test(style)) { return null }\n var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;\n return cache[style] ||\n (cache[style] = style.replace(/\\S+/g, \"cm-$&\"))\n }\n\n // Render the DOM representation of the text of a line. Also builds\n // up a 'line map', which points at the DOM nodes that represent\n // specific stretches of text, and is used by the measuring code.\n // The returned object contains the DOM node, this map, and\n // information about line-wide styles that were set by the mode.\n function buildLineContent(cm, lineView) {\n // The padding-right forces the element to have a 'border', which\n // is needed on Webkit to be able to get line-level bounding\n // rectangles for it (in measureChar).\n var content = eltP(\"span\", null, null, webkit ? \"padding-right: .1px\" : null);\n var builder = {pre: eltP(\"pre\", [content], \"CodeMirror-line\"), content: content,\n col: 0, pos: 0, cm: cm,\n trailingSpace: false,\n splitSpaces: cm.getOption(\"lineWrapping\")};\n lineView.measure = {};\n\n // Iterate over the logical lines that make up this visual line.\n for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {\n var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);\n builder.pos = 0;\n builder.addToken = buildToken;\n // Optionally wire in some hacks into the token-rendering\n // algorithm, to deal with browser quirks.\n if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))\n { builder.addToken = buildTokenBadBidi(builder.addToken, order); }\n builder.map = [];\n var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);\n insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));\n if (line.styleClasses) {\n if (line.styleClasses.bgClass)\n { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || \"\"); }\n if (line.styleClasses.textClass)\n { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || \"\"); }\n }\n\n // Ensure at least a single node is present, for measuring.\n if (builder.map.length == 0)\n { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }\n\n // Store the map and a cache object for the current logical line\n if (i == 0) {\n lineView.measure.map = builder.map;\n lineView.measure.cache = {};\n } else {\n (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)\n ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});\n }\n }\n\n // See issue #2901\n if (webkit) {\n var last = builder.content.lastChild;\n if (/\\bcm-tab\\b/.test(last.className) || (last.querySelector && last.querySelector(\".cm-tab\")))\n { builder.content.className = \"cm-tab-wrap-hack\"; }\n }\n\n signal(cm, \"renderLine\", cm, lineView.line, builder.pre);\n if (builder.pre.className)\n { builder.textClass = joinClasses(builder.pre.className, builder.textClass || \"\"); }\n\n return builder\n }\n\n function defaultSpecialCharPlaceholder(ch) {\n var token = elt(\"span\", \"\\u2022\", \"cm-invalidchar\");\n token.title = \"\\\\u\" + ch.charCodeAt(0).toString(16);\n token.setAttribute(\"aria-label\", token.title);\n return token\n }\n\n // Build up the DOM representation for a single token, and add it to\n // the line map. Takes care to render special characters separately.\n function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {\n if (!text) { return }\n var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;\n var special = builder.cm.state.specialChars, mustWrap = false;\n var content;\n if (!special.test(text)) {\n builder.col += text.length;\n content = document.createTextNode(displayText);\n builder.map.push(builder.pos, builder.pos + text.length, content);\n if (ie && ie_version < 9) { mustWrap = true; }\n builder.pos += text.length;\n } else {\n content = document.createDocumentFragment();\n var pos = 0;\n while (true) {\n special.lastIndex = pos;\n var m = special.exec(text);\n var skipped = m ? m.index - pos : text.length - pos;\n if (skipped) {\n var txt = document.createTextNode(displayText.slice(pos, pos + skipped));\n if (ie && ie_version < 9) { content.appendChild(elt(\"span\", [txt])); }\n else { content.appendChild(txt); }\n builder.map.push(builder.pos, builder.pos + skipped, txt);\n builder.col += skipped;\n builder.pos += skipped;\n }\n if (!m) { break }\n pos += skipped + 1;\n var txt$1 = (void 0);\n if (m[0] == \"\\t\") {\n var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;\n txt$1 = content.appendChild(elt(\"span\", spaceStr(tabWidth), \"cm-tab\"));\n txt$1.setAttribute(\"role\", \"presentation\");\n txt$1.setAttribute(\"cm-text\", \"\\t\");\n builder.col += tabWidth;\n } else if (m[0] == \"\\r\" || m[0] == \"\\n\") {\n txt$1 = content.appendChild(elt(\"span\", m[0] == \"\\r\" ? \"\\u240d\" : \"\\u2424\", \"cm-invalidchar\"));\n txt$1.setAttribute(\"cm-text\", m[0]);\n builder.col += 1;\n } else {\n txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);\n txt$1.setAttribute(\"cm-text\", m[0]);\n if (ie && ie_version < 9) { content.appendChild(elt(\"span\", [txt$1])); }\n else { content.appendChild(txt$1); }\n builder.col += 1;\n }\n builder.map.push(builder.pos, builder.pos + 1, txt$1);\n builder.pos++;\n }\n }\n builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;\n if (style || startStyle || endStyle || mustWrap || css) {\n var fullStyle = style || \"\";\n if (startStyle) { fullStyle += startStyle; }\n if (endStyle) { fullStyle += endStyle; }\n var token = elt(\"span\", [content], fullStyle, css);\n if (attributes) {\n for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != \"style\" && attr != \"class\")\n { token.setAttribute(attr, attributes[attr]); } }\n }\n return builder.content.appendChild(token)\n }\n builder.content.appendChild(content);\n }\n\n // Change some spaces to NBSP to prevent the browser from collapsing\n // trailing spaces at the end of a line when rendering text (issue #1362).\n function splitSpaces(text, trailingBefore) {\n if (text.length > 1 && !/ /.test(text)) { return text }\n var spaceBefore = trailingBefore, result = \"\";\n for (var i = 0; i < text.length; i++) {\n var ch = text.charAt(i);\n if (ch == \" \" && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))\n { ch = \"\\u00a0\"; }\n result += ch;\n spaceBefore = ch == \" \";\n }\n return result\n }\n\n // Work around nonsense dimensions being reported for stretches of\n // right-to-left text.\n function buildTokenBadBidi(inner, order) {\n return function (builder, text, style, startStyle, endStyle, css, attributes) {\n style = style ? style + \" cm-force-border\" : \"cm-force-border\";\n var start = builder.pos, end = start + text.length;\n for (;;) {\n // Find the part that overlaps with the start of this text\n var part = (void 0);\n for (var i = 0; i < order.length; i++) {\n part = order[i];\n if (part.to > start && part.from <= start) { break }\n }\n if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }\n inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);\n startStyle = null;\n text = text.slice(part.to - start);\n start = part.to;\n }\n }\n }\n\n function buildCollapsedSpan(builder, size, marker, ignoreWidget) {\n var widget = !ignoreWidget && marker.widgetNode;\n if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }\n if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {\n if (!widget)\n { widget = builder.content.appendChild(document.createElement(\"span\")); }\n widget.setAttribute(\"cm-marker\", marker.id);\n }\n if (widget) {\n builder.cm.display.input.setUneditable(widget);\n builder.content.appendChild(widget);\n }\n builder.pos += size;\n builder.trailingSpace = false;\n }\n\n // Outputs a number of spans to make up a line, taking highlighting\n // and marked text into account.\n function insertLineContent(line, builder, styles) {\n var spans = line.markedSpans, allText = line.text, at = 0;\n if (!spans) {\n for (var i$1 = 1; i$1 < styles.length; i$1+=2)\n { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }\n return\n }\n\n var len = allText.length, pos = 0, i = 1, text = \"\", style, css;\n var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;\n for (;;) {\n if (nextChange == pos) { // Update current marker set\n spanStyle = spanEndStyle = spanStartStyle = css = \"\";\n attributes = null;\n collapsed = null; nextChange = Infinity;\n var foundBookmarks = [], endStyles = (void 0);\n for (var j = 0; j < spans.length; ++j) {\n var sp = spans[j], m = sp.marker;\n if (m.type == \"bookmark\" && sp.from == pos && m.widgetNode) {\n foundBookmarks.push(m);\n } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {\n if (sp.to != null && sp.to != pos && nextChange > sp.to) {\n nextChange = sp.to;\n spanEndStyle = \"\";\n }\n if (m.className) { spanStyle += \" \" + m.className; }\n if (m.css) { css = (css ? css + \";\" : \"\") + m.css; }\n if (m.startStyle && sp.from == pos) { spanStartStyle += \" \" + m.startStyle; }\n if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }\n // support for the old title property\n // https://github.com/codemirror/CodeMirror/pull/5673\n if (m.title) { (attributes || (attributes = {})).title = m.title; }\n if (m.attributes) {\n for (var attr in m.attributes)\n { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }\n }\n if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))\n { collapsed = sp; }\n } else if (sp.from > pos && nextChange > sp.from) {\n nextChange = sp.from;\n }\n }\n if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)\n { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += \" \" + endStyles[j$1]; } } }\n\n if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)\n { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }\n if (collapsed && (collapsed.from || 0) == pos) {\n buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,\n collapsed.marker, collapsed.from == null);\n if (collapsed.to == null) { return }\n if (collapsed.to == pos) { collapsed = false; }\n }\n }\n if (pos >= len) { break }\n\n var upto = Math.min(len, nextChange);\n while (true) {\n if (text) {\n var end = pos + text.length;\n if (!collapsed) {\n var tokenText = end > upto ? text.slice(0, upto - pos) : text;\n builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,\n spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : \"\", css, attributes);\n }\n if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}\n pos = end;\n spanStartStyle = \"\";\n }\n text = allText.slice(at, at = styles[i++]);\n style = interpretTokenStyle(styles[i++], builder.cm.options);\n }\n }\n }\n\n\n // These objects are used to represent the visible (currently drawn)\n // part of the document. A LineView may correspond to multiple\n // logical lines, if those are connected by collapsed ranges.\n function LineView(doc, line, lineN) {\n // The starting line\n this.line = line;\n // Continuing lines, if any\n this.rest = visualLineContinued(line);\n // Number of logical lines in this visual line\n this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;\n this.node = this.text = null;\n this.hidden = lineIsHidden(doc, line);\n }\n\n // Create a range of LineView objects for the given lines.\n function buildViewArray(cm, from, to) {\n var array = [], nextPos;\n for (var pos = from; pos < to; pos = nextPos) {\n var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);\n nextPos = pos + view.size;\n array.push(view);\n }\n return array\n }\n\n var operationGroup = null;\n\n function pushOperation(op) {\n if (operationGroup) {\n operationGroup.ops.push(op);\n } else {\n op.ownsGroup = operationGroup = {\n ops: [op],\n delayedCallbacks: []\n };\n }\n }\n\n function fireCallbacksForOps(group) {\n // Calls delayed callbacks and cursorActivity handlers until no\n // new ones appear\n var callbacks = group.delayedCallbacks, i = 0;\n do {\n for (; i < callbacks.length; i++)\n { callbacks[i].call(null); }\n for (var j = 0; j < group.ops.length; j++) {\n var op = group.ops[j];\n if (op.cursorActivityHandlers)\n { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)\n { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }\n }\n } while (i < callbacks.length)\n }\n\n function finishOperation(op, endCb) {\n var group = op.ownsGroup;\n if (!group) { return }\n\n try { fireCallbacksForOps(group); }\n finally {\n operationGroup = null;\n endCb(group);\n }\n }\n\n var orphanDelayedCallbacks = null;\n\n // Often, we want to signal events at a point where we are in the\n // middle of some work, but don't want the handler to start calling\n // other methods on the editor, which might be in an inconsistent\n // state or simply not expect any other events to happen.\n // signalLater looks whether there are any handlers, and schedules\n // them to be executed when the last operation ends, or, if no\n // operation is active, when a timeout fires.\n function signalLater(emitter, type /*, values...*/) {\n var arr = getHandlers(emitter, type);\n if (!arr.length) { return }\n var args = Array.prototype.slice.call(arguments, 2), list;\n if (operationGroup) {\n list = operationGroup.delayedCallbacks;\n } else if (orphanDelayedCallbacks) {\n list = orphanDelayedCallbacks;\n } else {\n list = orphanDelayedCallbacks = [];\n setTimeout(fireOrphanDelayed, 0);\n }\n var loop = function ( i ) {\n list.push(function () { return arr[i].apply(null, args); });\n };\n\n for (var i = 0; i < arr.length; ++i)\n loop( i );\n }\n\n function fireOrphanDelayed() {\n var delayed = orphanDelayedCallbacks;\n orphanDelayedCallbacks = null;\n for (var i = 0; i < delayed.length; ++i) { delayed[i](); }\n }\n\n // When an aspect of a line changes, a string is added to\n // lineView.changes. This updates the relevant part of the line's\n // DOM structure.\n function updateLineForChanges(cm, lineView, lineN, dims) {\n for (var j = 0; j < lineView.changes.length; j++) {\n var type = lineView.changes[j];\n if (type == \"text\") { updateLineText(cm, lineView); }\n else if (type == \"gutter\") { updateLineGutter(cm, lineView, lineN, dims); }\n else if (type == \"class\") { updateLineClasses(cm, lineView); }\n else if (type == \"widget\") { updateLineWidgets(cm, lineView, dims); }\n }\n lineView.changes = null;\n }\n\n // Lines with gutter elements, widgets or a background class need to\n // be wrapped, and have the extra elements added to the wrapper div\n function ensureLineWrapped(lineView) {\n if (lineView.node == lineView.text) {\n lineView.node = elt(\"div\", null, null, \"position: relative\");\n if (lineView.text.parentNode)\n { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }\n lineView.node.appendChild(lineView.text);\n if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }\n }\n return lineView.node\n }\n\n function updateLineBackground(cm, lineView) {\n var cls = lineView.bgClass ? lineView.bgClass + \" \" + (lineView.line.bgClass || \"\") : lineView.line.bgClass;\n if (cls) { cls += \" CodeMirror-linebackground\"; }\n if (lineView.background) {\n if (cls) { lineView.background.className = cls; }\n else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }\n } else if (cls) {\n var wrap = ensureLineWrapped(lineView);\n lineView.background = wrap.insertBefore(elt(\"div\", null, cls), wrap.firstChild);\n cm.display.input.setUneditable(lineView.background);\n }\n }\n\n // Wrapper around buildLineContent which will reuse the structure\n // in display.externalMeasured when possible.\n function getLineContent(cm, lineView) {\n var ext = cm.display.externalMeasured;\n if (ext && ext.line == lineView.line) {\n cm.display.externalMeasured = null;\n lineView.measure = ext.measure;\n return ext.built\n }\n return buildLineContent(cm, lineView)\n }\n\n // Redraw the line's text. Interacts with the background and text\n // classes because the mode may output tokens that influence these\n // classes.\n function updateLineText(cm, lineView) {\n var cls = lineView.text.className;\n var built = getLineContent(cm, lineView);\n if (lineView.text == lineView.node) { lineView.node = built.pre; }\n lineView.text.parentNode.replaceChild(built.pre, lineView.text);\n lineView.text = built.pre;\n if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {\n lineView.bgClass = built.bgClass;\n lineView.textClass = built.textClass;\n updateLineClasses(cm, lineView);\n } else if (cls) {\n lineView.text.className = cls;\n }\n }\n\n function updateLineClasses(cm, lineView) {\n updateLineBackground(cm, lineView);\n if (lineView.line.wrapClass)\n { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }\n else if (lineView.node != lineView.text)\n { lineView.node.className = \"\"; }\n var textClass = lineView.textClass ? lineView.textClass + \" \" + (lineView.line.textClass || \"\") : lineView.line.textClass;\n lineView.text.className = textClass || \"\";\n }\n\n function updateLineGutter(cm, lineView, lineN, dims) {\n if (lineView.gutter) {\n lineView.node.removeChild(lineView.gutter);\n lineView.gutter = null;\n }\n if (lineView.gutterBackground) {\n lineView.node.removeChild(lineView.gutterBackground);\n lineView.gutterBackground = null;\n }\n if (lineView.line.gutterClass) {\n var wrap = ensureLineWrapped(lineView);\n lineView.gutterBackground = elt(\"div\", null, \"CodeMirror-gutter-background \" + lineView.line.gutterClass,\n (\"left: \" + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + \"px; width: \" + (dims.gutterTotalWidth) + \"px\"));\n cm.display.input.setUneditable(lineView.gutterBackground);\n wrap.insertBefore(lineView.gutterBackground, lineView.text);\n }\n var markers = lineView.line.gutterMarkers;\n if (cm.options.lineNumbers || markers) {\n var wrap$1 = ensureLineWrapped(lineView);\n var gutterWrap = lineView.gutter = elt(\"div\", null, \"CodeMirror-gutter-wrapper\", (\"left: \" + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + \"px\"));\n cm.display.input.setUneditable(gutterWrap);\n wrap$1.insertBefore(gutterWrap, lineView.text);\n if (lineView.line.gutterClass)\n { gutterWrap.className += \" \" + lineView.line.gutterClass; }\n if (cm.options.lineNumbers && (!markers || !markers[\"CodeMirror-linenumbers\"]))\n { lineView.lineNumber = gutterWrap.appendChild(\n elt(\"div\", lineNumberFor(cm.options, lineN),\n \"CodeMirror-linenumber CodeMirror-gutter-elt\",\n (\"left: \" + (dims.gutterLeft[\"CodeMirror-linenumbers\"]) + \"px; width: \" + (cm.display.lineNumInnerWidth) + \"px\"))); }\n if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {\n var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];\n if (found)\n { gutterWrap.appendChild(elt(\"div\", [found], \"CodeMirror-gutter-elt\",\n (\"left: \" + (dims.gutterLeft[id]) + \"px; width: \" + (dims.gutterWidth[id]) + \"px\"))); }\n } }\n }\n }\n\n function updateLineWidgets(cm, lineView, dims) {\n if (lineView.alignable) { lineView.alignable = null; }\n for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {\n next = node.nextSibling;\n if (node.className == \"CodeMirror-linewidget\")\n { lineView.node.removeChild(node); }\n }\n insertLineWidgets(cm, lineView, dims);\n }\n\n // Build a line's DOM representation from scratch\n function buildLineElement(cm, lineView, lineN, dims) {\n var built = getLineContent(cm, lineView);\n lineView.text = lineView.node = built.pre;\n if (built.bgClass) { lineView.bgClass = built.bgClass; }\n if (built.textClass) { lineView.textClass = built.textClass; }\n\n updateLineClasses(cm, lineView);\n updateLineGutter(cm, lineView, lineN, dims);\n insertLineWidgets(cm, lineView, dims);\n return lineView.node\n }\n\n // A lineView may contain multiple logical lines (when merged by\n // collapsed spans). The widgets for all of them need to be drawn.\n function insertLineWidgets(cm, lineView, dims) {\n insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);\n if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)\n { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }\n }\n\n function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {\n if (!line.widgets) { return }\n var wrap = ensureLineWrapped(lineView);\n for (var i = 0, ws = line.widgets; i < ws.length; ++i) {\n var widget = ws[i], node = elt(\"div\", [widget.node], \"CodeMirror-linewidget\");\n if (!widget.handleMouseEvents) { node.setAttribute(\"cm-ignore-events\", \"true\"); }\n positionLineWidget(widget, node, lineView, dims);\n cm.display.input.setUneditable(node);\n if (allowAbove && widget.above)\n { wrap.insertBefore(node, lineView.gutter || lineView.text); }\n else\n { wrap.appendChild(node); }\n signalLater(widget, \"redraw\");\n }\n }\n\n function positionLineWidget(widget, node, lineView, dims) {\n if (widget.noHScroll) {\n (lineView.alignable || (lineView.alignable = [])).push(node);\n var width = dims.wrapperWidth;\n node.style.left = dims.fixedPos + \"px\";\n if (!widget.coverGutter) {\n width -= dims.gutterTotalWidth;\n node.style.paddingLeft = dims.gutterTotalWidth + \"px\";\n }\n node.style.width = width + \"px\";\n }\n if (widget.coverGutter) {\n node.style.zIndex = 5;\n node.style.position = \"relative\";\n if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + \"px\"; }\n }\n }\n\n function widgetHeight(widget) {\n if (widget.height != null) { return widget.height }\n var cm = widget.doc.cm;\n if (!cm) { return 0 }\n if (!contains(document.body, widget.node)) {\n var parentStyle = \"position: relative;\";\n if (widget.coverGutter)\n { parentStyle += \"margin-left: -\" + cm.display.gutters.offsetWidth + \"px;\"; }\n if (widget.noHScroll)\n { parentStyle += \"width: \" + cm.display.wrapper.clientWidth + \"px;\"; }\n removeChildrenAndAdd(cm.display.measure, elt(\"div\", [widget.node], null, parentStyle));\n }\n return widget.height = widget.node.parentNode.offsetHeight\n }\n\n // Return true when the given mouse event happened in a widget\n function eventInWidget(display, e) {\n for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {\n if (!n || (n.nodeType == 1 && n.getAttribute(\"cm-ignore-events\") == \"true\") ||\n (n.parentNode == display.sizer && n != display.mover))\n { return true }\n }\n }\n\n // POSITION MEASUREMENT\n\n function paddingTop(display) {return display.lineSpace.offsetTop}\n function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}\n function paddingH(display) {\n if (display.cachedPaddingH) { return display.cachedPaddingH }\n var e = removeChildrenAndAdd(display.measure, elt(\"pre\", \"x\"));\n var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;\n var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};\n if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }\n return data\n }\n\n function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }\n function displayWidth(cm) {\n return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth\n }\n function displayHeight(cm) {\n return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight\n }\n\n // Ensure the lineView.wrapping.heights array is populated. This is\n // an array of bottom offsets for the lines that make up a drawn\n // line. When lineWrapping is on, there might be more than one\n // height.\n function ensureLineHeights(cm, lineView, rect) {\n var wrapping = cm.options.lineWrapping;\n var curWidth = wrapping && displayWidth(cm);\n if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {\n var heights = lineView.measure.heights = [];\n if (wrapping) {\n lineView.measure.width = curWidth;\n var rects = lineView.text.firstChild.getClientRects();\n for (var i = 0; i < rects.length - 1; i++) {\n var cur = rects[i], next = rects[i + 1];\n if (Math.abs(cur.bottom - next.bottom) > 2)\n { heights.push((cur.bottom + next.top) / 2 - rect.top); }\n }\n }\n heights.push(rect.bottom - rect.top);\n }\n }\n\n // Find a line map (mapping character offsets to text nodes) and a\n // measurement cache for the given line number. (A line view might\n // contain multiple lines when collapsed ranges are present.)\n function mapFromLineView(lineView, line, lineN) {\n if (lineView.line == line)\n { return {map: lineView.measure.map, cache: lineView.measure.cache} }\n for (var i = 0; i < lineView.rest.length; i++)\n { if (lineView.rest[i] == line)\n { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }\n for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)\n { if (lineNo(lineView.rest[i$1]) > lineN)\n { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }\n }\n\n // Render a line into the hidden node display.externalMeasured. Used\n // when measurement is needed for a line that's not in the viewport.\n function updateExternalMeasurement(cm, line) {\n line = visualLine(line);\n var lineN = lineNo(line);\n var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);\n view.lineN = lineN;\n var built = view.built = buildLineContent(cm, view);\n view.text = built.pre;\n removeChildrenAndAdd(cm.display.lineMeasure, built.pre);\n return view\n }\n\n // Get a {top, bottom, left, right} box (in line-local coordinates)\n // for a given character.\n function measureChar(cm, line, ch, bias) {\n return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)\n }\n\n // Find a line view that corresponds to the given line number.\n function findViewForLine(cm, lineN) {\n if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)\n { return cm.display.view[findViewIndex(cm, lineN)] }\n var ext = cm.display.externalMeasured;\n if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)\n { return ext }\n }\n\n // Measurement can be split in two steps, the set-up work that\n // applies to the whole line, and the measurement of the actual\n // character. Functions like coordsChar, that need to do a lot of\n // measurements in a row, can thus ensure that the set-up work is\n // only done once.\n function prepareMeasureForLine(cm, line) {\n var lineN = lineNo(line);\n var view = findViewForLine(cm, lineN);\n if (view && !view.text) {\n view = null;\n } else if (view && view.changes) {\n updateLineForChanges(cm, view, lineN, getDimensions(cm));\n cm.curOp.forceUpdate = true;\n }\n if (!view)\n { view = updateExternalMeasurement(cm, line); }\n\n var info = mapFromLineView(view, line, lineN);\n return {\n line: line, view: view, rect: null,\n map: info.map, cache: info.cache, before: info.before,\n hasHeights: false\n }\n }\n\n // Given a prepared measurement object, measures the position of an\n // actual character (or fetches it from the cache).\n function measureCharPrepared(cm, prepared, ch, bias, varHeight) {\n if (prepared.before) { ch = -1; }\n var key = ch + (bias || \"\"), found;\n if (prepared.cache.hasOwnProperty(key)) {\n found = prepared.cache[key];\n } else {\n if (!prepared.rect)\n { prepared.rect = prepared.view.text.getBoundingClientRect(); }\n if (!prepared.hasHeights) {\n ensureLineHeights(cm, prepared.view, prepared.rect);\n prepared.hasHeights = true;\n }\n found = measureCharInner(cm, prepared, ch, bias);\n if (!found.bogus) { prepared.cache[key] = found; }\n }\n return {left: found.left, right: found.right,\n top: varHeight ? found.rtop : found.top,\n bottom: varHeight ? found.rbottom : found.bottom}\n }\n\n var nullRect = {left: 0, right: 0, top: 0, bottom: 0};\n\n function nodeAndOffsetInLineMap(map$$1, ch, bias) {\n var node, start, end, collapse, mStart, mEnd;\n // First, search the line map for the text node corresponding to,\n // or closest to, the target character.\n for (var i = 0; i < map$$1.length; i += 3) {\n mStart = map$$1[i];\n mEnd = map$$1[i + 1];\n if (ch < mStart) {\n start = 0; end = 1;\n collapse = \"left\";\n } else if (ch < mEnd) {\n start = ch - mStart;\n end = start + 1;\n } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {\n end = mEnd - mStart;\n start = end - 1;\n if (ch >= mEnd) { collapse = \"right\"; }\n }\n if (start != null) {\n node = map$$1[i + 2];\n if (mStart == mEnd && bias == (node.insertLeft ? \"left\" : \"right\"))\n { collapse = bias; }\n if (bias == \"left\" && start == 0)\n { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {\n node = map$$1[(i -= 3) + 2];\n collapse = \"left\";\n } }\n if (bias == \"right\" && start == mEnd - mStart)\n { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {\n node = map$$1[(i += 3) + 2];\n collapse = \"right\";\n } }\n break\n }\n }\n return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}\n }\n\n function getUsefulRect(rects, bias) {\n var rect = nullRect;\n if (bias == \"left\") { for (var i = 0; i < rects.length; i++) {\n if ((rect = rects[i]).left != rect.right) { break }\n } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {\n if ((rect = rects[i$1]).left != rect.right) { break }\n } }\n return rect\n }\n\n function measureCharInner(cm, prepared, ch, bias) {\n var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);\n var node = place.node, start = place.start, end = place.end, collapse = place.collapse;\n\n var rect;\n if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.\n for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned\n while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }\n while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }\n if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)\n { rect = node.parentNode.getBoundingClientRect(); }\n else\n { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }\n if (rect.left || rect.right || start == 0) { break }\n end = start;\n start = start - 1;\n collapse = \"right\";\n }\n if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }\n } else { // If it is a widget, simply get the box for the whole widget.\n if (start > 0) { collapse = bias = \"right\"; }\n var rects;\n if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)\n { rect = rects[bias == \"right\" ? rects.length - 1 : 0]; }\n else\n { rect = node.getBoundingClientRect(); }\n }\n if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {\n var rSpan = node.parentNode.getClientRects()[0];\n if (rSpan)\n { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }\n else\n { rect = nullRect; }\n }\n\n var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;\n var mid = (rtop + rbot) / 2;\n var heights = prepared.view.measure.heights;\n var i = 0;\n for (; i < heights.length - 1; i++)\n { if (mid < heights[i]) { break } }\n var top = i ? heights[i - 1] : 0, bot = heights[i];\n var result = {left: (collapse == \"right\" ? rect.right : rect.left) - prepared.rect.left,\n right: (collapse == \"left\" ? rect.left : rect.right) - prepared.rect.left,\n top: top, bottom: bot};\n if (!rect.left && !rect.right) { result.bogus = true; }\n if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }\n\n return result\n }\n\n // Work around problem with bounding client rects on ranges being\n // returned incorrectly when zoomed on IE10 and below.\n function maybeUpdateRectForZooming(measure, rect) {\n if (!window.screen || screen.logicalXDPI == null ||\n screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))\n { return rect }\n var scaleX = screen.logicalXDPI / screen.deviceXDPI;\n var scaleY = screen.logicalYDPI / screen.deviceYDPI;\n return {left: rect.left * scaleX, right: rect.right * scaleX,\n top: rect.top * scaleY, bottom: rect.bottom * scaleY}\n }\n\n function clearLineMeasurementCacheFor(lineView) {\n if (lineView.measure) {\n lineView.measure.cache = {};\n lineView.measure.heights = null;\n if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)\n { lineView.measure.caches[i] = {}; } }\n }\n }\n\n function clearLineMeasurementCache(cm) {\n cm.display.externalMeasure = null;\n removeChildren(cm.display.lineMeasure);\n for (var i = 0; i < cm.display.view.length; i++)\n { clearLineMeasurementCacheFor(cm.display.view[i]); }\n }\n\n function clearCaches(cm) {\n clearLineMeasurementCache(cm);\n cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;\n if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }\n cm.display.lineNumChars = null;\n }\n\n function pageScrollX() {\n // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206\n // which causes page_Offset and bounding client rects to use\n // different reference viewports and invalidate our calculations.\n if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }\n return window.pageXOffset || (document.documentElement || document.body).scrollLeft\n }\n function pageScrollY() {\n if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }\n return window.pageYOffset || (document.documentElement || document.body).scrollTop\n }\n\n function widgetTopHeight(lineObj) {\n var height = 0;\n if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)\n { height += widgetHeight(lineObj.widgets[i]); } } }\n return height\n }\n\n // Converts a {top, bottom, left, right} box from line-local\n // coordinates into another coordinate system. Context may be one of\n // \"line\", \"div\" (display.lineDiv), \"local\"./null (editor), \"window\",\n // or \"page\".\n function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {\n if (!includeWidgets) {\n var height = widgetTopHeight(lineObj);\n rect.top += height; rect.bottom += height;\n }\n if (context == \"line\") { return rect }\n if (!context) { context = \"local\"; }\n var yOff = heightAtLine(lineObj);\n if (context == \"local\") { yOff += paddingTop(cm.display); }\n else { yOff -= cm.display.viewOffset; }\n if (context == \"page\" || context == \"window\") {\n var lOff = cm.display.lineSpace.getBoundingClientRect();\n yOff += lOff.top + (context == \"window\" ? 0 : pageScrollY());\n var xOff = lOff.left + (context == \"window\" ? 0 : pageScrollX());\n rect.left += xOff; rect.right += xOff;\n }\n rect.top += yOff; rect.bottom += yOff;\n return rect\n }\n\n // Coverts a box from \"div\" coords to another coordinate system.\n // Context may be \"window\", \"page\", \"div\", or \"local\"./null.\n function fromCoordSystem(cm, coords, context) {\n if (context == \"div\") { return coords }\n var left = coords.left, top = coords.top;\n // First move into \"page\" coordinate system\n if (context == \"page\") {\n left -= pageScrollX();\n top -= pageScrollY();\n } else if (context == \"local\" || !context) {\n var localBox = cm.display.sizer.getBoundingClientRect();\n left += localBox.left;\n top += localBox.top;\n }\n\n var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();\n return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}\n }\n\n function charCoords(cm, pos, context, lineObj, bias) {\n if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }\n return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)\n }\n\n // Returns a box for a given cursor position, which may have an\n // 'other' property containing the position of the secondary cursor\n // on a bidi boundary.\n // A cursor Pos(line, char, \"before\") is on the same visual line as `char - 1`\n // and after `char - 1` in writing order of `char - 1`\n // A cursor Pos(line, char, \"after\") is on the same visual line as `char`\n // and before `char` in writing order of `char`\n // Examples (upper-case letters are RTL, lower-case are LTR):\n // Pos(0, 1, ...)\n // before after\n // ab a|b a|b\n // aB a|B aB|\n // Ab |Ab A|b\n // AB B|A B|A\n // Every position after the last character on a line is considered to stick\n // to the last character on the line.\n function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {\n lineObj = lineObj || getLine(cm.doc, pos.line);\n if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }\n function get(ch, right) {\n var m = measureCharPrepared(cm, preparedMeasure, ch, right ? \"right\" : \"left\", varHeight);\n if (right) { m.left = m.right; } else { m.right = m.left; }\n return intoCoordSystem(cm, lineObj, m, context)\n }\n var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;\n if (ch >= lineObj.text.length) {\n ch = lineObj.text.length;\n sticky = \"before\";\n } else if (ch <= 0) {\n ch = 0;\n sticky = \"after\";\n }\n if (!order) { return get(sticky == \"before\" ? ch - 1 : ch, sticky == \"before\") }\n\n function getBidi(ch, partPos, invert) {\n var part = order[partPos], right = part.level == 1;\n return get(invert ? ch - 1 : ch, right != invert)\n }\n var partPos = getBidiPartAt(order, ch, sticky);\n var other = bidiOther;\n var val = getBidi(ch, partPos, sticky == \"before\");\n if (other != null) { val.other = getBidi(ch, other, sticky != \"before\"); }\n return val\n }\n\n // Used to cheaply estimate the coordinates for a position. Used for\n // intermediate scroll updates.\n function estimateCoords(cm, pos) {\n var left = 0;\n pos = clipPos(cm.doc, pos);\n if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }\n var lineObj = getLine(cm.doc, pos.line);\n var top = heightAtLine(lineObj) + paddingTop(cm.display);\n return {left: left, right: left, top: top, bottom: top + lineObj.height}\n }\n\n // Positions returned by coordsChar contain some extra information.\n // xRel is the relative x position of the input coordinates compared\n // to the found position (so xRel > 0 means the coordinates are to\n // the right of the character position, for example). When outside\n // is true, that means the coordinates lie outside the line's\n // vertical range.\n function PosWithInfo(line, ch, sticky, outside, xRel) {\n var pos = Pos(line, ch, sticky);\n pos.xRel = xRel;\n if (outside) { pos.outside = true; }\n return pos\n }\n\n // Compute the character position closest to the given coordinates.\n // Input must be lineSpace-local (\"div\" coordinate system).\n function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }\n\n function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {\n y -= widgetTopHeight(lineObj);\n var end = lineObj.text.length;\n var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);\n end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);\n return {begin: begin, end: end}\n }\n\n function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {\n if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }\n var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), \"line\").top;\n return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)\n }\n\n // Returns true if the given side of a box is after the given\n // coordinates, in top-to-bottom, left-to-right order.\n function boxIsAfter(box, x, y, left) {\n return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x\n }\n\n function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {\n // Move y into line-local coordinate space\n y -= heightAtLine(lineObj);\n var preparedMeasure = prepareMeasureForLine(cm, lineObj);\n // When directly calling `measureCharPrepared`, we have to adjust\n // for the widgets at this line.\n var widgetHeight$$1 = widgetTopHeight(lineObj);\n var begin = 0, end = lineObj.text.length, ltr = true;\n\n var order = getOrder(lineObj, cm.doc.direction);\n // If the line isn't plain left-to-right text, first figure out\n // which bidi section the coordinates fall into.\n if (order) {\n var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)\n (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);\n ltr = part.level != 1;\n // The awkward -1 offsets are needed because findFirst (called\n // on these below) will treat its first bound as inclusive,\n // second as exclusive, but we want to actually address the\n // characters in the part's range\n begin = ltr ? part.from : part.to - 1;\n end = ltr ? part.to : part.from - 1;\n }\n\n // A binary search to find the first character whose bounding box\n // starts after the coordinates. If we run across any whose box wrap\n // the coordinates, store that.\n var chAround = null, boxAround = null;\n var ch = findFirst(function (ch) {\n var box = measureCharPrepared(cm, preparedMeasure, ch);\n box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;\n if (!boxIsAfter(box, x, y, false)) { return false }\n if (box.top <= y && box.left <= x) {\n chAround = ch;\n boxAround = box;\n }\n return true\n }, begin, end);\n\n var baseX, sticky, outside = false;\n // If a box around the coordinates was found, use that\n if (boxAround) {\n // Distinguish coordinates nearer to the left or right side of the box\n var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;\n ch = chAround + (atStart ? 0 : 1);\n sticky = atStart ? \"after\" : \"before\";\n baseX = atLeft ? boxAround.left : boxAround.right;\n } else {\n // (Adjust for extended bound, if necessary.)\n if (!ltr && (ch == end || ch == begin)) { ch++; }\n // To determine which side to associate with, get the box to the\n // left of the character and compare it's vertical position to the\n // coordinates\n sticky = ch == 0 ? \"after\" : ch == lineObj.text.length ? \"before\" :\n (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?\n \"after\" : \"before\";\n // Now get accurate coordinates for this place, in order to get a\n // base X position\n var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), \"line\", lineObj, preparedMeasure);\n baseX = coords.left;\n outside = y < coords.top || y >= coords.bottom;\n }\n\n ch = skipExtendingChars(lineObj.text, ch, 1);\n return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)\n }\n\n function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {\n // Bidi parts are sorted left-to-right, and in a non-line-wrapping\n // situation, we can take this ordering to correspond to the visual\n // ordering. This finds the first part whose end is after the given\n // coordinates.\n var index = findFirst(function (i) {\n var part = order[i], ltr = part.level != 1;\n return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? \"before\" : \"after\"),\n \"line\", lineObj, preparedMeasure), x, y, true)\n }, 0, order.length - 1);\n var part = order[index];\n // If this isn't the first part, the part's start is also after\n // the coordinates, and the coordinates aren't on the same line as\n // that start, move one part back.\n if (index > 0) {\n var ltr = part.level != 1;\n var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? \"after\" : \"before\"),\n \"line\", lineObj, preparedMeasure);\n if (boxIsAfter(start, x, y, true) && start.top > y)\n { part = order[index - 1]; }\n }\n return part\n }\n\n function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {\n // In a wrapped line, rtl text on wrapping boundaries can do things\n // that don't correspond to the ordering in our `order` array at\n // all, so a binary search doesn't work, and we want to return a\n // part that only spans one line so that the binary search in\n // coordsCharInner is safe. As such, we first find the extent of the\n // wrapped line, and then do a flat search in which we discard any\n // spans that aren't on the line.\n var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);\n var begin = ref.begin;\n var end = ref.end;\n if (/\\s/.test(lineObj.text.charAt(end - 1))) { end--; }\n var part = null, closestDist = null;\n for (var i = 0; i < order.length; i++) {\n var p = order[i];\n if (p.from >= end || p.to <= begin) { continue }\n var ltr = p.level != 1;\n var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;\n // Weigh against spans ending before this, so that they are only\n // picked if nothing ends after\n var dist = endX < x ? x - endX + 1e9 : endX - x;\n if (!part || closestDist > dist) {\n part = p;\n closestDist = dist;\n }\n }\n if (!part) { part = order[order.length - 1]; }\n // Clip the part to the wrapped line.\n if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }\n if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }\n return part\n }\n\n var measureText;\n // Compute the default text height.\n function textHeight(display) {\n if (display.cachedTextHeight != null) { return display.cachedTextHeight }\n if (measureText == null) {\n measureText = elt(\"pre\");\n // Measure a bunch of lines, for browsers that compute\n // fractional heights.\n for (var i = 0; i < 49; ++i) {\n measureText.appendChild(document.createTextNode(\"x\"));\n measureText.appendChild(elt(\"br\"));\n }\n measureText.appendChild(document.createTextNode(\"x\"));\n }\n removeChildrenAndAdd(display.measure, measureText);\n var height = measureText.offsetHeight / 50;\n if (height > 3) { display.cachedTextHeight = height; }\n removeChildren(display.measure);\n return height || 1\n }\n\n // Compute the default character width.\n function charWidth(display) {\n if (display.cachedCharWidth != null) { return display.cachedCharWidth }\n var anchor = elt(\"span\", \"xxxxxxxxxx\");\n var pre = elt(\"pre\", [anchor]);\n removeChildrenAndAdd(display.measure, pre);\n var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;\n if (width > 2) { display.cachedCharWidth = width; }\n return width || 10\n }\n\n // Do a bulk-read of the DOM positions and sizes needed to draw the\n // view, so that we don't interleave reading and writing to the DOM.\n function getDimensions(cm) {\n var d = cm.display, left = {}, width = {};\n var gutterLeft = d.gutters.clientLeft;\n for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {\n left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;\n width[cm.options.gutters[i]] = n.clientWidth;\n }\n return {fixedPos: compensateForHScroll(d),\n gutterTotalWidth: d.gutters.offsetWidth,\n gutterLeft: left,\n gutterWidth: width,\n wrapperWidth: d.wrapper.clientWidth}\n }\n\n // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,\n // but using getBoundingClientRect to get a sub-pixel-accurate\n // result.\n function compensateForHScroll(display) {\n return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left\n }\n\n // Returns a function that estimates the height of a line, to use as\n // first approximation until the line becomes visible (and is thus\n // properly measurable).\n function estimateHeight(cm) {\n var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;\n var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);\n return function (line) {\n if (lineIsHidden(cm.doc, line)) { return 0 }\n\n var widgetsHeight = 0;\n if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {\n if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }\n } }\n\n if (wrapping)\n { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }\n else\n { return widgetsHeight + th }\n }\n }\n\n function estimateLineHeights(cm) {\n var doc = cm.doc, est = estimateHeight(cm);\n doc.iter(function (line) {\n var estHeight = est(line);\n if (estHeight != line.height) { updateLineHeight(line, estHeight); }\n });\n }\n\n // Given a mouse event, find the corresponding position. If liberal\n // is false, it checks whether a gutter or scrollbar was clicked,\n // and returns null if it was. forRect is used by rectangular\n // selections, and tries to estimate a character position even for\n // coordinates beyond the right of the text.\n function posFromMouse(cm, e, liberal, forRect) {\n var display = cm.display;\n if (!liberal && e_target(e).getAttribute(\"cm-not-content\") == \"true\") { return null }\n\n var x, y, space = display.lineSpace.getBoundingClientRect();\n // Fails unpredictably on IE[67] when mouse is dragged around quickly.\n try { x = e.clientX - space.left; y = e.clientY - space.top; }\n catch (e) { return null }\n var coords = coordsChar(cm, x, y), line;\n if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {\n var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;\n coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));\n }\n return coords\n }\n\n // Find the view element corresponding to a given line. Return null\n // when the line isn't visible.\n function findViewIndex(cm, n) {\n if (n >= cm.display.viewTo) { return null }\n n -= cm.display.viewFrom;\n if (n < 0) { return null }\n var view = cm.display.view;\n for (var i = 0; i < view.length; i++) {\n n -= view[i].size;\n if (n < 0) { return i }\n }\n }\n\n function updateSelection(cm) {\n cm.display.input.showSelection(cm.display.input.prepareSelection());\n }\n\n function prepareSelection(cm, primary) {\n if ( primary === void 0 ) primary = true;\n\n var doc = cm.doc, result = {};\n var curFragment = result.cursors = document.createDocumentFragment();\n var selFragment = result.selection = document.createDocumentFragment();\n\n for (var i = 0; i < doc.sel.ranges.length; i++) {\n if (!primary && i == doc.sel.primIndex) { continue }\n var range$$1 = doc.sel.ranges[i];\n if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }\n var collapsed = range$$1.empty();\n if (collapsed || cm.options.showCursorWhenSelecting)\n { drawSelectionCursor(cm, range$$1.head, curFragment); }\n if (!collapsed)\n { drawSelectionRange(cm, range$$1, selFragment); }\n }\n return result\n }\n\n // Draws a cursor for the given range\n function drawSelectionCursor(cm, head, output) {\n var pos = cursorCoords(cm, head, \"div\", null, null, !cm.options.singleCursorHeightPerLine);\n\n var cursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor\"));\n cursor.style.left = pos.left + \"px\";\n cursor.style.top = pos.top + \"px\";\n cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + \"px\";\n\n if (pos.other) {\n // Secondary cursor, shown when on a 'jump' in bi-directional text\n var otherCursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor CodeMirror-secondarycursor\"));\n otherCursor.style.display = \"\";\n otherCursor.style.left = pos.other.left + \"px\";\n otherCursor.style.top = pos.other.top + \"px\";\n otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + \"px\";\n }\n }\n\n function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }\n\n // Draws the given range as a highlighted selection\n function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }\n\n // Cursor-blinking\n function restartBlink(cm) {\n if (!cm.state.focused) { return }\n var display = cm.display;\n clearInterval(display.blinker);\n var on = true;\n display.cursorDiv.style.visibility = \"\";\n if (cm.options.cursorBlinkRate > 0)\n { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? \"\" : \"hidden\"; },\n cm.options.cursorBlinkRate); }\n else if (cm.options.cursorBlinkRate < 0)\n { display.cursorDiv.style.visibility = \"hidden\"; }\n }\n\n function ensureFocus(cm) {\n if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }\n }\n\n function delayBlurEvent(cm) {\n cm.state.delayingBlurEvent = true;\n setTimeout(function () { if (cm.state.delayingBlurEvent) {\n cm.state.delayingBlurEvent = false;\n onBlur(cm);\n } }, 100);\n }\n\n function onFocus(cm, e) {\n if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }\n\n if (cm.options.readOnly == \"nocursor\") { return }\n if (!cm.state.focused) {\n signal(cm, \"focus\", cm, e);\n cm.state.focused = true;\n addClass(cm.display.wrapper, \"CodeMirror-focused\");\n // This test prevents this from firing when a context\n // menu is closed (since the input reset would kill the\n // select-all detection hack)\n if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {\n cm.display.input.reset();\n if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730\n }\n cm.display.input.receivedFocus();\n }\n restartBlink(cm);\n }\n function onBlur(cm, e) {\n if (cm.state.delayingBlurEvent) { return }\n\n if (cm.state.focused) {\n signal(cm, \"blur\", cm, e);\n cm.state.focused = false;\n rmClass(cm.display.wrapper, \"CodeMirror-focused\");\n }\n clearInterval(cm.display.blinker);\n setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);\n }\n\n // Read the actual heights of the rendered lines, and update their\n // stored heights to match.\n function updateHeightsInViewport(cm) {\n var display = cm.display;\n var prevBottom = display.lineDiv.offsetTop;\n for (var i = 0; i < display.view.length; i++) {\n var cur = display.view[i], wrapping = cm.options.lineWrapping;\n var height = (void 0), width = 0;\n if (cur.hidden) { continue }\n if (ie && ie_version < 8) {\n var bot = cur.node.offsetTop + cur.node.offsetHeight;\n height = bot - prevBottom;\n prevBottom = bot;\n } else {\n var box = cur.node.getBoundingClientRect();\n height = box.bottom - box.top;\n // Check that lines don't extend past the right of the current\n // editor width\n if (!wrapping && cur.text.firstChild)\n { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }\n }\n var diff = cur.line.height - height;\n if (height < 2) { height = textHeight(display); }\n if (diff > .005 || diff < -.005) {\n updateLineHeight(cur.line, height);\n updateWidgetHeight(cur.line);\n if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)\n { updateWidgetHeight(cur.rest[j]); } }\n }\n if (width > cm.display.sizerWidth) {\n var chWidth = Math.ceil(width / charWidth(cm.display));\n if (chWidth > cm.display.maxLineLength) {\n cm.display.maxLineLength = chWidth;\n cm.display.maxLine = cur.line;\n cm.display.maxLineChanged = true;\n }\n }\n }\n }\n\n // Read and store the height of line widgets associated with the\n // given line.\n function updateWidgetHeight(line) {\n if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {\n var w = line.widgets[i], parent = w.node.parentNode;\n if (parent) { w.height = parent.offsetHeight; }\n } }\n }\n\n // Compute the lines that are visible in a given viewport (defaults\n // the the current scroll position). viewport may contain top,\n // height, and ensure (see op.scrollToPos) properties.\n function visibleLines(display, doc, viewport) {\n var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;\n top = Math.floor(top - paddingTop(display));\n var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;\n\n var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);\n // Ensure is a {from: {line, ch}, to: {line, ch}} object, and\n // forces those lines into the viewport (if possible).\n if (viewport && viewport.ensure) {\n var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;\n if (ensureFrom < from) {\n from = ensureFrom;\n to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);\n } else if (Math.min(ensureTo, doc.lastLine()) >= to) {\n from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);\n to = ensureTo;\n }\n }\n return {from: from, to: Math.max(to, from + 1)}\n }\n\n // Re-align line numbers and gutter marks to compensate for\n // horizontal scrolling.\n function alignHorizontally(cm) {\n var display = cm.display, view = display.view;\n if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }\n var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;\n var gutterW = display.gutters.offsetWidth, left = comp + \"px\";\n for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {\n if (cm.options.fixedGutter) {\n if (view[i].gutter)\n { view[i].gutter.style.left = left; }\n if (view[i].gutterBackground)\n { view[i].gutterBackground.style.left = left; }\n }\n var align = view[i].alignable;\n if (align) { for (var j = 0; j < align.length; j++)\n { align[j].style.left = left; } }\n } }\n if (cm.options.fixedGutter)\n { display.gutters.style.left = (comp + gutterW) + \"px\"; }\n }\n\n // Used to ensure that the line number gutter is still the right\n // size for the current document size. Returns true when an update\n // is needed.\n function maybeUpdateLineNumberWidth(cm) {\n if (!cm.options.lineNumbers) { return false }\n var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;\n if (last.length != display.lineNumChars) {\n var test = display.measure.appendChild(elt(\"div\", [elt(\"div\", last)],\n \"CodeMirror-linenumber CodeMirror-gutter-elt\"));\n var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;\n display.lineGutter.style.width = \"\";\n display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;\n display.lineNumWidth = display.lineNumInnerWidth + padding;\n display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;\n display.lineGutter.style.width = display.lineNumWidth + \"px\";\n updateGutterSpace(cm);\n return true\n }\n return false\n }\n\n // SCROLLING THINGS INTO VIEW\n\n // If an editor sits on the top or bottom of the window, partially\n // scrolled out of view, this ensures that the cursor is visible.\n function maybeScrollWindow(cm, rect) {\n if (signalDOMEvent(cm, \"scrollCursorIntoView\")) { return }\n\n var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;\n if (rect.top + box.top < 0) { doScroll = true; }\n else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }\n if (doScroll != null && !phantom) {\n var scrollNode = elt(\"div\", \"\\u200b\", null, (\"position: absolute;\\n top: \" + (rect.top - display.viewOffset - paddingTop(cm.display)) + \"px;\\n height: \" + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + \"px;\\n left: \" + (rect.left) + \"px; width: \" + (Math.max(2, rect.right - rect.left)) + \"px;\"));\n cm.display.lineSpace.appendChild(scrollNode);\n scrollNode.scrollIntoView(doScroll);\n cm.display.lineSpace.removeChild(scrollNode);\n }\n }\n\n // Scroll a given position into view (immediately), verifying that\n // it actually became visible (as line heights are accurately\n // measured, the position of something may 'drift' during drawing).\n function scrollPosIntoView(cm, pos, end, margin) {\n if (margin == null) { margin = 0; }\n var rect;\n if (!cm.options.lineWrapping && pos == end) {\n // Set pos and end to the cursor positions around the character pos sticks to\n // If pos.sticky == \"before\", that is around pos.ch - 1, otherwise around pos.ch\n // If pos == Pos(_, 0, \"before\"), pos and end are unchanged\n pos = pos.ch ? Pos(pos.line, pos.sticky == \"before\" ? pos.ch - 1 : pos.ch, \"after\") : pos;\n end = pos.sticky == \"before\" ? Pos(pos.line, pos.ch + 1, \"before\") : pos;\n }\n for (var limit = 0; limit < 5; limit++) {\n var changed = false;\n var coords = cursorCoords(cm, pos);\n var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);\n rect = {left: Math.min(coords.left, endCoords.left),\n top: Math.min(coords.top, endCoords.top) - margin,\n right: Math.max(coords.left, endCoords.left),\n bottom: Math.max(coords.bottom, endCoords.bottom) + margin};\n var scrollPos = calculateScrollPos(cm, rect);\n var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;\n if (scrollPos.scrollTop != null) {\n updateScrollTop(cm, scrollPos.scrollTop);\n if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }\n }\n if (scrollPos.scrollLeft != null) {\n setScrollLeft(cm, scrollPos.scrollLeft);\n if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }\n }\n if (!changed) { break }\n }\n return rect\n }\n\n // Scroll a given set of coordinates into view (immediately).\n function scrollIntoView(cm, rect) {\n var scrollPos = calculateScrollPos(cm, rect);\n if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }\n if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }\n }\n\n // Calculate a new scroll position needed to scroll the given\n // rectangle into view. Returns an object with scrollTop and\n // scrollLeft properties. When these are undefined, the\n // vertical/horizontal position does not need to be adjusted.\n function calculateScrollPos(cm, rect) {\n var display = cm.display, snapMargin = textHeight(cm.display);\n if (rect.top < 0) { rect.top = 0; }\n var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;\n var screen = displayHeight(cm), result = {};\n if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }\n var docBottom = cm.doc.height + paddingVert(display);\n var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;\n if (rect.top < screentop) {\n result.scrollTop = atTop ? 0 : rect.top;\n } else if (rect.bottom > screentop + screen) {\n var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);\n if (newTop != screentop) { result.scrollTop = newTop; }\n }\n\n var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;\n var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);\n var tooWide = rect.right - rect.left > screenw;\n if (tooWide) { rect.right = rect.left + screenw; }\n if (rect.left < 10)\n { result.scrollLeft = 0; }\n else if (rect.left < screenleft)\n { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }\n else if (rect.right > screenw + screenleft - 3)\n { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }\n return result\n }\n\n // Store a relative adjustment to the scroll position in the current\n // operation (to be applied when the operation finishes).\n function addToScrollTop(cm, top) {\n if (top == null) { return }\n resolveScrollToPos(cm);\n cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;\n }\n\n // Make sure that at the end of the operation the current cursor is\n // shown.\n function ensureCursorVisible(cm) {\n resolveScrollToPos(cm);\n var cur = cm.getCursor();\n cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};\n }\n\n function scrollToCoords(cm, x, y) {\n if (x != null || y != null) { resolveScrollToPos(cm); }\n if (x != null) { cm.curOp.scrollLeft = x; }\n if (y != null) { cm.curOp.scrollTop = y; }\n }\n\n function scrollToRange(cm, range$$1) {\n resolveScrollToPos(cm);\n cm.curOp.scrollToPos = range$$1;\n }\n\n // When an operation has its scrollToPos property set, and another\n // scroll action is applied before the end of the operation, this\n // 'simulates' scrolling that position into view in a cheap way, so\n // that the effect of intermediate scroll commands is not ignored.\n function resolveScrollToPos(cm) {\n var range$$1 = cm.curOp.scrollToPos;\n if (range$$1) {\n cm.curOp.scrollToPos = null;\n var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);\n scrollToCoordsRange(cm, from, to, range$$1.margin);\n }\n }\n\n function scrollToCoordsRange(cm, from, to, margin) {\n var sPos = calculateScrollPos(cm, {\n left: Math.min(from.left, to.left),\n top: Math.min(from.top, to.top) - margin,\n right: Math.max(from.right, to.right),\n bottom: Math.max(from.bottom, to.bottom) + margin\n });\n scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);\n }\n\n // Sync the scrollable area and scrollbars, ensure the viewport\n // covers the visible area.\n function updateScrollTop(cm, val) {\n if (Math.abs(cm.doc.scrollTop - val) < 2) { return }\n if (!gecko) { updateDisplaySimple(cm, {top: val}); }\n setScrollTop(cm, val, true);\n if (gecko) { updateDisplaySimple(cm); }\n startWorker(cm, 100);\n }\n\n function setScrollTop(cm, val, forceScroll) {\n val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);\n if (cm.display.scroller.scrollTop == val && !forceScroll) { return }\n cm.doc.scrollTop = val;\n cm.display.scrollbars.setScrollTop(val);\n if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }\n }\n\n // Sync scroller and scrollbar, ensure the gutter elements are\n // aligned.\n function setScrollLeft(cm, val, isScroller, forceScroll) {\n val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);\n if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }\n cm.doc.scrollLeft = val;\n alignHorizontally(cm);\n if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }\n cm.display.scrollbars.setScrollLeft(val);\n }\n\n // SCROLLBARS\n\n // Prepare DOM reads needed to update the scrollbars. Done in one\n // shot to minimize update/measure roundtrips.\n function measureForScrollbars(cm) {\n var d = cm.display, gutterW = d.gutters.offsetWidth;\n var docH = Math.round(cm.doc.height + paddingVert(cm.display));\n return {\n clientHeight: d.scroller.clientHeight,\n viewHeight: d.wrapper.clientHeight,\n scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,\n viewWidth: d.wrapper.clientWidth,\n barLeft: cm.options.fixedGutter ? gutterW : 0,\n docHeight: docH,\n scrollHeight: docH + scrollGap(cm) + d.barHeight,\n nativeBarWidth: d.nativeBarWidth,\n gutterWidth: gutterW\n }\n }\n\n var NativeScrollbars = function(place, scroll, cm) {\n this.cm = cm;\n var vert = this.vert = elt(\"div\", [elt(\"div\", null, null, \"min-width: 1px\")], \"CodeMirror-vscrollbar\");\n var horiz = this.horiz = elt(\"div\", [elt(\"div\", null, null, \"height: 100%; min-height: 1px\")], \"CodeMirror-hscrollbar\");\n vert.tabIndex = horiz.tabIndex = -1;\n place(vert); place(horiz);\n\n on(vert, \"scroll\", function () {\n if (vert.clientHeight) { scroll(vert.scrollTop, \"vertical\"); }\n });\n on(horiz, \"scroll\", function () {\n if (horiz.clientWidth) { scroll(horiz.scrollLeft, \"horizontal\"); }\n });\n\n this.checkedZeroWidth = false;\n // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).\n if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = \"18px\"; }\n };\n\n NativeScrollbars.prototype.update = function (measure) {\n var needsH = measure.scrollWidth > measure.clientWidth + 1;\n var needsV = measure.scrollHeight > measure.clientHeight + 1;\n var sWidth = measure.nativeBarWidth;\n\n if (needsV) {\n this.vert.style.display = \"block\";\n this.vert.style.bottom = needsH ? sWidth + \"px\" : \"0\";\n var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);\n // A bug in IE8 can cause this value to be negative, so guard it.\n this.vert.firstChild.style.height =\n Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + \"px\";\n } else {\n this.vert.style.display = \"\";\n this.vert.firstChild.style.height = \"0\";\n }\n\n if (needsH) {\n this.horiz.style.display = \"block\";\n this.horiz.style.right = needsV ? sWidth + \"px\" : \"0\";\n this.horiz.style.left = measure.barLeft + \"px\";\n var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);\n this.horiz.firstChild.style.width =\n Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + \"px\";\n } else {\n this.horiz.style.display = \"\";\n this.horiz.firstChild.style.width = \"0\";\n }\n\n if (!this.checkedZeroWidth && measure.clientHeight > 0) {\n if (sWidth == 0) { this.zeroWidthHack(); }\n this.checkedZeroWidth = true;\n }\n\n return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}\n };\n\n NativeScrollbars.prototype.setScrollLeft = function (pos) {\n if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }\n if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, \"horiz\"); }\n };\n\n NativeScrollbars.prototype.setScrollTop = function (pos) {\n if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }\n if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, \"vert\"); }\n };\n\n NativeScrollbars.prototype.zeroWidthHack = function () {\n var w = mac && !mac_geMountainLion ? \"12px\" : \"18px\";\n this.horiz.style.height = this.vert.style.width = w;\n this.horiz.style.pointerEvents = this.vert.style.pointerEvents = \"none\";\n this.disableHoriz = new Delayed;\n this.disableVert = new Delayed;\n };\n\n NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {\n bar.style.pointerEvents = \"auto\";\n function maybeDisable() {\n // To find out whether the scrollbar is still visible, we\n // check whether the element under the pixel in the bottom\n // right corner of the scrollbar box is the scrollbar box\n // itself (when the bar is still visible) or its filler child\n // (when the bar is hidden). If it is still visible, we keep\n // it enabled, if it's hidden, we disable pointer events.\n var box = bar.getBoundingClientRect();\n var elt$$1 = type == \"vert\" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)\n : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);\n if (elt$$1 != bar) { bar.style.pointerEvents = \"none\"; }\n else { delay.set(1000, maybeDisable); }\n }\n delay.set(1000, maybeDisable);\n };\n\n NativeScrollbars.prototype.clear = function () {\n var parent = this.horiz.parentNode;\n parent.removeChild(this.horiz);\n parent.removeChild(this.vert);\n };\n\n var NullScrollbars = function () {};\n\n NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };\n NullScrollbars.prototype.setScrollLeft = function () {};\n NullScrollbars.prototype.setScrollTop = function () {};\n NullScrollbars.prototype.clear = function () {};\n\n function updateScrollbars(cm, measure) {\n if (!measure) { measure = measureForScrollbars(cm); }\n var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;\n updateScrollbarsInner(cm, measure);\n for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {\n if (startWidth != cm.display.barWidth && cm.options.lineWrapping)\n { updateHeightsInViewport(cm); }\n updateScrollbarsInner(cm, measureForScrollbars(cm));\n startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;\n }\n }\n\n // Re-synchronize the fake scrollbars with the actual size of the\n // content.\n function updateScrollbarsInner(cm, measure) {\n var d = cm.display;\n var sizes = d.scrollbars.update(measure);\n\n d.sizer.style.paddingRight = (d.barWidth = sizes.right) + \"px\";\n d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + \"px\";\n d.heightForcer.style.borderBottom = sizes.bottom + \"px solid transparent\";\n\n if (sizes.right && sizes.bottom) {\n d.scrollbarFiller.style.display = \"block\";\n d.scrollbarFiller.style.height = sizes.bottom + \"px\";\n d.scrollbarFiller.style.width = sizes.right + \"px\";\n } else { d.scrollbarFiller.style.display = \"\"; }\n if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {\n d.gutterFiller.style.display = \"block\";\n d.gutterFiller.style.height = sizes.bottom + \"px\";\n d.gutterFiller.style.width = measure.gutterWidth + \"px\";\n } else { d.gutterFiller.style.display = \"\"; }\n }\n\n var scrollbarModel = {\"native\": NativeScrollbars, \"null\": NullScrollbars};\n\n function initScrollbars(cm) {\n if (cm.display.scrollbars) {\n cm.display.scrollbars.clear();\n if (cm.display.scrollbars.addClass)\n { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }\n }\n\n cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {\n cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);\n // Prevent clicks in the scrollbars from killing focus\n on(node, \"mousedown\", function () {\n if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }\n });\n node.setAttribute(\"cm-not-content\", \"true\");\n }, function (pos, axis) {\n if (axis == \"horizontal\") { setScrollLeft(cm, pos); }\n else { updateScrollTop(cm, pos); }\n }, cm);\n if (cm.display.scrollbars.addClass)\n { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }\n }\n\n // Operations are used to wrap a series of changes to the editor\n // state in such a way that each change won't have to update the\n // cursor and display (which would be awkward, slow, and\n // error-prone). Instead, display updates are batched and then all\n // combined and executed at once.\n\n var nextOpId = 0;\n // Start a new operation.\n function startOperation(cm) {\n cm.curOp = {\n cm: cm,\n viewChanged: false, // Flag that indicates that lines might need to be redrawn\n startHeight: cm.doc.height, // Used to detect need to update scrollbar\n forceUpdate: false, // Used to force a redraw\n updateInput: null, // Whether to reset the input textarea\n typing: false, // Whether this reset should be careful to leave existing text (for compositing)\n changeObjs: null, // Accumulated changes, for firing change events\n cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on\n cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already\n selectionChanged: false, // Whether the selection needs to be redrawn\n updateMaxLine: false, // Set when the widest line needs to be determined anew\n scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet\n scrollToPos: null, // Used to scroll to a specific position\n focus: false,\n id: ++nextOpId // Unique ID\n };\n pushOperation(cm.curOp);\n }\n\n // Finish an operation, updating the display and signalling delayed events\n function endOperation(cm) {\n var op = cm.curOp;\n if (op) { finishOperation(op, function (group) {\n for (var i = 0; i < group.ops.length; i++)\n { group.ops[i].cm.curOp = null; }\n endOperations(group);\n }); }\n }\n\n // The DOM updates done when an operation finishes are batched so\n // that the minimum number of relayouts are required.\n function endOperations(group) {\n var ops = group.ops;\n for (var i = 0; i < ops.length; i++) // Read DOM\n { endOperation_R1(ops[i]); }\n for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)\n { endOperation_W1(ops[i$1]); }\n for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM\n { endOperation_R2(ops[i$2]); }\n for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)\n { endOperation_W2(ops[i$3]); }\n for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM\n { endOperation_finish(ops[i$4]); }\n }\n\n function endOperation_R1(op) {\n var cm = op.cm, display = cm.display;\n maybeClipScrollbars(cm);\n if (op.updateMaxLine) { findMaxLine(cm); }\n\n op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||\n op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||\n op.scrollToPos.to.line >= display.viewTo) ||\n display.maxLineChanged && cm.options.lineWrapping;\n op.update = op.mustUpdate &&\n new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);\n }\n\n function endOperation_W1(op) {\n op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);\n }\n\n function endOperation_R2(op) {\n var cm = op.cm, display = cm.display;\n if (op.updatedDisplay) { updateHeightsInViewport(cm); }\n\n op.barMeasure = measureForScrollbars(cm);\n\n // If the max line changed since it was last measured, measure it,\n // and ensure the document's width matches it.\n // updateDisplay_W2 will use these properties to do the actual resizing\n if (display.maxLineChanged && !cm.options.lineWrapping) {\n op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;\n cm.display.sizerWidth = op.adjustWidthTo;\n op.barMeasure.scrollWidth =\n Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);\n op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));\n }\n\n if (op.updatedDisplay || op.selectionChanged)\n { op.preparedSelection = display.input.prepareSelection(); }\n }\n\n function endOperation_W2(op) {\n var cm = op.cm;\n\n if (op.adjustWidthTo != null) {\n cm.display.sizer.style.minWidth = op.adjustWidthTo + \"px\";\n if (op.maxScrollLeft < cm.doc.scrollLeft)\n { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }\n cm.display.maxLineChanged = false;\n }\n\n var takeFocus = op.focus && op.focus == activeElt();\n if (op.preparedSelection)\n { cm.display.input.showSelection(op.preparedSelection, takeFocus); }\n if (op.updatedDisplay || op.startHeight != cm.doc.height)\n { updateScrollbars(cm, op.barMeasure); }\n if (op.updatedDisplay)\n { setDocumentHeight(cm, op.barMeasure); }\n\n if (op.selectionChanged) { restartBlink(cm); }\n\n if (cm.state.focused && op.updateInput)\n { cm.display.input.reset(op.typing); }\n if (takeFocus) { ensureFocus(op.cm); }\n }\n\n function endOperation_finish(op) {\n var cm = op.cm, display = cm.display, doc = cm.doc;\n\n if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }\n\n // Abort mouse wheel delta measurement, when scrolling explicitly\n if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))\n { display.wheelStartX = display.wheelStartY = null; }\n\n // Propagate the scroll position to the actual DOM scroller\n if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }\n\n if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }\n // If we need to scroll a specific position into view, do so.\n if (op.scrollToPos) {\n var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),\n clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);\n maybeScrollWindow(cm, rect);\n }\n\n // Fire events for markers that are hidden/unidden by editing or\n // undoing\n var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;\n if (hidden) { for (var i = 0; i < hidden.length; ++i)\n { if (!hidden[i].lines.length) { signal(hidden[i], \"hide\"); } } }\n if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)\n { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], \"unhide\"); } } }\n\n if (display.wrapper.offsetHeight)\n { doc.scrollTop = cm.display.scroller.scrollTop; }\n\n // Fire change events, and delayed event handlers\n if (op.changeObjs)\n { signal(cm, \"changes\", cm, op.changeObjs); }\n if (op.update)\n { op.update.finish(); }\n }\n\n // Run the given function in an operation\n function runInOp(cm, f) {\n if (cm.curOp) { return f() }\n startOperation(cm);\n try { return f() }\n finally { endOperation(cm); }\n }\n // Wraps a function in an operation. Returns the wrapped function.\n function operation(cm, f) {\n return function() {\n if (cm.curOp) { return f.apply(cm, arguments) }\n startOperation(cm);\n try { return f.apply(cm, arguments) }\n finally { endOperation(cm); }\n }\n }\n // Used to add methods to editor and doc instances, wrapping them in\n // operations.\n function methodOp(f) {\n return function() {\n if (this.curOp) { return f.apply(this, arguments) }\n startOperation(this);\n try { return f.apply(this, arguments) }\n finally { endOperation(this); }\n }\n }\n function docMethodOp(f) {\n return function() {\n var cm = this.cm;\n if (!cm || cm.curOp) { return f.apply(this, arguments) }\n startOperation(cm);\n try { return f.apply(this, arguments) }\n finally { endOperation(cm); }\n }\n }\n\n // Updates the display.view data structure for a given change to the\n // document. From and to are in pre-change coordinates. Lendiff is\n // the amount of lines added or subtracted by the change. This is\n // used for changes that span multiple lines, or change the way\n // lines are divided into visual lines. regLineChange (below)\n // registers single-line changes.\n function regChange(cm, from, to, lendiff) {\n if (from == null) { from = cm.doc.first; }\n if (to == null) { to = cm.doc.first + cm.doc.size; }\n if (!lendiff) { lendiff = 0; }\n\n var display = cm.display;\n if (lendiff && to < display.viewTo &&\n (display.updateLineNumbers == null || display.updateLineNumbers > from))\n { display.updateLineNumbers = from; }\n\n cm.curOp.viewChanged = true;\n\n if (from >= display.viewTo) { // Change after\n if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)\n { resetView(cm); }\n } else if (to <= display.viewFrom) { // Change before\n if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {\n resetView(cm);\n } else {\n display.viewFrom += lendiff;\n display.viewTo += lendiff;\n }\n } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap\n resetView(cm);\n } else if (from <= display.viewFrom) { // Top overlap\n var cut = viewCuttingPoint(cm, to, to + lendiff, 1);\n if (cut) {\n display.view = display.view.slice(cut.index);\n display.viewFrom = cut.lineN;\n display.viewTo += lendiff;\n } else {\n resetView(cm);\n }\n } else if (to >= display.viewTo) { // Bottom overlap\n var cut$1 = viewCuttingPoint(cm, from, from, -1);\n if (cut$1) {\n display.view = display.view.slice(0, cut$1.index);\n display.viewTo = cut$1.lineN;\n } else {\n resetView(cm);\n }\n } else { // Gap in the middle\n var cutTop = viewCuttingPoint(cm, from, from, -1);\n var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);\n if (cutTop && cutBot) {\n display.view = display.view.slice(0, cutTop.index)\n .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))\n .concat(display.view.slice(cutBot.index));\n display.viewTo += lendiff;\n } else {\n resetView(cm);\n }\n }\n\n var ext = display.externalMeasured;\n if (ext) {\n if (to < ext.lineN)\n { ext.lineN += lendiff; }\n else if (from < ext.lineN + ext.size)\n { display.externalMeasured = null; }\n }\n }\n\n // Register a change to a single line. Type must be one of \"text\",\n // \"gutter\", \"class\", \"widget\"\n function regLineChange(cm, line, type) {\n cm.curOp.viewChanged = true;\n var display = cm.display, ext = cm.display.externalMeasured;\n if (ext && line >= ext.lineN && line < ext.lineN + ext.size)\n { display.externalMeasured = null; }\n\n if (line < display.viewFrom || line >= display.viewTo) { return }\n var lineView = display.view[findViewIndex(cm, line)];\n if (lineView.node == null) { return }\n var arr = lineView.changes || (lineView.changes = []);\n if (indexOf(arr, type) == -1) { arr.push(type); }\n }\n\n // Clear the view.\n function resetView(cm) {\n cm.display.viewFrom = cm.display.viewTo = cm.doc.first;\n cm.display.view = [];\n cm.display.viewOffset = 0;\n }\n\n function viewCuttingPoint(cm, oldN, newN, dir) {\n var index = findViewIndex(cm, oldN), diff, view = cm.display.view;\n if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)\n { return {index: index, lineN: newN} }\n var n = cm.display.viewFrom;\n for (var i = 0; i < index; i++)\n { n += view[i].size; }\n if (n != oldN) {\n if (dir > 0) {\n if (index == view.length - 1) { return null }\n diff = (n + view[index].size) - oldN;\n index++;\n } else {\n diff = n - oldN;\n }\n oldN += diff; newN += diff;\n }\n while (visualLineNo(cm.doc, newN) != newN) {\n if (index == (dir < 0 ? 0 : view.length - 1)) { return null }\n newN += dir * view[index - (dir < 0 ? 1 : 0)].size;\n index += dir;\n }\n return {index: index, lineN: newN}\n }\n\n // Force the view to cover a given range, adding empty view element\n // or clipping off existing ones as needed.\n function adjustView(cm, from, to) {\n var display = cm.display, view = display.view;\n if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {\n display.view = buildViewArray(cm, from, to);\n display.viewFrom = from;\n } else {\n if (display.viewFrom > from)\n { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }\n else if (display.viewFrom < from)\n { display.view = display.view.slice(findViewIndex(cm, from)); }\n display.viewFrom = from;\n if (display.viewTo < to)\n { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }\n else if (display.viewTo > to)\n { display.view = display.view.slice(0, findViewIndex(cm, to)); }\n }\n display.viewTo = to;\n }\n\n // Count the number of lines in the view whose DOM representation is\n // out of date (or nonexistent).\n function countDirtyView(cm) {\n var view = cm.display.view, dirty = 0;\n for (var i = 0; i < view.length; i++) {\n var lineView = view[i];\n if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }\n }\n return dirty\n }\n\n // HIGHLIGHT WORKER\n\n function startWorker(cm, time) {\n if (cm.doc.highlightFrontier < cm.display.viewTo)\n { cm.state.highlight.set(time, bind(highlightWorker, cm)); }\n }\n\n function highlightWorker(cm) {\n var doc = cm.doc;\n if (doc.highlightFrontier >= cm.display.viewTo) { return }\n var end = +new Date + cm.options.workTime;\n var context = getContextBefore(cm, doc.highlightFrontier);\n var changedLines = [];\n\n doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {\n if (context.line >= cm.display.viewFrom) { // Visible\n var oldStyles = line.styles;\n var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;\n var highlighted = highlightLine(cm, line, context, true);\n if (resetState) { context.state = resetState; }\n line.styles = highlighted.styles;\n var oldCls = line.styleClasses, newCls = highlighted.classes;\n if (newCls) { line.styleClasses = newCls; }\n else if (oldCls) { line.styleClasses = null; }\n var ischange = !oldStyles || oldStyles.length != line.styles.length ||\n oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);\n for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }\n if (ischange) { changedLines.push(context.line); }\n line.stateAfter = context.save();\n context.nextLine();\n } else {\n if (line.text.length <= cm.options.maxHighlightLength)\n { processLine(cm, line.text, context); }\n line.stateAfter = context.line % 5 == 0 ? context.save() : null;\n context.nextLine();\n }\n if (+new Date > end) {\n startWorker(cm, cm.options.workDelay);\n return true\n }\n });\n doc.highlightFrontier = context.line;\n doc.modeFrontier = Math.max(doc.modeFrontier, context.line);\n if (changedLines.length) { runInOp(cm, function () {\n for (var i = 0; i < changedLines.length; i++)\n { regLineChange(cm, changedLines[i], \"text\"); }\n }); }\n }\n\n // DISPLAY DRAWING\n\n var DisplayUpdate = function(cm, viewport, force) {\n var display = cm.display;\n\n this.viewport = viewport;\n // Store some values that we'll need later (but don't want to force a relayout for)\n this.visible = visibleLines(display, cm.doc, viewport);\n this.editorIsHidden = !display.wrapper.offsetWidth;\n this.wrapperHeight = display.wrapper.clientHeight;\n this.wrapperWidth = display.wrapper.clientWidth;\n this.oldDisplayWidth = displayWidth(cm);\n this.force = force;\n this.dims = getDimensions(cm);\n this.events = [];\n };\n\n DisplayUpdate.prototype.signal = function (emitter, type) {\n if (hasHandler(emitter, type))\n { this.events.push(arguments); }\n };\n DisplayUpdate.prototype.finish = function () {\n var this$1 = this;\n\n for (var i = 0; i < this.events.length; i++)\n { signal.apply(null, this$1.events[i]); }\n };\n\n function maybeClipScrollbars(cm) {\n var display = cm.display;\n if (!display.scrollbarsClipped && display.scroller.offsetWidth) {\n display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;\n display.heightForcer.style.height = scrollGap(cm) + \"px\";\n display.sizer.style.marginBottom = -display.nativeBarWidth + \"px\";\n display.sizer.style.borderRightWidth = scrollGap(cm) + \"px\";\n display.scrollbarsClipped = true;\n }\n }\n\n function selectionSnapshot(cm) {\n if (cm.hasFocus()) { return null }\n var active = activeElt();\n if (!active || !contains(cm.display.lineDiv, active)) { return null }\n var result = {activeElt: active};\n if (window.getSelection) {\n var sel = window.getSelection();\n if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {\n result.anchorNode = sel.anchorNode;\n result.anchorOffset = sel.anchorOffset;\n result.focusNode = sel.focusNode;\n result.focusOffset = sel.focusOffset;\n }\n }\n return result\n }\n\n function restoreSelection(snapshot) {\n if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }\n snapshot.activeElt.focus();\n if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {\n var sel = window.getSelection(), range$$1 = document.createRange();\n range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);\n range$$1.collapse(false);\n sel.removeAllRanges();\n sel.addRange(range$$1);\n sel.extend(snapshot.focusNode, snapshot.focusOffset);\n }\n }\n\n // Does the actual updating of the line display. Bails out\n // (returning false) when there is nothing to be done and forced is\n // false.\n function updateDisplayIfNeeded(cm, update) {\n var display = cm.display, doc = cm.doc;\n\n if (update.editorIsHidden) {\n resetView(cm);\n return false\n }\n\n // Bail out if the visible area is already rendered and nothing changed.\n if (!update.force &&\n update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&\n (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&\n display.renderedView == display.view && countDirtyView(cm) == 0)\n { return false }\n\n if (maybeUpdateLineNumberWidth(cm)) {\n resetView(cm);\n update.dims = getDimensions(cm);\n }\n\n // Compute a suitable new viewport (from & to)\n var end = doc.first + doc.size;\n var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);\n var to = Math.min(end, update.visible.to + cm.options.viewportMargin);\n if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }\n if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }\n if (sawCollapsedSpans) {\n from = visualLineNo(cm.doc, from);\n to = visualLineEndNo(cm.doc, to);\n }\n\n var different = from != display.viewFrom || to != display.viewTo ||\n display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;\n adjustView(cm, from, to);\n\n display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));\n // Position the mover div to align with the current scroll position\n cm.display.mover.style.top = display.viewOffset + \"px\";\n\n var toUpdate = countDirtyView(cm);\n if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&\n (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))\n { return false }\n\n // For big changes, we hide the enclosing element during the\n // update, since that speeds up the operations on most browsers.\n var selSnapshot = selectionSnapshot(cm);\n if (toUpdate > 4) { display.lineDiv.style.display = \"none\"; }\n patchDisplay(cm, display.updateLineNumbers, update.dims);\n if (toUpdate > 4) { display.lineDiv.style.display = \"\"; }\n display.renderedView = display.view;\n // There might have been a widget with a focused element that got\n // hidden or updated, if so re-focus it.\n restoreSelection(selSnapshot);\n\n // Prevent selection and cursors from interfering with the scroll\n // width and height.\n removeChildren(display.cursorDiv);\n removeChildren(display.selectionDiv);\n display.gutters.style.height = display.sizer.style.minHeight = 0;\n\n if (different) {\n display.lastWrapHeight = update.wrapperHeight;\n display.lastWrapWidth = update.wrapperWidth;\n startWorker(cm, 400);\n }\n\n display.updateLineNumbers = null;\n\n return true\n }\n\n function postUpdateDisplay(cm, update) {\n var viewport = update.viewport;\n\n for (var first = true;; first = false) {\n if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {\n // Clip forced viewport to actual scrollable area.\n if (viewport && viewport.top != null)\n { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }\n // Updated line heights might result in the drawn area not\n // actually covering the viewport. Keep looping until it does.\n update.visible = visibleLines(cm.display, cm.doc, viewport);\n if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)\n { break }\n }\n if (!updateDisplayIfNeeded(cm, update)) { break }\n updateHeightsInViewport(cm);\n var barMeasure = measureForScrollbars(cm);\n updateSelection(cm);\n updateScrollbars(cm, barMeasure);\n setDocumentHeight(cm, barMeasure);\n update.force = false;\n }\n\n update.signal(cm, \"update\", cm);\n if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {\n update.signal(cm, \"viewportChange\", cm, cm.display.viewFrom, cm.display.viewTo);\n cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;\n }\n }\n\n function updateDisplaySimple(cm, viewport) {\n var update = new DisplayUpdate(cm, viewport);\n if (updateDisplayIfNeeded(cm, update)) {\n updateHeightsInViewport(cm);\n postUpdateDisplay(cm, update);\n var barMeasure = measureForScrollbars(cm);\n updateSelection(cm);\n updateScrollbars(cm, barMeasure);\n setDocumentHeight(cm, barMeasure);\n update.finish();\n }\n }\n\n // Sync the actual display DOM structure with display.view, removing\n // nodes for lines that are no longer in view, and creating the ones\n // that are not there yet, and updating the ones that are out of\n // date.\n function patchDisplay(cm, updateNumbersFrom, dims) {\n var display = cm.display, lineNumbers = cm.options.lineNumbers;\n var container = display.lineDiv, cur = container.firstChild;\n\n function rm(node) {\n var next = node.nextSibling;\n // Works around a throw-scroll bug in OS X Webkit\n if (webkit && mac && cm.display.currentWheelTarget == node)\n { node.style.display = \"none\"; }\n else\n { node.parentNode.removeChild(node); }\n return next\n }\n\n var view = display.view, lineN = display.viewFrom;\n // Loop over the elements in the view, syncing cur (the DOM nodes\n // in display.lineDiv) with the view as we go.\n for (var i = 0; i < view.length; i++) {\n var lineView = view[i];\n if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet\n var node = buildLineElement(cm, lineView, lineN, dims);\n container.insertBefore(node, cur);\n } else { // Already drawn\n while (cur != lineView.node) { cur = rm(cur); }\n var updateNumber = lineNumbers && updateNumbersFrom != null &&\n updateNumbersFrom <= lineN && lineView.lineNumber;\n if (lineView.changes) {\n if (indexOf(lineView.changes, \"gutter\") > -1) { updateNumber = false; }\n updateLineForChanges(cm, lineView, lineN, dims);\n }\n if (updateNumber) {\n removeChildren(lineView.lineNumber);\n lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));\n }\n cur = lineView.node.nextSibling;\n }\n lineN += lineView.size;\n }\n while (cur) { cur = rm(cur); }\n }\n\n function updateGutterSpace(cm) {\n var width = cm.display.gutters.offsetWidth;\n cm.display.sizer.style.marginLeft = width + \"px\";\n }\n\n function setDocumentHeight(cm, measure) {\n cm.display.sizer.style.minHeight = measure.docHeight + \"px\";\n cm.display.heightForcer.style.top = measure.docHeight + \"px\";\n cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + \"px\";\n }\n\n // Rebuild the gutter elements, ensure the margin to the left of the\n // code matches their width.\n function updateGutters(cm) {\n var gutters = cm.display.gutters, specs = cm.options.gutters;\n removeChildren(gutters);\n var i = 0;\n for (; i < specs.length; ++i) {\n var gutterClass = specs[i];\n var gElt = gutters.appendChild(elt(\"div\", null, \"CodeMirror-gutter \" + gutterClass));\n if (gutterClass == \"CodeMirror-linenumbers\") {\n cm.display.lineGutter = gElt;\n gElt.style.width = (cm.display.lineNumWidth || 1) + \"px\";\n }\n }\n gutters.style.display = i ? \"\" : \"none\";\n updateGutterSpace(cm);\n }\n\n // Make sure the gutters options contains the element\n // \"CodeMirror-linenumbers\" when the lineNumbers option is true.\n function setGuttersForLineNumbers(options) {\n var found = indexOf(options.gutters, \"CodeMirror-linenumbers\");\n if (found == -1 && options.lineNumbers) {\n options.gutters = options.gutters.concat([\"CodeMirror-linenumbers\"]);\n } else if (found > -1 && !options.lineNumbers) {\n options.gutters = options.gutters.slice(0);\n options.gutters.splice(found, 1);\n }\n }\n\n // Since the delta values reported on mouse wheel events are\n // unstandardized between browsers and even browser versions, and\n // generally horribly unpredictable, this code starts by measuring\n // the scroll effect that the first few mouse wheel events have,\n // and, from that, detects the way it can convert deltas to pixel\n // offsets afterwards.\n //\n // The reason we want to know the amount a wheel event will scroll\n // is that it gives us a chance to update the display before the\n // actual scrolling happens, reducing flickering.\n\n var wheelSamples = 0, wheelPixelsPerUnit = null;\n // Fill in a browser-detected starting value on browsers where we\n // know one. These don't have to be accurate -- the result of them\n // being wrong would just be a slight flicker on the first wheel\n // scroll (if it is large enough).\n if (ie) { wheelPixelsPerUnit = -.53; }\n else if (gecko) { wheelPixelsPerUnit = 15; }\n else if (chrome) { wheelPixelsPerUnit = -.7; }\n else if (safari) { wheelPixelsPerUnit = -1/3; }\n\n function wheelEventDelta(e) {\n var dx = e.wheelDeltaX, dy = e.wheelDeltaY;\n if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }\n if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }\n else if (dy == null) { dy = e.wheelDelta; }\n return {x: dx, y: dy}\n }\n function wheelEventPixels(e) {\n var delta = wheelEventDelta(e);\n delta.x *= wheelPixelsPerUnit;\n delta.y *= wheelPixelsPerUnit;\n return delta\n }\n\n function onScrollWheel(cm, e) {\n var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;\n\n var display = cm.display, scroll = display.scroller;\n // Quit if there's nothing to scroll here\n var canScrollX = scroll.scrollWidth > scroll.clientWidth;\n var canScrollY = scroll.scrollHeight > scroll.clientHeight;\n if (!(dx && canScrollX || dy && canScrollY)) { return }\n\n // Webkit browsers on OS X abort momentum scrolls when the target\n // of the scroll event is removed from the scrollable element.\n // This hack (see related code in patchDisplay) makes sure the\n // element is kept around.\n if (dy && mac && webkit) {\n outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {\n for (var i = 0; i < view.length; i++) {\n if (view[i].node == cur) {\n cm.display.currentWheelTarget = cur;\n break outer\n }\n }\n }\n }\n\n // On some browsers, horizontal scrolling will cause redraws to\n // happen before the gutter has been realigned, causing it to\n // wriggle around in a most unseemly way. When we have an\n // estimated pixels/delta value, we just handle horizontal\n // scrolling entirely here. It'll be slightly off from native, but\n // better than glitching out.\n if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {\n if (dy && canScrollY)\n { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }\n setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));\n // Only prevent default scrolling if vertical scrolling is\n // actually possible. Otherwise, it causes vertical scroll\n // jitter on OSX trackpads when deltaX is small and deltaY\n // is large (issue #3579)\n if (!dy || (dy && canScrollY))\n { e_preventDefault(e); }\n display.wheelStartX = null; // Abort measurement, if in progress\n return\n }\n\n // 'Project' the visible viewport to cover the area that is being\n // scrolled into view (if we know enough to estimate it).\n if (dy && wheelPixelsPerUnit != null) {\n var pixels = dy * wheelPixelsPerUnit;\n var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;\n if (pixels < 0) { top = Math.max(0, top + pixels - 50); }\n else { bot = Math.min(cm.doc.height, bot + pixels + 50); }\n updateDisplaySimple(cm, {top: top, bottom: bot});\n }\n\n if (wheelSamples < 20) {\n if (display.wheelStartX == null) {\n display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;\n display.wheelDX = dx; display.wheelDY = dy;\n setTimeout(function () {\n if (display.wheelStartX == null) { return }\n var movedX = scroll.scrollLeft - display.wheelStartX;\n var movedY = scroll.scrollTop - display.wheelStartY;\n var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||\n (movedX && display.wheelDX && movedX / display.wheelDX);\n display.wheelStartX = display.wheelStartY = null;\n if (!sample) { return }\n wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);\n ++wheelSamples;\n }, 200);\n } else {\n display.wheelDX += dx; display.wheelDY += dy;\n }\n }\n }\n\n // Selection objects are immutable. A new one is created every time\n // the selection changes. A selection is one or more non-overlapping\n // (and non-touching) ranges, sorted, and an integer that indicates\n // which one is the primary selection (the one that's scrolled into\n // view, that getCursor returns, etc).\n var Selection = function(ranges, primIndex) {\n this.ranges = ranges;\n this.primIndex = primIndex;\n };\n\n Selection.prototype.primary = function () { return this.ranges[this.primIndex] };\n\n Selection.prototype.equals = function (other) {\n var this$1 = this;\n\n if (other == this) { return true }\n if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }\n for (var i = 0; i < this.ranges.length; i++) {\n var here = this$1.ranges[i], there = other.ranges[i];\n if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }\n }\n return true\n };\n\n Selection.prototype.deepCopy = function () {\n var this$1 = this;\n\n var out = [];\n for (var i = 0; i < this.ranges.length; i++)\n { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }\n return new Selection(out, this.primIndex)\n };\n\n Selection.prototype.somethingSelected = function () {\n var this$1 = this;\n\n for (var i = 0; i < this.ranges.length; i++)\n { if (!this$1.ranges[i].empty()) { return true } }\n return false\n };\n\n Selection.prototype.contains = function (pos, end) {\n var this$1 = this;\n\n if (!end) { end = pos; }\n for (var i = 0; i < this.ranges.length; i++) {\n var range = this$1.ranges[i];\n if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)\n { return i }\n }\n return -1\n };\n\n var Range = function(anchor, head) {\n this.anchor = anchor; this.head = head;\n };\n\n Range.prototype.from = function () { return minPos(this.anchor, this.head) };\n Range.prototype.to = function () { return maxPos(this.anchor, this.head) };\n Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };\n\n // Take an unsorted, potentially overlapping set of ranges, and\n // build a selection out of it. 'Consumes' ranges array (modifying\n // it).\n function normalizeSelection(cm, ranges, primIndex) {\n var mayTouch = cm && cm.options.selectionsMayTouch;\n var prim = ranges[primIndex];\n ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });\n primIndex = indexOf(ranges, prim);\n for (var i = 1; i < ranges.length; i++) {\n var cur = ranges[i], prev = ranges[i - 1];\n var diff = cmp(prev.to(), cur.from());\n if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {\n var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());\n var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;\n if (i <= primIndex) { --primIndex; }\n ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));\n }\n }\n return new Selection(ranges, primIndex)\n }\n\n function simpleSelection(anchor, head) {\n return new Selection([new Range(anchor, head || anchor)], 0)\n }\n\n // Compute the position of the end of a change (its 'to' property\n // refers to the pre-change end).\n function changeEnd(change) {\n if (!change.text) { return change.to }\n return Pos(change.from.line + change.text.length - 1,\n lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))\n }\n\n // Adjust a position to refer to the post-change position of the\n // same text, or the end of the change if the change covers it.\n function adjustForChange(pos, change) {\n if (cmp(pos, change.from) < 0) { return pos }\n if (cmp(pos, change.to) <= 0) { return changeEnd(change) }\n\n var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;\n if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }\n return Pos(line, ch)\n }\n\n function computeSelAfterChange(doc, change) {\n var out = [];\n for (var i = 0; i < doc.sel.ranges.length; i++) {\n var range = doc.sel.ranges[i];\n out.push(new Range(adjustForChange(range.anchor, change),\n adjustForChange(range.head, change)));\n }\n return normalizeSelection(doc.cm, out, doc.sel.primIndex)\n }\n\n function offsetPos(pos, old, nw) {\n if (pos.line == old.line)\n { return Pos(nw.line, pos.ch - old.ch + nw.ch) }\n else\n { return Pos(nw.line + (pos.line - old.line), pos.ch) }\n }\n\n // Used by replaceSelections to allow moving the selection to the\n // start or around the replaced test. Hint may be \"start\" or \"around\".\n function computeReplacedSel(doc, changes, hint) {\n var out = [];\n var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;\n for (var i = 0; i < changes.length; i++) {\n var change = changes[i];\n var from = offsetPos(change.from, oldPrev, newPrev);\n var to = offsetPos(changeEnd(change), oldPrev, newPrev);\n oldPrev = change.to;\n newPrev = to;\n if (hint == \"around\") {\n var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;\n out[i] = new Range(inv ? to : from, inv ? from : to);\n } else {\n out[i] = new Range(from, from);\n }\n }\n return new Selection(out, doc.sel.primIndex)\n }\n\n // Used to get the editor into a consistent state again when options change.\n\n function loadMode(cm) {\n cm.doc.mode = getMode(cm.options, cm.doc.modeOption);\n resetModeState(cm);\n }\n\n function resetModeState(cm) {\n cm.doc.iter(function (line) {\n if (line.stateAfter) { line.stateAfter = null; }\n if (line.styles) { line.styles = null; }\n });\n cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;\n startWorker(cm, 100);\n cm.state.modeGen++;\n if (cm.curOp) { regChange(cm); }\n }\n\n // DOCUMENT DATA STRUCTURE\n\n // By default, updates that start and end at the beginning of a line\n // are treated specially, in order to make the association of line\n // widgets and marker elements with the text behave more intuitive.\n function isWholeLineUpdate(doc, change) {\n return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == \"\" &&\n (!doc.cm || doc.cm.options.wholeLineUpdateBefore)\n }\n\n // Perform a change on the document data structure.\n function updateDoc(doc, change, markedSpans, estimateHeight$$1) {\n function spansFor(n) {return markedSpans ? markedSpans[n] : null}\n function update(line, text, spans) {\n updateLine(line, text, spans, estimateHeight$$1);\n signalLater(line, \"change\", line, change);\n }\n function linesFor(start, end) {\n var result = [];\n for (var i = start; i < end; ++i)\n { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }\n return result\n }\n\n var from = change.from, to = change.to, text = change.text;\n var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);\n var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;\n\n // Adjust the line structure\n if (change.full) {\n doc.insert(0, linesFor(0, text.length));\n doc.remove(text.length, doc.size - text.length);\n } else if (isWholeLineUpdate(doc, change)) {\n // This is a whole-line replace. Treated specially to make\n // sure line objects move the way they are supposed to.\n var added = linesFor(0, text.length - 1);\n update(lastLine, lastLine.text, lastSpans);\n if (nlines) { doc.remove(from.line, nlines); }\n if (added.length) { doc.insert(from.line, added); }\n } else if (firstLine == lastLine) {\n if (text.length == 1) {\n update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);\n } else {\n var added$1 = linesFor(1, text.length - 1);\n added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));\n update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n doc.insert(from.line + 1, added$1);\n }\n } else if (text.length == 1) {\n update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));\n doc.remove(from.line + 1, nlines);\n } else {\n update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);\n var added$2 = linesFor(1, text.length - 1);\n if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }\n doc.insert(from.line + 1, added$2);\n }\n\n signalLater(doc, \"change\", doc, change);\n }\n\n // Call f for all linked documents.\n function linkedDocs(doc, f, sharedHistOnly) {\n function propagate(doc, skip, sharedHist) {\n if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {\n var rel = doc.linked[i];\n if (rel.doc == skip) { continue }\n var shared = sharedHist && rel.sharedHist;\n if (sharedHistOnly && !shared) { continue }\n f(rel.doc, shared);\n propagate(rel.doc, doc, shared);\n } }\n }\n propagate(doc, null, true);\n }\n\n // Attach a document to an editor.\n function attachDoc(cm, doc) {\n if (doc.cm) { throw new Error(\"This document is already in use.\") }\n cm.doc = doc;\n doc.cm = cm;\n estimateLineHeights(cm);\n loadMode(cm);\n setDirectionClass(cm);\n if (!cm.options.lineWrapping) { findMaxLine(cm); }\n cm.options.mode = doc.modeOption;\n regChange(cm);\n }\n\n function setDirectionClass(cm) {\n (cm.doc.direction == \"rtl\" ? addClass : rmClass)(cm.display.lineDiv, \"CodeMirror-rtl\");\n }\n\n function directionChanged(cm) {\n runInOp(cm, function () {\n setDirectionClass(cm);\n regChange(cm);\n });\n }\n\n function History(startGen) {\n // Arrays of change events and selections. Doing something adds an\n // event to done and clears undo. Undoing moves events from done\n // to undone, redoing moves them in the other direction.\n this.done = []; this.undone = [];\n this.undoDepth = Infinity;\n // Used to track when changes can be merged into a single undo\n // event\n this.lastModTime = this.lastSelTime = 0;\n this.lastOp = this.lastSelOp = null;\n this.lastOrigin = this.lastSelOrigin = null;\n // Used by the isClean() method\n this.generation = this.maxGeneration = startGen || 1;\n }\n\n // Create a history change event from an updateDoc-style change\n // object.\n function historyChangeFromChange(doc, change) {\n var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};\n attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);\n linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);\n return histChange\n }\n\n // Pop all selection events off the end of a history array. Stop at\n // a change event.\n function clearSelectionEvents(array) {\n while (array.length) {\n var last = lst(array);\n if (last.ranges) { array.pop(); }\n else { break }\n }\n }\n\n // Find the top change event in the history. Pop off selection\n // events that are in the way.\n function lastChangeEvent(hist, force) {\n if (force) {\n clearSelectionEvents(hist.done);\n return lst(hist.done)\n } else if (hist.done.length && !lst(hist.done).ranges) {\n return lst(hist.done)\n } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {\n hist.done.pop();\n return lst(hist.done)\n }\n }\n\n // Register a change in the history. Merges changes that are within\n // a single operation, or are close together with an origin that\n // allows merging (starting with \"+\") into a single event.\n function addChangeToHistory(doc, change, selAfter, opId) {\n var hist = doc.history;\n hist.undone.length = 0;\n var time = +new Date, cur;\n var last;\n\n if ((hist.lastOp == opId ||\n hist.lastOrigin == change.origin && change.origin &&\n ((change.origin.charAt(0) == \"+\" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||\n change.origin.charAt(0) == \"*\")) &&\n (cur = lastChangeEvent(hist, hist.lastOp == opId))) {\n // Merge this change into the last event\n last = lst(cur.changes);\n if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {\n // Optimized case for simple insertion -- don't want to add\n // new changesets for every character typed\n last.to = changeEnd(change);\n } else {\n // Add new sub-event\n cur.changes.push(historyChangeFromChange(doc, change));\n }\n } else {\n // Can not be merged, start a new event.\n var before = lst(hist.done);\n if (!before || !before.ranges)\n { pushSelectionToHistory(doc.sel, hist.done); }\n cur = {changes: [historyChangeFromChange(doc, change)],\n generation: hist.generation};\n hist.done.push(cur);\n while (hist.done.length > hist.undoDepth) {\n hist.done.shift();\n if (!hist.done[0].ranges) { hist.done.shift(); }\n }\n }\n hist.done.push(selAfter);\n hist.generation = ++hist.maxGeneration;\n hist.lastModTime = hist.lastSelTime = time;\n hist.lastOp = hist.lastSelOp = opId;\n hist.lastOrigin = hist.lastSelOrigin = change.origin;\n\n if (!last) { signal(doc, \"historyAdded\"); }\n }\n\n function selectionEventCanBeMerged(doc, origin, prev, sel) {\n var ch = origin.charAt(0);\n return ch == \"*\" ||\n ch == \"+\" &&\n prev.ranges.length == sel.ranges.length &&\n prev.somethingSelected() == sel.somethingSelected() &&\n new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)\n }\n\n // Called whenever the selection changes, sets the new selection as\n // the pending selection in the history, and pushes the old pending\n // selection into the 'done' array when it was significantly\n // different (in number of selected ranges, emptiness, or time).\n function addSelectionToHistory(doc, sel, opId, options) {\n var hist = doc.history, origin = options && options.origin;\n\n // A new event is started when the previous origin does not match\n // the current, or the origins don't allow matching. Origins\n // starting with * are always merged, those starting with + are\n // merged when similar and close together in time.\n if (opId == hist.lastSelOp ||\n (origin && hist.lastSelOrigin == origin &&\n (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||\n selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))\n { hist.done[hist.done.length - 1] = sel; }\n else\n { pushSelectionToHistory(sel, hist.done); }\n\n hist.lastSelTime = +new Date;\n hist.lastSelOrigin = origin;\n hist.lastSelOp = opId;\n if (options && options.clearRedo !== false)\n { clearSelectionEvents(hist.undone); }\n }\n\n function pushSelectionToHistory(sel, dest) {\n var top = lst(dest);\n if (!(top && top.ranges && top.equals(sel)))\n { dest.push(sel); }\n }\n\n // Used to store marked span information in the history.\n function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n }\n\n // When un/re-doing restores text containing marked spans, those\n // that have been explicitly cleared should not be restored.\n function removeClearedSpans(spans) {\n if (!spans) { return null }\n var out;\n for (var i = 0; i < spans.length; ++i) {\n if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }\n else if (out) { out.push(spans[i]); }\n }\n return !out ? spans : out.length ? out : null\n }\n\n // Retrieve and filter the old marked spans stored in a change event.\n function getOldSpans(doc, change) {\n var found = change[\"spans_\" + doc.id];\n if (!found) { return null }\n var nw = [];\n for (var i = 0; i < change.text.length; ++i)\n { nw.push(removeClearedSpans(found[i])); }\n return nw\n }\n\n // Used for un/re-doing changes from the history. Combines the\n // result of computing the existing spans with the set of spans that\n // existed in the history (so that deleting around a span and then\n // undoing brings back the span).\n function mergeOldSpans(doc, change) {\n var old = getOldSpans(doc, change);\n var stretched = stretchSpansOverChange(doc, change);\n if (!old) { return stretched }\n if (!stretched) { return old }\n\n for (var i = 0; i < old.length; ++i) {\n var oldCur = old[i], stretchCur = stretched[i];\n if (oldCur && stretchCur) {\n spans: for (var j = 0; j < stretchCur.length; ++j) {\n var span = stretchCur[j];\n for (var k = 0; k < oldCur.length; ++k)\n { if (oldCur[k].marker == span.marker) { continue spans } }\n oldCur.push(span);\n }\n } else if (stretchCur) {\n old[i] = stretchCur;\n }\n }\n return old\n }\n\n // Used both to provide a JSON-safe object in .getHistory, and, when\n // detaching a document, to split the history in two\n function copyHistoryArray(events, newGroup, instantiateSel) {\n var copy = [];\n for (var i = 0; i < events.length; ++i) {\n var event = events[i];\n if (event.ranges) {\n copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);\n continue\n }\n var changes = event.changes, newChanges = [];\n copy.push({changes: newChanges});\n for (var j = 0; j < changes.length; ++j) {\n var change = changes[j], m = (void 0);\n newChanges.push({from: change.from, to: change.to, text: change.text});\n if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\\d+)$/)) {\n if (indexOf(newGroup, Number(m[1])) > -1) {\n lst(newChanges)[prop] = change[prop];\n delete change[prop];\n }\n } } }\n }\n }\n return copy\n }\n\n // The 'scroll' parameter given to many of these indicated whether\n // the new cursor position should be scrolled into view after\n // modifying the selection.\n\n // If shift is held or the extend flag is set, extends a range to\n // include a given position (and optionally a second position).\n // Otherwise, simply returns the range between the given positions.\n // Used for cursor motion and such.\n function extendRange(range, head, other, extend) {\n if (extend) {\n var anchor = range.anchor;\n if (other) {\n var posBefore = cmp(head, anchor) < 0;\n if (posBefore != (cmp(other, anchor) < 0)) {\n anchor = head;\n head = other;\n } else if (posBefore != (cmp(head, other) < 0)) {\n head = other;\n }\n }\n return new Range(anchor, head)\n } else {\n return new Range(other || head, head)\n }\n }\n\n // Extend the primary selection range, discard the rest.\n function extendSelection(doc, head, other, options, extend) {\n if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }\n setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);\n }\n\n // Extend all selections (pos is an array of selections with length\n // equal the number of selections)\n function extendSelections(doc, heads, options) {\n var out = [];\n var extend = doc.cm && (doc.cm.display.shift || doc.extend);\n for (var i = 0; i < doc.sel.ranges.length; i++)\n { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }\n var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);\n setSelection(doc, newSel, options);\n }\n\n // Updates a single range in the selection.\n function replaceOneSelection(doc, i, range, options) {\n var ranges = doc.sel.ranges.slice(0);\n ranges[i] = range;\n setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);\n }\n\n // Reset the selection to a single range.\n function setSimpleSelection(doc, anchor, head, options) {\n setSelection(doc, simpleSelection(anchor, head), options);\n }\n\n // Give beforeSelectionChange handlers a change to influence a\n // selection update.\n function filterSelectionChange(doc, sel, options) {\n var obj = {\n ranges: sel.ranges,\n update: function(ranges) {\n var this$1 = this;\n\n this.ranges = [];\n for (var i = 0; i < ranges.length; i++)\n { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),\n clipPos(doc, ranges[i].head)); }\n },\n origin: options && options.origin\n };\n signal(doc, \"beforeSelectionChange\", doc, obj);\n if (doc.cm) { signal(doc.cm, \"beforeSelectionChange\", doc.cm, obj); }\n if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }\n else { return sel }\n }\n\n function setSelectionReplaceHistory(doc, sel, options) {\n var done = doc.history.done, last = lst(done);\n if (last && last.ranges) {\n done[done.length - 1] = sel;\n setSelectionNoUndo(doc, sel, options);\n } else {\n setSelection(doc, sel, options);\n }\n }\n\n // Set a new selection.\n function setSelection(doc, sel, options) {\n setSelectionNoUndo(doc, sel, options);\n addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);\n }\n\n function setSelectionNoUndo(doc, sel, options) {\n if (hasHandler(doc, \"beforeSelectionChange\") || doc.cm && hasHandler(doc.cm, \"beforeSelectionChange\"))\n { sel = filterSelectionChange(doc, sel, options); }\n\n var bias = options && options.bias ||\n (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);\n setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));\n\n if (!(options && options.scroll === false) && doc.cm)\n { ensureCursorVisible(doc.cm); }\n }\n\n function setSelectionInner(doc, sel) {\n if (sel.equals(doc.sel)) { return }\n\n doc.sel = sel;\n\n if (doc.cm) {\n doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;\n signalCursorActivity(doc.cm);\n }\n signalLater(doc, \"cursorActivity\", doc);\n }\n\n // Verify that the selection does not partially select any atomic\n // marked ranges.\n function reCheckSelection(doc) {\n setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));\n }\n\n // Return a selection that does not partially select any atomic\n // ranges.\n function skipAtomicInSelection(doc, sel, bias, mayClear) {\n var out;\n for (var i = 0; i < sel.ranges.length; i++) {\n var range = sel.ranges[i];\n var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];\n var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);\n var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);\n if (out || newAnchor != range.anchor || newHead != range.head) {\n if (!out) { out = sel.ranges.slice(0, i); }\n out[i] = new Range(newAnchor, newHead);\n }\n }\n return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel\n }\n\n function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {\n var line = getLine(doc, pos.line);\n if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {\n var sp = line.markedSpans[i], m = sp.marker;\n if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&\n (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {\n if (mayClear) {\n signal(m, \"beforeCursorEnter\");\n if (m.explicitlyCleared) {\n if (!line.markedSpans) { break }\n else {--i; continue}\n }\n }\n if (!m.atomic) { continue }\n\n if (oldPos) {\n var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);\n if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)\n { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }\n if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))\n { return skipAtomicInner(doc, near, pos, dir, mayClear) }\n }\n\n var far = m.find(dir < 0 ? -1 : 1);\n if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)\n { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }\n return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null\n }\n } }\n return pos\n }\n\n // Ensure a given position is not inside an atomic range.\n function skipAtomic(doc, pos, oldPos, bias, mayClear) {\n var dir = bias || 1;\n var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||\n (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||\n skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||\n (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));\n if (!found) {\n doc.cantEdit = true;\n return Pos(doc.first, 0)\n }\n return found\n }\n\n function movePos(doc, pos, dir, line) {\n if (dir < 0 && pos.ch == 0) {\n if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }\n else { return null }\n } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {\n if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }\n else { return null }\n } else {\n return new Pos(pos.line, pos.ch + dir)\n }\n }\n\n function selectAll(cm) {\n cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);\n }\n\n // UPDATING\n\n // Allow \"beforeChange\" event handlers to influence a change\n function filterChange(doc, change, update) {\n var obj = {\n canceled: false,\n from: change.from,\n to: change.to,\n text: change.text,\n origin: change.origin,\n cancel: function () { return obj.canceled = true; }\n };\n if (update) { obj.update = function (from, to, text, origin) {\n if (from) { obj.from = clipPos(doc, from); }\n if (to) { obj.to = clipPos(doc, to); }\n if (text) { obj.text = text; }\n if (origin !== undefined) { obj.origin = origin; }\n }; }\n signal(doc, \"beforeChange\", doc, obj);\n if (doc.cm) { signal(doc.cm, \"beforeChange\", doc.cm, obj); }\n\n if (obj.canceled) { return null }\n return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}\n }\n\n // Apply a change to a document, and add it to the document's\n // history, and propagating it to all linked documents.\n function makeChange(doc, change, ignoreReadOnly) {\n if (doc.cm) {\n if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }\n if (doc.cm.state.suppressEdits) { return }\n }\n\n if (hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\")) {\n change = filterChange(doc, change, true);\n if (!change) { return }\n }\n\n // Possibly split or suppress the update based on the presence\n // of read-only spans in its range.\n var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);\n if (split) {\n for (var i = split.length - 1; i >= 0; --i)\n { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [\"\"] : change.text, origin: change.origin}); }\n } else {\n makeChangeInner(doc, change);\n }\n }\n\n function makeChangeInner(doc, change) {\n if (change.text.length == 1 && change.text[0] == \"\" && cmp(change.from, change.to) == 0) { return }\n var selAfter = computeSelAfterChange(doc, change);\n addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);\n\n makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));\n var rebased = [];\n\n linkedDocs(doc, function (doc, sharedHist) {\n if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n rebaseHist(doc.history, change);\n rebased.push(doc.history);\n }\n makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));\n });\n }\n\n // Revert a change stored in a document's history.\n function makeChangeFromHistory(doc, type, allowSelectionOnly) {\n var suppress = doc.cm && doc.cm.state.suppressEdits;\n if (suppress && !allowSelectionOnly) { return }\n\n var hist = doc.history, event, selAfter = doc.sel;\n var source = type == \"undo\" ? hist.done : hist.undone, dest = type == \"undo\" ? hist.undone : hist.done;\n\n // Verify that there is a useable event (so that ctrl-z won't\n // needlessly clear selection events)\n var i = 0;\n for (; i < source.length; i++) {\n event = source[i];\n if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)\n { break }\n }\n if (i == source.length) { return }\n hist.lastOrigin = hist.lastSelOrigin = null;\n\n for (;;) {\n event = source.pop();\n if (event.ranges) {\n pushSelectionToHistory(event, dest);\n if (allowSelectionOnly && !event.equals(doc.sel)) {\n setSelection(doc, event, {clearRedo: false});\n return\n }\n selAfter = event;\n } else if (suppress) {\n source.push(event);\n return\n } else { break }\n }\n\n // Build up a reverse change object to add to the opposite history\n // stack (redo when undoing, and vice versa).\n var antiChanges = [];\n pushSelectionToHistory(selAfter, dest);\n dest.push({changes: antiChanges, generation: hist.generation});\n hist.generation = event.generation || ++hist.maxGeneration;\n\n var filter = hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\");\n\n var loop = function ( i ) {\n var change = event.changes[i];\n change.origin = type;\n if (filter && !filterChange(doc, change, false)) {\n source.length = 0;\n return {}\n }\n\n antiChanges.push(historyChangeFromChange(doc, change));\n\n var after = i ? computeSelAfterChange(doc, change) : lst(source);\n makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));\n if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }\n var rebased = [];\n\n // Propagate to the linked documents\n linkedDocs(doc, function (doc, sharedHist) {\n if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n rebaseHist(doc.history, change);\n rebased.push(doc.history);\n }\n makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));\n });\n };\n\n for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {\n var returned = loop( i$1 );\n\n if ( returned ) return returned.v;\n }\n }\n\n // Sub-views need their line numbers shifted when text is added\n // above or below them in the parent document.\n function shiftDoc(doc, distance) {\n if (distance == 0) { return }\n doc.first += distance;\n doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(\n Pos(range.anchor.line + distance, range.anchor.ch),\n Pos(range.head.line + distance, range.head.ch)\n ); }), doc.sel.primIndex);\n if (doc.cm) {\n regChange(doc.cm, doc.first, doc.first - distance, distance);\n for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)\n { regLineChange(doc.cm, l, \"gutter\"); }\n }\n }\n\n // More lower-level change function, handling only a single document\n // (not linked ones).\n function makeChangeSingleDoc(doc, change, selAfter, spans) {\n if (doc.cm && !doc.cm.curOp)\n { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }\n\n if (change.to.line < doc.first) {\n shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));\n return\n }\n if (change.from.line > doc.lastLine()) { return }\n\n // Clip the change to the size of this doc\n if (change.from.line < doc.first) {\n var shift = change.text.length - 1 - (doc.first - change.from.line);\n shiftDoc(doc, shift);\n change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),\n text: [lst(change.text)], origin: change.origin};\n }\n var last = doc.lastLine();\n if (change.to.line > last) {\n change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),\n text: [change.text[0]], origin: change.origin};\n }\n\n change.removed = getBetween(doc, change.from, change.to);\n\n if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }\n if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }\n else { updateDoc(doc, change, spans); }\n setSelectionNoUndo(doc, selAfter, sel_dontScroll);\n }\n\n // Handle the interaction of a change to a document with the editor\n // that this document is part of.\n function makeChangeSingleDocInEditor(cm, change, spans) {\n var doc = cm.doc, display = cm.display, from = change.from, to = change.to;\n\n var recomputeMaxLength = false, checkWidthStart = from.line;\n if (!cm.options.lineWrapping) {\n checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));\n doc.iter(checkWidthStart, to.line + 1, function (line) {\n if (line == display.maxLine) {\n recomputeMaxLength = true;\n return true\n }\n });\n }\n\n if (doc.sel.contains(change.from, change.to) > -1)\n { signalCursorActivity(cm); }\n\n updateDoc(doc, change, spans, estimateHeight(cm));\n\n if (!cm.options.lineWrapping) {\n doc.iter(checkWidthStart, from.line + change.text.length, function (line) {\n var len = lineLength(line);\n if (len > display.maxLineLength) {\n display.maxLine = line;\n display.maxLineLength = len;\n display.maxLineChanged = true;\n recomputeMaxLength = false;\n }\n });\n if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }\n }\n\n retreatFrontier(doc, from.line);\n startWorker(cm, 400);\n\n var lendiff = change.text.length - (to.line - from.line) - 1;\n // Remember that these lines changed, for updating the display\n if (change.full)\n { regChange(cm); }\n else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))\n { regLineChange(cm, from.line, \"text\"); }\n else\n { regChange(cm, from.line, to.line + 1, lendiff); }\n\n var changesHandler = hasHandler(cm, \"changes\"), changeHandler = hasHandler(cm, \"change\");\n if (changeHandler || changesHandler) {\n var obj = {\n from: from, to: to,\n text: change.text,\n removed: change.removed,\n origin: change.origin\n };\n if (changeHandler) { signalLater(cm, \"change\", cm, obj); }\n if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }\n }\n cm.display.selForContextMenu = null;\n }\n\n function replaceRange(doc, code, from, to, origin) {\n var assign;\n\n if (!to) { to = from; }\n if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }\n if (typeof code == \"string\") { code = doc.splitLines(code); }\n makeChange(doc, {from: from, to: to, text: code, origin: origin});\n }\n\n // Rebasing/resetting history to deal with externally-sourced changes\n\n function rebaseHistSelSingle(pos, from, to, diff) {\n if (to < pos.line) {\n pos.line += diff;\n } else if (from < pos.line) {\n pos.line = from;\n pos.ch = 0;\n }\n }\n\n // Tries to rebase an array of history events given a change in the\n // document. If the change touches the same lines as the event, the\n // event, and everything 'behind' it, is discarded. If the change is\n // before the event, the event's positions are updated. Uses a\n // copy-on-write scheme for the positions, to avoid having to\n // reallocate them all on every rebase, but also avoid problems with\n // shared position objects being unsafely updated.\n function rebaseHistArray(array, from, to, diff) {\n for (var i = 0; i < array.length; ++i) {\n var sub = array[i], ok = true;\n if (sub.ranges) {\n if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }\n for (var j = 0; j < sub.ranges.length; j++) {\n rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);\n rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);\n }\n continue\n }\n for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {\n var cur = sub.changes[j$1];\n if (to < cur.from.line) {\n cur.from = Pos(cur.from.line + diff, cur.from.ch);\n cur.to = Pos(cur.to.line + diff, cur.to.ch);\n } else if (from <= cur.to.line) {\n ok = false;\n break\n }\n }\n if (!ok) {\n array.splice(0, i + 1);\n i = 0;\n }\n }\n }\n\n function rebaseHist(hist, change) {\n var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;\n rebaseHistArray(hist.done, from, to, diff);\n rebaseHistArray(hist.undone, from, to, diff);\n }\n\n // Utility for applying a change to a line by handle or number,\n // returning the number and optionally registering the line as\n // changed.\n function changeLine(doc, handle, changeType, op) {\n var no = handle, line = handle;\n if (typeof handle == \"number\") { line = getLine(doc, clipLine(doc, handle)); }\n else { no = lineNo(handle); }\n if (no == null) { return null }\n if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }\n return line\n }\n\n // The document is represented as a BTree consisting of leaves, with\n // chunk of lines in them, and branches, with up to ten leaves or\n // other branch nodes below them. The top node is always a branch\n // node, and is the document object itself (meaning it has\n // additional methods and properties).\n //\n // All nodes have parent links. The tree is used both to go from\n // line numbers to line objects, and to go from objects to numbers.\n // It also indexes by height, and is used to convert between height\n // and line object, and to find the total height of the document.\n //\n // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html\n\n function LeafChunk(lines) {\n var this$1 = this;\n\n this.lines = lines;\n this.parent = null;\n var height = 0;\n for (var i = 0; i < lines.length; ++i) {\n lines[i].parent = this$1;\n height += lines[i].height;\n }\n this.height = height;\n }\n\n LeafChunk.prototype = {\n chunkSize: function() { return this.lines.length },\n\n // Remove the n lines at offset 'at'.\n removeInner: function(at, n) {\n var this$1 = this;\n\n for (var i = at, e = at + n; i < e; ++i) {\n var line = this$1.lines[i];\n this$1.height -= line.height;\n cleanUpLine(line);\n signalLater(line, \"delete\");\n }\n this.lines.splice(at, n);\n },\n\n // Helper used to collapse a small branch into a single leaf.\n collapse: function(lines) {\n lines.push.apply(lines, this.lines);\n },\n\n // Insert the given array of lines at offset 'at', count them as\n // having the given height.\n insertInner: function(at, lines, height) {\n var this$1 = this;\n\n this.height += height;\n this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));\n for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }\n },\n\n // Used to iterate over a part of the tree.\n iterN: function(at, n, op) {\n var this$1 = this;\n\n for (var e = at + n; at < e; ++at)\n { if (op(this$1.lines[at])) { return true } }\n }\n };\n\n function BranchChunk(children) {\n var this$1 = this;\n\n this.children = children;\n var size = 0, height = 0;\n for (var i = 0; i < children.length; ++i) {\n var ch = children[i];\n size += ch.chunkSize(); height += ch.height;\n ch.parent = this$1;\n }\n this.size = size;\n this.height = height;\n this.parent = null;\n }\n\n BranchChunk.prototype = {\n chunkSize: function() { return this.size },\n\n removeInner: function(at, n) {\n var this$1 = this;\n\n this.size -= n;\n for (var i = 0; i < this.children.length; ++i) {\n var child = this$1.children[i], sz = child.chunkSize();\n if (at < sz) {\n var rm = Math.min(n, sz - at), oldHeight = child.height;\n child.removeInner(at, rm);\n this$1.height -= oldHeight - child.height;\n if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }\n if ((n -= rm) == 0) { break }\n at = 0;\n } else { at -= sz; }\n }\n // If the result is smaller than 25 lines, ensure that it is a\n // single leaf node.\n if (this.size - n < 25 &&\n (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {\n var lines = [];\n this.collapse(lines);\n this.children = [new LeafChunk(lines)];\n this.children[0].parent = this;\n }\n },\n\n collapse: function(lines) {\n var this$1 = this;\n\n for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }\n },\n\n insertInner: function(at, lines, height) {\n var this$1 = this;\n\n this.size += lines.length;\n this.height += height;\n for (var i = 0; i < this.children.length; ++i) {\n var child = this$1.children[i], sz = child.chunkSize();\n if (at <= sz) {\n child.insertInner(at, lines, height);\n if (child.lines && child.lines.length > 50) {\n // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.\n // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.\n var remaining = child.lines.length % 25 + 25;\n for (var pos = remaining; pos < child.lines.length;) {\n var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));\n child.height -= leaf.height;\n this$1.children.splice(++i, 0, leaf);\n leaf.parent = this$1;\n }\n child.lines = child.lines.slice(0, remaining);\n this$1.maybeSpill();\n }\n break\n }\n at -= sz;\n }\n },\n\n // When a node has grown, check whether it should be split.\n maybeSpill: function() {\n if (this.children.length <= 10) { return }\n var me = this;\n do {\n var spilled = me.children.splice(me.children.length - 5, 5);\n var sibling = new BranchChunk(spilled);\n if (!me.parent) { // Become the parent node\n var copy = new BranchChunk(me.children);\n copy.parent = me;\n me.children = [copy, sibling];\n me = copy;\n } else {\n me.size -= sibling.size;\n me.height -= sibling.height;\n var myIndex = indexOf(me.parent.children, me);\n me.parent.children.splice(myIndex + 1, 0, sibling);\n }\n sibling.parent = me.parent;\n } while (me.children.length > 10)\n me.parent.maybeSpill();\n },\n\n iterN: function(at, n, op) {\n var this$1 = this;\n\n for (var i = 0; i < this.children.length; ++i) {\n var child = this$1.children[i], sz = child.chunkSize();\n if (at < sz) {\n var used = Math.min(n, sz - at);\n if (child.iterN(at, used, op)) { return true }\n if ((n -= used) == 0) { break }\n at = 0;\n } else { at -= sz; }\n }\n }\n };\n\n // Line widgets are block elements displayed above or below a line.\n\n var LineWidget = function(doc, node, options) {\n var this$1 = this;\n\n if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))\n { this$1[opt] = options[opt]; } } }\n this.doc = doc;\n this.node = node;\n };\n\n LineWidget.prototype.clear = function () {\n var this$1 = this;\n\n var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);\n if (no == null || !ws) { return }\n for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }\n if (!ws.length) { line.widgets = null; }\n var height = widgetHeight(this);\n updateLineHeight(line, Math.max(0, line.height - height));\n if (cm) {\n runInOp(cm, function () {\n adjustScrollWhenAboveVisible(cm, line, -height);\n regLineChange(cm, no, \"widget\");\n });\n signalLater(cm, \"lineWidgetCleared\", cm, this, no);\n }\n };\n\n LineWidget.prototype.changed = function () {\n var this$1 = this;\n\n var oldH = this.height, cm = this.doc.cm, line = this.line;\n this.height = null;\n var diff = widgetHeight(this) - oldH;\n if (!diff) { return }\n if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }\n if (cm) {\n runInOp(cm, function () {\n cm.curOp.forceUpdate = true;\n adjustScrollWhenAboveVisible(cm, line, diff);\n signalLater(cm, \"lineWidgetChanged\", cm, this$1, lineNo(line));\n });\n }\n };\n eventMixin(LineWidget);\n\n function adjustScrollWhenAboveVisible(cm, line, diff) {\n if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))\n { addToScrollTop(cm, diff); }\n }\n\n function addLineWidget(doc, handle, node, options) {\n var widget = new LineWidget(doc, node, options);\n var cm = doc.cm;\n if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }\n changeLine(doc, handle, \"widget\", function (line) {\n var widgets = line.widgets || (line.widgets = []);\n if (widget.insertAt == null) { widgets.push(widget); }\n else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }\n widget.line = line;\n if (cm && !lineIsHidden(doc, line)) {\n var aboveVisible = heightAtLine(line) < doc.scrollTop;\n updateLineHeight(line, line.height + widgetHeight(widget));\n if (aboveVisible) { addToScrollTop(cm, widget.height); }\n cm.curOp.forceUpdate = true;\n }\n return true\n });\n if (cm) { signalLater(cm, \"lineWidgetAdded\", cm, widget, typeof handle == \"number\" ? handle : lineNo(handle)); }\n return widget\n }\n\n // TEXTMARKERS\n\n // Created with markText and setBookmark methods. A TextMarker is a\n // handle that can be used to clear or find a marked position in the\n // document. Line objects hold arrays (markedSpans) containing\n // {from, to, marker} object pointing to such marker objects, and\n // indicating that such a marker is present on that line. Multiple\n // lines may point to the same marker when it spans across lines.\n // The spans will have null for their from/to properties when the\n // marker continues beyond the start/end of the line. Markers have\n // links back to the lines they currently touch.\n\n // Collapsed markers have unique ids, in order to be able to order\n // them, which is needed for uniquely determining an outer marker\n // when they overlap (they may nest, but not partially overlap).\n var nextMarkerId = 0;\n\n var TextMarker = function(doc, type) {\n this.lines = [];\n this.type = type;\n this.doc = doc;\n this.id = ++nextMarkerId;\n };\n\n // Clear the marker.\n TextMarker.prototype.clear = function () {\n var this$1 = this;\n\n if (this.explicitlyCleared) { return }\n var cm = this.doc.cm, withOp = cm && !cm.curOp;\n if (withOp) { startOperation(cm); }\n if (hasHandler(this, \"clear\")) {\n var found = this.find();\n if (found) { signalLater(this, \"clear\", found.from, found.to); }\n }\n var min = null, max = null;\n for (var i = 0; i < this.lines.length; ++i) {\n var line = this$1.lines[i];\n var span = getMarkedSpanFor(line.markedSpans, this$1);\n if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), \"text\"); }\n else if (cm) {\n if (span.to != null) { max = lineNo(line); }\n if (span.from != null) { min = lineNo(line); }\n }\n line.markedSpans = removeMarkedSpan(line.markedSpans, span);\n if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)\n { updateLineHeight(line, textHeight(cm.display)); }\n }\n if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {\n var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);\n if (len > cm.display.maxLineLength) {\n cm.display.maxLine = visual;\n cm.display.maxLineLength = len;\n cm.display.maxLineChanged = true;\n }\n } }\n\n if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }\n this.lines.length = 0;\n this.explicitlyCleared = true;\n if (this.atomic && this.doc.cantEdit) {\n this.doc.cantEdit = false;\n if (cm) { reCheckSelection(cm.doc); }\n }\n if (cm) { signalLater(cm, \"markerCleared\", cm, this, min, max); }\n if (withOp) { endOperation(cm); }\n if (this.parent) { this.parent.clear(); }\n };\n\n // Find the position of the marker in the document. Returns a {from,\n // to} object by default. Side can be passed to get a specific side\n // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the\n // Pos objects returned contain a line object, rather than a line\n // number (used to prevent looking up the same line twice).\n TextMarker.prototype.find = function (side, lineObj) {\n var this$1 = this;\n\n if (side == null && this.type == \"bookmark\") { side = 1; }\n var from, to;\n for (var i = 0; i < this.lines.length; ++i) {\n var line = this$1.lines[i];\n var span = getMarkedSpanFor(line.markedSpans, this$1);\n if (span.from != null) {\n from = Pos(lineObj ? line : lineNo(line), span.from);\n if (side == -1) { return from }\n }\n if (span.to != null) {\n to = Pos(lineObj ? line : lineNo(line), span.to);\n if (side == 1) { return to }\n }\n }\n return from && {from: from, to: to}\n };\n\n // Signals that the marker's widget changed, and surrounding layout\n // should be recomputed.\n TextMarker.prototype.changed = function () {\n var this$1 = this;\n\n var pos = this.find(-1, true), widget = this, cm = this.doc.cm;\n if (!pos || !cm) { return }\n runInOp(cm, function () {\n var line = pos.line, lineN = lineNo(pos.line);\n var view = findViewForLine(cm, lineN);\n if (view) {\n clearLineMeasurementCacheFor(view);\n cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;\n }\n cm.curOp.updateMaxLine = true;\n if (!lineIsHidden(widget.doc, line) && widget.height != null) {\n var oldHeight = widget.height;\n widget.height = null;\n var dHeight = widgetHeight(widget) - oldHeight;\n if (dHeight)\n { updateLineHeight(line, line.height + dHeight); }\n }\n signalLater(cm, \"markerChanged\", cm, this$1);\n });\n };\n\n TextMarker.prototype.attachLine = function (line) {\n if (!this.lines.length && this.doc.cm) {\n var op = this.doc.cm.curOp;\n if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)\n { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }\n }\n this.lines.push(line);\n };\n\n TextMarker.prototype.detachLine = function (line) {\n this.lines.splice(indexOf(this.lines, line), 1);\n if (!this.lines.length && this.doc.cm) {\n var op = this.doc.cm.curOp\n ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);\n }\n };\n eventMixin(TextMarker);\n\n // Create a marker, wire it up to the right lines, and\n function markText(doc, from, to, options, type) {\n // Shared markers (across linked documents) are handled separately\n // (markTextShared will call out to this again, once per\n // document).\n if (options && options.shared) { return markTextShared(doc, from, to, options, type) }\n // Ensure we are in an operation.\n if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }\n\n var marker = new TextMarker(doc, type), diff = cmp(from, to);\n if (options) { copyObj(options, marker, false); }\n // Don't connect empty markers unless clearWhenEmpty is false\n if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)\n { return marker }\n if (marker.replacedWith) {\n // Showing up as a widget implies collapsed (widget replaces text)\n marker.collapsed = true;\n marker.widgetNode = eltP(\"span\", [marker.replacedWith], \"CodeMirror-widget\");\n if (!options.handleMouseEvents) { marker.widgetNode.setAttribute(\"cm-ignore-events\", \"true\"); }\n if (options.insertLeft) { marker.widgetNode.insertLeft = true; }\n }\n if (marker.collapsed) {\n if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||\n from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))\n { throw new Error(\"Inserting collapsed marker partially overlapping an existing one\") }\n seeCollapsedSpans();\n }\n\n if (marker.addToHistory)\n { addChangeToHistory(doc, {from: from, to: to, origin: \"markText\"}, doc.sel, NaN); }\n\n var curLine = from.line, cm = doc.cm, updateMaxLine;\n doc.iter(curLine, to.line + 1, function (line) {\n if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)\n { updateMaxLine = true; }\n if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }\n addMarkedSpan(line, new MarkedSpan(marker,\n curLine == from.line ? from.ch : null,\n curLine == to.line ? to.ch : null));\n ++curLine;\n });\n // lineIsHidden depends on the presence of the spans, so needs a second pass\n if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {\n if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }\n }); }\n\n if (marker.clearOnEnter) { on(marker, \"beforeCursorEnter\", function () { return marker.clear(); }); }\n\n if (marker.readOnly) {\n seeReadOnlySpans();\n if (doc.history.done.length || doc.history.undone.length)\n { doc.clearHistory(); }\n }\n if (marker.collapsed) {\n marker.id = ++nextMarkerId;\n marker.atomic = true;\n }\n if (cm) {\n // Sync editor state\n if (updateMaxLine) { cm.curOp.updateMaxLine = true; }\n if (marker.collapsed)\n { regChange(cm, from.line, to.line + 1); }\n else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||\n marker.attributes || marker.title)\n { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, \"text\"); } }\n if (marker.atomic) { reCheckSelection(cm.doc); }\n signalLater(cm, \"markerAdded\", cm, marker);\n }\n return marker\n }\n\n // SHARED TEXTMARKERS\n\n // A shared marker spans multiple linked documents. It is\n // implemented as a meta-marker-object controlling multiple normal\n // markers.\n var SharedTextMarker = function(markers, primary) {\n var this$1 = this;\n\n this.markers = markers;\n this.primary = primary;\n for (var i = 0; i < markers.length; ++i)\n { markers[i].parent = this$1; }\n };\n\n SharedTextMarker.prototype.clear = function () {\n var this$1 = this;\n\n if (this.explicitlyCleared) { return }\n this.explicitlyCleared = true;\n for (var i = 0; i < this.markers.length; ++i)\n { this$1.markers[i].clear(); }\n signalLater(this, \"clear\");\n };\n\n SharedTextMarker.prototype.find = function (side, lineObj) {\n return this.primary.find(side, lineObj)\n };\n eventMixin(SharedTextMarker);\n\n function markTextShared(doc, from, to, options, type) {\n options = copyObj(options);\n options.shared = false;\n var markers = [markText(doc, from, to, options, type)], primary = markers[0];\n var widget = options.widgetNode;\n linkedDocs(doc, function (doc) {\n if (widget) { options.widgetNode = widget.cloneNode(true); }\n markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));\n for (var i = 0; i < doc.linked.length; ++i)\n { if (doc.linked[i].isParent) { return } }\n primary = lst(markers);\n });\n return new SharedTextMarker(markers, primary)\n }\n\n function findSharedMarkers(doc) {\n return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })\n }\n\n function copySharedMarkers(doc, markers) {\n for (var i = 0; i < markers.length; i++) {\n var marker = markers[i], pos = marker.find();\n var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);\n if (cmp(mFrom, mTo)) {\n var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);\n marker.markers.push(subMark);\n subMark.parent = marker;\n }\n }\n }\n\n function detachSharedMarkers(markers) {\n var loop = function ( i ) {\n var marker = markers[i], linked = [marker.primary.doc];\n linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });\n for (var j = 0; j < marker.markers.length; j++) {\n var subMarker = marker.markers[j];\n if (indexOf(linked, subMarker.doc) == -1) {\n subMarker.parent = null;\n marker.markers.splice(j--, 1);\n }\n }\n };\n\n for (var i = 0; i < markers.length; i++) loop( i );\n }\n\n var nextDocId = 0;\n var Doc = function(text, mode, firstLine, lineSep, direction) {\n if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }\n if (firstLine == null) { firstLine = 0; }\n\n BranchChunk.call(this, [new LeafChunk([new Line(\"\", null)])]);\n this.first = firstLine;\n this.scrollTop = this.scrollLeft = 0;\n this.cantEdit = false;\n this.cleanGeneration = 1;\n this.modeFrontier = this.highlightFrontier = firstLine;\n var start = Pos(firstLine, 0);\n this.sel = simpleSelection(start);\n this.history = new History(null);\n this.id = ++nextDocId;\n this.modeOption = mode;\n this.lineSep = lineSep;\n this.direction = (direction == \"rtl\") ? \"rtl\" : \"ltr\";\n this.extend = false;\n\n if (typeof text == \"string\") { text = this.splitLines(text); }\n updateDoc(this, {from: start, to: start, text: text});\n setSelection(this, simpleSelection(start), sel_dontScroll);\n };\n\n Doc.prototype = createObj(BranchChunk.prototype, {\n constructor: Doc,\n // Iterate over the document. Supports two forms -- with only one\n // argument, it calls that for each line in the document. With\n // three, it iterates over the range given by the first two (with\n // the second being non-inclusive).\n iter: function(from, to, op) {\n if (op) { this.iterN(from - this.first, to - from, op); }\n else { this.iterN(this.first, this.first + this.size, from); }\n },\n\n // Non-public interface for adding and removing lines.\n insert: function(at, lines) {\n var height = 0;\n for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }\n this.insertInner(at - this.first, lines, height);\n },\n remove: function(at, n) { this.removeInner(at - this.first, n); },\n\n // From here, the methods are part of the public interface. Most\n // are also available from CodeMirror (editor) instances.\n\n getValue: function(lineSep) {\n var lines = getLines(this, this.first, this.first + this.size);\n if (lineSep === false) { return lines }\n return lines.join(lineSep || this.lineSeparator())\n },\n setValue: docMethodOp(function(code) {\n var top = Pos(this.first, 0), last = this.first + this.size - 1;\n makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),\n text: this.splitLines(code), origin: \"setValue\", full: true}, true);\n if (this.cm) { scrollToCoords(this.cm, 0, 0); }\n setSelection(this, simpleSelection(top), sel_dontScroll);\n }),\n replaceRange: function(code, from, to, origin) {\n from = clipPos(this, from);\n to = to ? clipPos(this, to) : from;\n replaceRange(this, code, from, to, origin);\n },\n getRange: function(from, to, lineSep) {\n var lines = getBetween(this, clipPos(this, from), clipPos(this, to));\n if (lineSep === false) { return lines }\n return lines.join(lineSep || this.lineSeparator())\n },\n\n getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},\n\n getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},\n getLineNumber: function(line) {return lineNo(line)},\n\n getLineHandleVisualStart: function(line) {\n if (typeof line == \"number\") { line = getLine(this, line); }\n return visualLine(line)\n },\n\n lineCount: function() {return this.size},\n firstLine: function() {return this.first},\n lastLine: function() {return this.first + this.size - 1},\n\n clipPos: function(pos) {return clipPos(this, pos)},\n\n getCursor: function(start) {\n var range$$1 = this.sel.primary(), pos;\n if (start == null || start == \"head\") { pos = range$$1.head; }\n else if (start == \"anchor\") { pos = range$$1.anchor; }\n else if (start == \"end\" || start == \"to\" || start === false) { pos = range$$1.to(); }\n else { pos = range$$1.from(); }\n return pos\n },\n listSelections: function() { return this.sel.ranges },\n somethingSelected: function() {return this.sel.somethingSelected()},\n\n setCursor: docMethodOp(function(line, ch, options) {\n setSimpleSelection(this, clipPos(this, typeof line == \"number\" ? Pos(line, ch || 0) : line), null, options);\n }),\n setSelection: docMethodOp(function(anchor, head, options) {\n setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);\n }),\n extendSelection: docMethodOp(function(head, other, options) {\n extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);\n }),\n extendSelections: docMethodOp(function(heads, options) {\n extendSelections(this, clipPosArray(this, heads), options);\n }),\n extendSelectionsBy: docMethodOp(function(f, options) {\n var heads = map(this.sel.ranges, f);\n extendSelections(this, clipPosArray(this, heads), options);\n }),\n setSelections: docMethodOp(function(ranges, primary, options) {\n var this$1 = this;\n\n if (!ranges.length) { return }\n var out = [];\n for (var i = 0; i < ranges.length; i++)\n { out[i] = new Range(clipPos(this$1, ranges[i].anchor),\n clipPos(this$1, ranges[i].head)); }\n if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }\n setSelection(this, normalizeSelection(this.cm, out, primary), options);\n }),\n addSelection: docMethodOp(function(anchor, head, options) {\n var ranges = this.sel.ranges.slice(0);\n ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));\n setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);\n }),\n\n getSelection: function(lineSep) {\n var this$1 = this;\n\n var ranges = this.sel.ranges, lines;\n for (var i = 0; i < ranges.length; i++) {\n var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());\n lines = lines ? lines.concat(sel) : sel;\n }\n if (lineSep === false) { return lines }\n else { return lines.join(lineSep || this.lineSeparator()) }\n },\n getSelections: function(lineSep) {\n var this$1 = this;\n\n var parts = [], ranges = this.sel.ranges;\n for (var i = 0; i < ranges.length; i++) {\n var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());\n if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }\n parts[i] = sel;\n }\n return parts\n },\n replaceSelection: function(code, collapse, origin) {\n var dup = [];\n for (var i = 0; i < this.sel.ranges.length; i++)\n { dup[i] = code; }\n this.replaceSelections(dup, collapse, origin || \"+input\");\n },\n replaceSelections: docMethodOp(function(code, collapse, origin) {\n var this$1 = this;\n\n var changes = [], sel = this.sel;\n for (var i = 0; i < sel.ranges.length; i++) {\n var range$$1 = sel.ranges[i];\n changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};\n }\n var newSel = collapse && collapse != \"end\" && computeReplacedSel(this, changes, collapse);\n for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)\n { makeChange(this$1, changes[i$1]); }\n if (newSel) { setSelectionReplaceHistory(this, newSel); }\n else if (this.cm) { ensureCursorVisible(this.cm); }\n }),\n undo: docMethodOp(function() {makeChangeFromHistory(this, \"undo\");}),\n redo: docMethodOp(function() {makeChangeFromHistory(this, \"redo\");}),\n undoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"undo\", true);}),\n redoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"redo\", true);}),\n\n setExtending: function(val) {this.extend = val;},\n getExtending: function() {return this.extend},\n\n historySize: function() {\n var hist = this.history, done = 0, undone = 0;\n for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }\n for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }\n return {undo: done, redo: undone}\n },\n clearHistory: function() {this.history = new History(this.history.maxGeneration);},\n\n markClean: function() {\n this.cleanGeneration = this.changeGeneration(true);\n },\n changeGeneration: function(forceSplit) {\n if (forceSplit)\n { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }\n return this.history.generation\n },\n isClean: function (gen) {\n return this.history.generation == (gen || this.cleanGeneration)\n },\n\n getHistory: function() {\n return {done: copyHistoryArray(this.history.done),\n undone: copyHistoryArray(this.history.undone)}\n },\n setHistory: function(histData) {\n var hist = this.history = new History(this.history.maxGeneration);\n hist.done = copyHistoryArray(histData.done.slice(0), null, true);\n hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);\n },\n\n setGutterMarker: docMethodOp(function(line, gutterID, value) {\n return changeLine(this, line, \"gutter\", function (line) {\n var markers = line.gutterMarkers || (line.gutterMarkers = {});\n markers[gutterID] = value;\n if (!value && isEmpty(markers)) { line.gutterMarkers = null; }\n return true\n })\n }),\n\n clearGutter: docMethodOp(function(gutterID) {\n var this$1 = this;\n\n this.iter(function (line) {\n if (line.gutterMarkers && line.gutterMarkers[gutterID]) {\n changeLine(this$1, line, \"gutter\", function () {\n line.gutterMarkers[gutterID] = null;\n if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }\n return true\n });\n }\n });\n }),\n\n lineInfo: function(line) {\n var n;\n if (typeof line == \"number\") {\n if (!isLine(this, line)) { return null }\n n = line;\n line = getLine(this, line);\n if (!line) { return null }\n } else {\n n = lineNo(line);\n if (n == null) { return null }\n }\n return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,\n textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,\n widgets: line.widgets}\n },\n\n addLineClass: docMethodOp(function(handle, where, cls) {\n return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", function (line) {\n var prop = where == \"text\" ? \"textClass\"\n : where == \"background\" ? \"bgClass\"\n : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\";\n if (!line[prop]) { line[prop] = cls; }\n else if (classTest(cls).test(line[prop])) { return false }\n else { line[prop] += \" \" + cls; }\n return true\n })\n }),\n removeLineClass: docMethodOp(function(handle, where, cls) {\n return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", function (line) {\n var prop = where == \"text\" ? \"textClass\"\n : where == \"background\" ? \"bgClass\"\n : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\";\n var cur = line[prop];\n if (!cur) { return false }\n else if (cls == null) { line[prop] = null; }\n else {\n var found = cur.match(classTest(cls));\n if (!found) { return false }\n var end = found.index + found[0].length;\n line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? \"\" : \" \") + cur.slice(end) || null;\n }\n return true\n })\n }),\n\n addLineWidget: docMethodOp(function(handle, node, options) {\n return addLineWidget(this, handle, node, options)\n }),\n removeLineWidget: function(widget) { widget.clear(); },\n\n markText: function(from, to, options) {\n return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || \"range\")\n },\n setBookmark: function(pos, options) {\n var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),\n insertLeft: options && options.insertLeft,\n clearWhenEmpty: false, shared: options && options.shared,\n handleMouseEvents: options && options.handleMouseEvents};\n pos = clipPos(this, pos);\n return markText(this, pos, pos, realOpts, \"bookmark\")\n },\n findMarksAt: function(pos) {\n pos = clipPos(this, pos);\n var markers = [], spans = getLine(this, pos.line).markedSpans;\n if (spans) { for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if ((span.from == null || span.from <= pos.ch) &&\n (span.to == null || span.to >= pos.ch))\n { markers.push(span.marker.parent || span.marker); }\n } }\n return markers\n },\n findMarks: function(from, to, filter) {\n from = clipPos(this, from); to = clipPos(this, to);\n var found = [], lineNo$$1 = from.line;\n this.iter(from.line, to.line + 1, function (line) {\n var spans = line.markedSpans;\n if (spans) { for (var i = 0; i < spans.length; i++) {\n var span = spans[i];\n if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||\n span.from == null && lineNo$$1 != from.line ||\n span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&\n (!filter || filter(span.marker)))\n { found.push(span.marker.parent || span.marker); }\n } }\n ++lineNo$$1;\n });\n return found\n },\n getAllMarks: function() {\n var markers = [];\n this.iter(function (line) {\n var sps = line.markedSpans;\n if (sps) { for (var i = 0; i < sps.length; ++i)\n { if (sps[i].from != null) { markers.push(sps[i].marker); } } }\n });\n return markers\n },\n\n posFromIndex: function(off) {\n var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;\n this.iter(function (line) {\n var sz = line.text.length + sepSize;\n if (sz > off) { ch = off; return true }\n off -= sz;\n ++lineNo$$1;\n });\n return clipPos(this, Pos(lineNo$$1, ch))\n },\n indexFromPos: function (coords) {\n coords = clipPos(this, coords);\n var index = coords.ch;\n if (coords.line < this.first || coords.ch < 0) { return 0 }\n var sepSize = this.lineSeparator().length;\n this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value\n index += line.text.length + sepSize;\n });\n return index\n },\n\n copy: function(copyHistory) {\n var doc = new Doc(getLines(this, this.first, this.first + this.size),\n this.modeOption, this.first, this.lineSep, this.direction);\n doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;\n doc.sel = this.sel;\n doc.extend = false;\n if (copyHistory) {\n doc.history.undoDepth = this.history.undoDepth;\n doc.setHistory(this.getHistory());\n }\n return doc\n },\n\n linkedDoc: function(options) {\n if (!options) { options = {}; }\n var from = this.first, to = this.first + this.size;\n if (options.from != null && options.from > from) { from = options.from; }\n if (options.to != null && options.to < to) { to = options.to; }\n var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);\n if (options.sharedHist) { copy.history = this.history\n ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});\n copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];\n copySharedMarkers(copy, findSharedMarkers(this));\n return copy\n },\n unlinkDoc: function(other) {\n var this$1 = this;\n\n if (other instanceof CodeMirror) { other = other.doc; }\n if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {\n var link = this$1.linked[i];\n if (link.doc != other) { continue }\n this$1.linked.splice(i, 1);\n other.unlinkDoc(this$1);\n detachSharedMarkers(findSharedMarkers(this$1));\n break\n } }\n // If the histories were shared, split them again\n if (other.history == this.history) {\n var splitIds = [other.id];\n linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);\n other.history = new History(null);\n other.history.done = copyHistoryArray(this.history.done, splitIds);\n other.history.undone = copyHistoryArray(this.history.undone, splitIds);\n }\n },\n iterLinkedDocs: function(f) {linkedDocs(this, f);},\n\n getMode: function() {return this.mode},\n getEditor: function() {return this.cm},\n\n splitLines: function(str) {\n if (this.lineSep) { return str.split(this.lineSep) }\n return splitLinesAuto(str)\n },\n lineSeparator: function() { return this.lineSep || \"\\n\" },\n\n setDirection: docMethodOp(function (dir) {\n if (dir != \"rtl\") { dir = \"ltr\"; }\n if (dir == this.direction) { return }\n this.direction = dir;\n this.iter(function (line) { return line.order = null; });\n if (this.cm) { directionChanged(this.cm); }\n })\n });\n\n // Public alias.\n Doc.prototype.eachLine = Doc.prototype.iter;\n\n // Kludge to work around strange IE behavior where it'll sometimes\n // re-fire a series of drag-related events right after the drop (#1551)\n var lastDrop = 0;\n\n function onDrop(e) {\n var cm = this;\n clearDragCursor(cm);\n if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))\n { return }\n e_preventDefault(e);\n if (ie) { lastDrop = +new Date; }\n var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;\n if (!pos || cm.isReadOnly()) { return }\n // Might be a file drop, in which case we simply extract the text\n // and insert it.\n if (files && files.length && window.FileReader && window.File) {\n var n = files.length, text = Array(n), read = 0;\n var loadFile = function (file, i) {\n if (cm.options.allowDropFileTypes &&\n indexOf(cm.options.allowDropFileTypes, file.type) == -1)\n { return }\n\n var reader = new FileReader;\n reader.onload = operation(cm, function () {\n var content = reader.result;\n if (/[\\x00-\\x08\\x0e-\\x1f]{2}/.test(content)) { content = \"\"; }\n text[i] = content;\n if (++read == n) {\n pos = clipPos(cm.doc, pos);\n var change = {from: pos, to: pos,\n text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),\n origin: \"paste\"};\n makeChange(cm.doc, change);\n setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));\n }\n });\n reader.readAsText(file);\n };\n for (var i = 0; i < n; ++i) { loadFile(files[i], i); }\n } else { // Normal drop\n // Don't do a replace if the drop happened inside of the selected text.\n if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {\n cm.state.draggingText(e);\n // Ensure the editor is re-focused\n setTimeout(function () { return cm.display.input.focus(); }, 20);\n return\n }\n try {\n var text$1 = e.dataTransfer.getData(\"Text\");\n if (text$1) {\n var selected;\n if (cm.state.draggingText && !cm.state.draggingText.copy)\n { selected = cm.listSelections(); }\n setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));\n if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)\n { replaceRange(cm.doc, \"\", selected[i$1].anchor, selected[i$1].head, \"drag\"); } }\n cm.replaceSelection(text$1, \"around\", \"paste\");\n cm.display.input.focus();\n }\n }\n catch(e){}\n }\n }\n\n function onDragStart(cm, e) {\n if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }\n if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }\n\n e.dataTransfer.setData(\"Text\", cm.getSelection());\n e.dataTransfer.effectAllowed = \"copyMove\";\n\n // Use dummy image instead of default browsers image.\n // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.\n if (e.dataTransfer.setDragImage && !safari) {\n var img = elt(\"img\", null, null, \"position: fixed; left: 0; top: 0;\");\n img.src = \"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\";\n if (presto) {\n img.width = img.height = 1;\n cm.display.wrapper.appendChild(img);\n // Force a relayout, or Opera won't use our image for some obscure reason\n img._top = img.offsetTop;\n }\n e.dataTransfer.setDragImage(img, 0, 0);\n if (presto) { img.parentNode.removeChild(img); }\n }\n }\n\n function onDragOver(cm, e) {\n var pos = posFromMouse(cm, e);\n if (!pos) { return }\n var frag = document.createDocumentFragment();\n drawSelectionCursor(cm, pos, frag);\n if (!cm.display.dragCursor) {\n cm.display.dragCursor = elt(\"div\", null, \"CodeMirror-cursors CodeMirror-dragcursors\");\n cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);\n }\n removeChildrenAndAdd(cm.display.dragCursor, frag);\n }\n\n function clearDragCursor(cm) {\n if (cm.display.dragCursor) {\n cm.display.lineSpace.removeChild(cm.display.dragCursor);\n cm.display.dragCursor = null;\n }\n }\n\n // These must be handled carefully, because naively registering a\n // handler for each editor will cause the editors to never be\n // garbage collected.\n\n function forEachCodeMirror(f) {\n if (!document.getElementsByClassName) { return }\n var byClass = document.getElementsByClassName(\"CodeMirror\"), editors = [];\n for (var i = 0; i < byClass.length; i++) {\n var cm = byClass[i].CodeMirror;\n if (cm) { editors.push(cm); }\n }\n if (editors.length) { editors[0].operation(function () {\n for (var i = 0; i < editors.length; i++) { f(editors[i]); }\n }); }\n }\n\n var globalsRegistered = false;\n function ensureGlobalHandlers() {\n if (globalsRegistered) { return }\n registerGlobalHandlers();\n globalsRegistered = true;\n }\n function registerGlobalHandlers() {\n // When the window resizes, we need to refresh active editors.\n var resizeTimer;\n on(window, \"resize\", function () {\n if (resizeTimer == null) { resizeTimer = setTimeout(function () {\n resizeTimer = null;\n forEachCodeMirror(onResize);\n }, 100); }\n });\n // When the window loses focus, we want to show the editor as blurred\n on(window, \"blur\", function () { return forEachCodeMirror(onBlur); });\n }\n // Called when the window resizes\n function onResize(cm) {\n var d = cm.display;\n // Might be a text scaling operation, clear size caches.\n d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n d.scrollbarsClipped = false;\n cm.setSize();\n }\n\n var keyNames = {\n 3: \"Pause\", 8: \"Backspace\", 9: \"Tab\", 13: \"Enter\", 16: \"Shift\", 17: \"Ctrl\", 18: \"Alt\",\n 19: \"Pause\", 20: \"CapsLock\", 27: \"Esc\", 32: \"Space\", 33: \"PageUp\", 34: \"PageDown\", 35: \"End\",\n 36: \"Home\", 37: \"Left\", 38: \"Up\", 39: \"Right\", 40: \"Down\", 44: \"PrintScrn\", 45: \"Insert\",\n 46: \"Delete\", 59: \";\", 61: \"=\", 91: \"Mod\", 92: \"Mod\", 93: \"Mod\",\n 106: \"*\", 107: \"=\", 109: \"-\", 110: \".\", 111: \"/\", 127: \"Delete\", 145: \"ScrollLock\",\n 173: \"-\", 186: \";\", 187: \"=\", 188: \",\", 189: \"-\", 190: \".\", 191: \"/\", 192: \"`\", 219: \"[\", 220: \"\\\\\",\n 221: \"]\", 222: \"'\", 63232: \"Up\", 63233: \"Down\", 63234: \"Left\", 63235: \"Right\", 63272: \"Delete\",\n 63273: \"Home\", 63275: \"End\", 63276: \"PageUp\", 63277: \"PageDown\", 63302: \"Insert\"\n };\n\n // Number keys\n for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }\n // Alphabetic keys\n for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }\n // Function keys\n for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = \"F\" + i$2; }\n\n var keyMap = {};\n\n keyMap.basic = {\n \"Left\": \"goCharLeft\", \"Right\": \"goCharRight\", \"Up\": \"goLineUp\", \"Down\": \"goLineDown\",\n \"End\": \"goLineEnd\", \"Home\": \"goLineStartSmart\", \"PageUp\": \"goPageUp\", \"PageDown\": \"goPageDown\",\n \"Delete\": \"delCharAfter\", \"Backspace\": \"delCharBefore\", \"Shift-Backspace\": \"delCharBefore\",\n \"Tab\": \"defaultTab\", \"Shift-Tab\": \"indentAuto\",\n \"Enter\": \"newlineAndIndent\", \"Insert\": \"toggleOverwrite\",\n \"Esc\": \"singleSelection\"\n };\n // Note that the save and find-related commands aren't defined by\n // default. User code or addons can define them. Unknown commands\n // are simply ignored.\n keyMap.pcDefault = {\n \"Ctrl-A\": \"selectAll\", \"Ctrl-D\": \"deleteLine\", \"Ctrl-Z\": \"undo\", \"Shift-Ctrl-Z\": \"redo\", \"Ctrl-Y\": \"redo\",\n \"Ctrl-Home\": \"goDocStart\", \"Ctrl-End\": \"goDocEnd\", \"Ctrl-Up\": \"goLineUp\", \"Ctrl-Down\": \"goLineDown\",\n \"Ctrl-Left\": \"goGroupLeft\", \"Ctrl-Right\": \"goGroupRight\", \"Alt-Left\": \"goLineStart\", \"Alt-Right\": \"goLineEnd\",\n \"Ctrl-Backspace\": \"delGroupBefore\", \"Ctrl-Delete\": \"delGroupAfter\", \"Ctrl-S\": \"save\", \"Ctrl-F\": \"find\",\n \"Ctrl-G\": \"findNext\", \"Shift-Ctrl-G\": \"findPrev\", \"Shift-Ctrl-F\": \"replace\", \"Shift-Ctrl-R\": \"replaceAll\",\n \"Ctrl-[\": \"indentLess\", \"Ctrl-]\": \"indentMore\",\n \"Ctrl-U\": \"undoSelection\", \"Shift-Ctrl-U\": \"redoSelection\", \"Alt-U\": \"redoSelection\",\n \"fallthrough\": \"basic\"\n };\n // Very basic readline/emacs-style bindings, which are standard on Mac.\n keyMap.emacsy = {\n \"Ctrl-F\": \"goCharRight\", \"Ctrl-B\": \"goCharLeft\", \"Ctrl-P\": \"goLineUp\", \"Ctrl-N\": \"goLineDown\",\n \"Alt-F\": \"goWordRight\", \"Alt-B\": \"goWordLeft\", \"Ctrl-A\": \"goLineStart\", \"Ctrl-E\": \"goLineEnd\",\n \"Ctrl-V\": \"goPageDown\", \"Shift-Ctrl-V\": \"goPageUp\", \"Ctrl-D\": \"delCharAfter\", \"Ctrl-H\": \"delCharBefore\",\n \"Alt-D\": \"delWordAfter\", \"Alt-Backspace\": \"delWordBefore\", \"Ctrl-K\": \"killLine\", \"Ctrl-T\": \"transposeChars\",\n \"Ctrl-O\": \"openLine\"\n };\n keyMap.macDefault = {\n \"Cmd-A\": \"selectAll\", \"Cmd-D\": \"deleteLine\", \"Cmd-Z\": \"undo\", \"Shift-Cmd-Z\": \"redo\", \"Cmd-Y\": \"redo\",\n \"Cmd-Home\": \"goDocStart\", \"Cmd-Up\": \"goDocStart\", \"Cmd-End\": \"goDocEnd\", \"Cmd-Down\": \"goDocEnd\", \"Alt-Left\": \"goGroupLeft\",\n \"Alt-Right\": \"goGroupRight\", \"Cmd-Left\": \"goLineLeft\", \"Cmd-Right\": \"goLineRight\", \"Alt-Backspace\": \"delGroupBefore\",\n \"Ctrl-Alt-Backspace\": \"delGroupAfter\", \"Alt-Delete\": \"delGroupAfter\", \"Cmd-S\": \"save\", \"Cmd-F\": \"find\",\n \"Cmd-G\": \"findNext\", \"Shift-Cmd-G\": \"findPrev\", \"Cmd-Alt-F\": \"replace\", \"Shift-Cmd-Alt-F\": \"replaceAll\",\n \"Cmd-[\": \"indentLess\", \"Cmd-]\": \"indentMore\", \"Cmd-Backspace\": \"delWrappedLineLeft\", \"Cmd-Delete\": \"delWrappedLineRight\",\n \"Cmd-U\": \"undoSelection\", \"Shift-Cmd-U\": \"redoSelection\", \"Ctrl-Up\": \"goDocStart\", \"Ctrl-Down\": \"goDocEnd\",\n \"fallthrough\": [\"basic\", \"emacsy\"]\n };\n keyMap[\"default\"] = mac ? keyMap.macDefault : keyMap.pcDefault;\n\n // KEYMAP DISPATCH\n\n function normalizeKeyName(name) {\n var parts = name.split(/-(?!$)/);\n name = parts[parts.length - 1];\n var alt, ctrl, shift, cmd;\n for (var i = 0; i < parts.length - 1; i++) {\n var mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }\n else if (/^a(lt)?$/i.test(mod)) { alt = true; }\n else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }\n else if (/^s(hift)?$/i.test(mod)) { shift = true; }\n else { throw new Error(\"Unrecognized modifier name: \" + mod) }\n }\n if (alt) { name = \"Alt-\" + name; }\n if (ctrl) { name = \"Ctrl-\" + name; }\n if (cmd) { name = \"Cmd-\" + name; }\n if (shift) { name = \"Shift-\" + name; }\n return name\n }\n\n // This is a kludge to keep keymaps mostly working as raw objects\n // (backwards compatibility) while at the same time support features\n // like normalization and multi-stroke key bindings. It compiles a\n // new normalized keymap, and then updates the old object to reflect\n // this.\n function normalizeKeyMap(keymap) {\n var copy = {};\n for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {\n var value = keymap[keyname];\n if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }\n if (value == \"...\") { delete keymap[keyname]; continue }\n\n var keys = map(keyname.split(\" \"), normalizeKeyName);\n for (var i = 0; i < keys.length; i++) {\n var val = (void 0), name = (void 0);\n if (i == keys.length - 1) {\n name = keys.join(\" \");\n val = value;\n } else {\n name = keys.slice(0, i + 1).join(\" \");\n val = \"...\";\n }\n var prev = copy[name];\n if (!prev) { copy[name] = val; }\n else if (prev != val) { throw new Error(\"Inconsistent bindings for \" + name) }\n }\n delete keymap[keyname];\n } }\n for (var prop in copy) { keymap[prop] = copy[prop]; }\n return keymap\n }\n\n function lookupKey(key, map$$1, handle, context) {\n map$$1 = getKeyMap(map$$1);\n var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];\n if (found === false) { return \"nothing\" }\n if (found === \"...\") { return \"multi\" }\n if (found != null && handle(found)) { return \"handled\" }\n\n if (map$$1.fallthrough) {\n if (Object.prototype.toString.call(map$$1.fallthrough) != \"[object Array]\")\n { return lookupKey(key, map$$1.fallthrough, handle, context) }\n for (var i = 0; i < map$$1.fallthrough.length; i++) {\n var result = lookupKey(key, map$$1.fallthrough[i], handle, context);\n if (result) { return result }\n }\n }\n }\n\n // Modifier key presses don't count as 'real' key presses for the\n // purpose of keymap fallthrough.\n function isModifierKey(value) {\n var name = typeof value == \"string\" ? value : keyNames[value.keyCode];\n return name == \"Ctrl\" || name == \"Alt\" || name == \"Shift\" || name == \"Mod\"\n }\n\n function addModifierNames(name, event, noShift) {\n var base = name;\n if (event.altKey && base != \"Alt\") { name = \"Alt-\" + name; }\n if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != \"Ctrl\") { name = \"Ctrl-\" + name; }\n if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != \"Cmd\") { name = \"Cmd-\" + name; }\n if (!noShift && event.shiftKey && base != \"Shift\") { name = \"Shift-\" + name; }\n return name\n }\n\n // Look up the name of a key as indicated by an event object.\n function keyName(event, noShift) {\n if (presto && event.keyCode == 34 && event[\"char\"]) { return false }\n var name = keyNames[event.keyCode];\n if (name == null || event.altGraphKey) { return false }\n // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,\n // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)\n if (event.keyCode == 3 && event.code) { name = event.code; }\n return addModifierNames(name, event, noShift)\n }\n\n function getKeyMap(val) {\n return typeof val == \"string\" ? keyMap[val] : val\n }\n\n // Helper for deleting text near the selection(s), used to implement\n // backspace, delete, and similar functionality.\n function deleteNearSelection(cm, compute) {\n var ranges = cm.doc.sel.ranges, kill = [];\n // Build up a set of ranges to kill first, merging overlapping\n // ranges.\n for (var i = 0; i < ranges.length; i++) {\n var toKill = compute(ranges[i]);\n while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {\n var replaced = kill.pop();\n if (cmp(replaced.from, toKill.from) < 0) {\n toKill.from = replaced.from;\n break\n }\n }\n kill.push(toKill);\n }\n // Next, remove those actual ranges.\n runInOp(cm, function () {\n for (var i = kill.length - 1; i >= 0; i--)\n { replaceRange(cm.doc, \"\", kill[i].from, kill[i].to, \"+delete\"); }\n ensureCursorVisible(cm);\n });\n }\n\n function moveCharLogically(line, ch, dir) {\n var target = skipExtendingChars(line.text, ch + dir, dir);\n return target < 0 || target > line.text.length ? null : target\n }\n\n function moveLogically(line, start, dir) {\n var ch = moveCharLogically(line, start.ch, dir);\n return ch == null ? null : new Pos(start.line, ch, dir < 0 ? \"after\" : \"before\")\n }\n\n function endOfLine(visually, cm, lineObj, lineNo, dir) {\n if (visually) {\n var order = getOrder(lineObj, cm.doc.direction);\n if (order) {\n var part = dir < 0 ? lst(order) : order[0];\n var moveInStorageOrder = (dir < 0) == (part.level == 1);\n var sticky = moveInStorageOrder ? \"after\" : \"before\";\n var ch;\n // With a wrapped rtl chunk (possibly spanning multiple bidi parts),\n // it could be that the last bidi part is not on the last visual line,\n // since visual lines contain content order-consecutive chunks.\n // Thus, in rtl, we are looking for the first (content-order) character\n // in the rtl chunk that is on the last line (that is, the same line\n // as the last (content-order) character).\n if (part.level > 0 || cm.doc.direction == \"rtl\") {\n var prep = prepareMeasureForLine(cm, lineObj);\n ch = dir < 0 ? lineObj.text.length - 1 : 0;\n var targetTop = measureCharPrepared(cm, prep, ch).top;\n ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);\n if (sticky == \"before\") { ch = moveCharLogically(lineObj, ch, 1); }\n } else { ch = dir < 0 ? part.to : part.from; }\n return new Pos(lineNo, ch, sticky)\n }\n }\n return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? \"before\" : \"after\")\n }\n\n function moveVisually(cm, line, start, dir) {\n var bidi = getOrder(line, cm.doc.direction);\n if (!bidi) { return moveLogically(line, start, dir) }\n if (start.ch >= line.text.length) {\n start.ch = line.text.length;\n start.sticky = \"before\";\n } else if (start.ch <= 0) {\n start.ch = 0;\n start.sticky = \"after\";\n }\n var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];\n if (cm.doc.direction == \"ltr\" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {\n // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,\n // nothing interesting happens.\n return moveLogically(line, start, dir)\n }\n\n var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };\n var prep;\n var getWrappedLineExtent = function (ch) {\n if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }\n prep = prep || prepareMeasureForLine(cm, line);\n return wrappedLineExtentChar(cm, line, prep, ch)\n };\n var wrappedLineExtent = getWrappedLineExtent(start.sticky == \"before\" ? mv(start, -1) : start.ch);\n\n if (cm.doc.direction == \"rtl\" || part.level == 1) {\n var moveInStorageOrder = (part.level == 1) == (dir < 0);\n var ch = mv(start, moveInStorageOrder ? 1 : -1);\n if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {\n // Case 2: We move within an rtl part or in an rtl editor on the same visual line\n var sticky = moveInStorageOrder ? \"before\" : \"after\";\n return new Pos(start.line, ch, sticky)\n }\n }\n\n // Case 3: Could not move within this bidi part in this visual line, so leave\n // the current bidi part\n\n var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {\n var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder\n ? new Pos(start.line, mv(ch, 1), \"before\")\n : new Pos(start.line, ch, \"after\"); };\n\n for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {\n var part = bidi[partPos];\n var moveInStorageOrder = (dir > 0) == (part.level != 1);\n var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);\n if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }\n ch = moveInStorageOrder ? part.from : mv(part.to, -1);\n if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }\n }\n };\n\n // Case 3a: Look for other bidi parts on the same visual line\n var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);\n if (res) { return res }\n\n // Case 3b: Look for other bidi parts on the next visual line\n var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);\n if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {\n res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));\n if (res) { return res }\n }\n\n // Case 4: Nowhere to move\n return null\n }\n\n // Commands are parameter-less actions that can be performed on an\n // editor, mostly used for keybindings.\n var commands = {\n selectAll: selectAll,\n singleSelection: function (cm) { return cm.setSelection(cm.getCursor(\"anchor\"), cm.getCursor(\"head\"), sel_dontScroll); },\n killLine: function (cm) { return deleteNearSelection(cm, function (range) {\n if (range.empty()) {\n var len = getLine(cm.doc, range.head.line).text.length;\n if (range.head.ch == len && range.head.line < cm.lastLine())\n { return {from: range.head, to: Pos(range.head.line + 1, 0)} }\n else\n { return {from: range.head, to: Pos(range.head.line, len)} }\n } else {\n return {from: range.from(), to: range.to()}\n }\n }); },\n deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({\n from: Pos(range.from().line, 0),\n to: clipPos(cm.doc, Pos(range.to().line + 1, 0))\n }); }); },\n delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({\n from: Pos(range.from().line, 0), to: range.from()\n }); }); },\n delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {\n var top = cm.charCoords(range.head, \"div\").top + 5;\n var leftPos = cm.coordsChar({left: 0, top: top}, \"div\");\n return {from: leftPos, to: range.from()}\n }); },\n delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {\n var top = cm.charCoords(range.head, \"div\").top + 5;\n var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\");\n return {from: range.from(), to: rightPos }\n }); },\n undo: function (cm) { return cm.undo(); },\n redo: function (cm) { return cm.redo(); },\n undoSelection: function (cm) { return cm.undoSelection(); },\n redoSelection: function (cm) { return cm.redoSelection(); },\n goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },\n goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },\n goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },\n {origin: \"+move\", bias: 1}\n ); },\n goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },\n {origin: \"+move\", bias: 1}\n ); },\n goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },\n {origin: \"+move\", bias: -1}\n ); },\n goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {\n var top = cm.cursorCoords(range.head, \"div\").top + 5;\n return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\")\n }, sel_move); },\n goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {\n var top = cm.cursorCoords(range.head, \"div\").top + 5;\n return cm.coordsChar({left: 0, top: top}, \"div\")\n }, sel_move); },\n goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {\n var top = cm.cursorCoords(range.head, \"div\").top + 5;\n var pos = cm.coordsChar({left: 0, top: top}, \"div\");\n if (pos.ch < cm.getLine(pos.line).search(/\\S/)) { return lineStartSmart(cm, range.head) }\n return pos\n }, sel_move); },\n goLineUp: function (cm) { return cm.moveV(-1, \"line\"); },\n goLineDown: function (cm) { return cm.moveV(1, \"line\"); },\n goPageUp: function (cm) { return cm.moveV(-1, \"page\"); },\n goPageDown: function (cm) { return cm.moveV(1, \"page\"); },\n goCharLeft: function (cm) { return cm.moveH(-1, \"char\"); },\n goCharRight: function (cm) { return cm.moveH(1, \"char\"); },\n goColumnLeft: function (cm) { return cm.moveH(-1, \"column\"); },\n goColumnRight: function (cm) { return cm.moveH(1, \"column\"); },\n goWordLeft: function (cm) { return cm.moveH(-1, \"word\"); },\n goGroupRight: function (cm) { return cm.moveH(1, \"group\"); },\n goGroupLeft: function (cm) { return cm.moveH(-1, \"group\"); },\n goWordRight: function (cm) { return cm.moveH(1, \"word\"); },\n delCharBefore: function (cm) { return cm.deleteH(-1, \"char\"); },\n delCharAfter: function (cm) { return cm.deleteH(1, \"char\"); },\n delWordBefore: function (cm) { return cm.deleteH(-1, \"word\"); },\n delWordAfter: function (cm) { return cm.deleteH(1, \"word\"); },\n delGroupBefore: function (cm) { return cm.deleteH(-1, \"group\"); },\n delGroupAfter: function (cm) { return cm.deleteH(1, \"group\"); },\n indentAuto: function (cm) { return cm.indentSelection(\"smart\"); },\n indentMore: function (cm) { return cm.indentSelection(\"add\"); },\n indentLess: function (cm) { return cm.indentSelection(\"subtract\"); },\n insertTab: function (cm) { return cm.replaceSelection(\"\\t\"); },\n insertSoftTab: function (cm) {\n var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;\n for (var i = 0; i < ranges.length; i++) {\n var pos = ranges[i].from();\n var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);\n spaces.push(spaceStr(tabSize - col % tabSize));\n }\n cm.replaceSelections(spaces);\n },\n defaultTab: function (cm) {\n if (cm.somethingSelected()) { cm.indentSelection(\"add\"); }\n else { cm.execCommand(\"insertTab\"); }\n },\n // Swap the two chars left and right of each selection's head.\n // Move cursor behind the two swapped characters afterwards.\n //\n // Doesn't consider line feeds a character.\n // Doesn't scan more than one line above to find a character.\n // Doesn't do anything on an empty line.\n // Doesn't do anything with non-empty selections.\n transposeChars: function (cm) { return runInOp(cm, function () {\n var ranges = cm.listSelections(), newSel = [];\n for (var i = 0; i < ranges.length; i++) {\n if (!ranges[i].empty()) { continue }\n var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;\n if (line) {\n if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }\n if (cur.ch > 0) {\n cur = new Pos(cur.line, cur.ch + 1);\n cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),\n Pos(cur.line, cur.ch - 2), cur, \"+transpose\");\n } else if (cur.line > cm.doc.first) {\n var prev = getLine(cm.doc, cur.line - 1).text;\n if (prev) {\n cur = new Pos(cur.line, 1);\n cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +\n prev.charAt(prev.length - 1),\n Pos(cur.line - 1, prev.length - 1), cur, \"+transpose\");\n }\n }\n }\n newSel.push(new Range(cur, cur));\n }\n cm.setSelections(newSel);\n }); },\n newlineAndIndent: function (cm) { return runInOp(cm, function () {\n var sels = cm.listSelections();\n for (var i = sels.length - 1; i >= 0; i--)\n { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, \"+input\"); }\n sels = cm.listSelections();\n for (var i$1 = 0; i$1 < sels.length; i$1++)\n { cm.indentLine(sels[i$1].from().line, null, true); }\n ensureCursorVisible(cm);\n }); },\n openLine: function (cm) { return cm.replaceSelection(\"\\n\", \"start\"); },\n toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }\n };\n\n\n function lineStart(cm, lineN) {\n var line = getLine(cm.doc, lineN);\n var visual = visualLine(line);\n if (visual != line) { lineN = lineNo(visual); }\n return endOfLine(true, cm, visual, lineN, 1)\n }\n function lineEnd(cm, lineN) {\n var line = getLine(cm.doc, lineN);\n var visual = visualLineEnd(line);\n if (visual != line) { lineN = lineNo(visual); }\n return endOfLine(true, cm, line, lineN, -1)\n }\n function lineStartSmart(cm, pos) {\n var start = lineStart(cm, pos.line);\n var line = getLine(cm.doc, start.line);\n var order = getOrder(line, cm.doc.direction);\n if (!order || order[0].level == 0) {\n var firstNonWS = Math.max(0, line.text.search(/\\S/));\n var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;\n return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)\n }\n return start\n }\n\n // Run a handler that was bound to a key.\n function doHandleBinding(cm, bound, dropShift) {\n if (typeof bound == \"string\") {\n bound = commands[bound];\n if (!bound) { return false }\n }\n // Ensure previous input has been read, so that the handler sees a\n // consistent view of the document\n cm.display.input.ensurePolled();\n var prevShift = cm.display.shift, done = false;\n try {\n if (cm.isReadOnly()) { cm.state.suppressEdits = true; }\n if (dropShift) { cm.display.shift = false; }\n done = bound(cm) != Pass;\n } finally {\n cm.display.shift = prevShift;\n cm.state.suppressEdits = false;\n }\n return done\n }\n\n function lookupKeyForEditor(cm, name, handle) {\n for (var i = 0; i < cm.state.keyMaps.length; i++) {\n var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);\n if (result) { return result }\n }\n return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))\n || lookupKey(name, cm.options.keyMap, handle, cm)\n }\n\n // Note that, despite the name, this function is also used to check\n // for bound mouse clicks.\n\n var stopSeq = new Delayed;\n\n function dispatchKey(cm, name, e, handle) {\n var seq = cm.state.keySeq;\n if (seq) {\n if (isModifierKey(name)) { return \"handled\" }\n if (/\\'$/.test(name))\n { cm.state.keySeq = null; }\n else\n { stopSeq.set(50, function () {\n if (cm.state.keySeq == seq) {\n cm.state.keySeq = null;\n cm.display.input.reset();\n }\n }); }\n if (dispatchKeyInner(cm, seq + \" \" + name, e, handle)) { return true }\n }\n return dispatchKeyInner(cm, name, e, handle)\n }\n\n function dispatchKeyInner(cm, name, e, handle) {\n var result = lookupKeyForEditor(cm, name, handle);\n\n if (result == \"multi\")\n { cm.state.keySeq = name; }\n if (result == \"handled\")\n { signalLater(cm, \"keyHandled\", cm, name, e); }\n\n if (result == \"handled\" || result == \"multi\") {\n e_preventDefault(e);\n restartBlink(cm);\n }\n\n return !!result\n }\n\n // Handle a key from the keydown event.\n function handleKeyBinding(cm, e) {\n var name = keyName(e, true);\n if (!name) { return false }\n\n if (e.shiftKey && !cm.state.keySeq) {\n // First try to resolve full name (including 'Shift-'). Failing\n // that, see if there is a cursor-motion command (starting with\n // 'go') bound to the keyname without 'Shift-'.\n return dispatchKey(cm, \"Shift-\" + name, e, function (b) { return doHandleBinding(cm, b, true); })\n || dispatchKey(cm, name, e, function (b) {\n if (typeof b == \"string\" ? /^go[A-Z]/.test(b) : b.motion)\n { return doHandleBinding(cm, b) }\n })\n } else {\n return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })\n }\n }\n\n // Handle a key from the keypress event\n function handleCharBinding(cm, e, ch) {\n return dispatchKey(cm, \"'\" + ch + \"'\", e, function (b) { return doHandleBinding(cm, b, true); })\n }\n\n var lastStoppedKey = null;\n function onKeyDown(e) {\n var cm = this;\n cm.curOp.focus = activeElt();\n if (signalDOMEvent(cm, e)) { return }\n // IE does strange things with escape.\n if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }\n var code = e.keyCode;\n cm.display.shift = code == 16 || e.shiftKey;\n var handled = handleKeyBinding(cm, e);\n if (presto) {\n lastStoppedKey = handled ? code : null;\n // Opera has no cut event... we try to at least catch the key combo\n if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))\n { cm.replaceSelection(\"\", null, \"cut\"); }\n }\n\n // Turn mouse into crosshair when Alt is held on Mac.\n if (code == 18 && !/\\bCodeMirror-crosshair\\b/.test(cm.display.lineDiv.className))\n { showCrossHair(cm); }\n }\n\n function showCrossHair(cm) {\n var lineDiv = cm.display.lineDiv;\n addClass(lineDiv, \"CodeMirror-crosshair\");\n\n function up(e) {\n if (e.keyCode == 18 || !e.altKey) {\n rmClass(lineDiv, \"CodeMirror-crosshair\");\n off(document, \"keyup\", up);\n off(document, \"mouseover\", up);\n }\n }\n on(document, \"keyup\", up);\n on(document, \"mouseover\", up);\n }\n\n function onKeyUp(e) {\n if (e.keyCode == 16) { this.doc.sel.shift = false; }\n signalDOMEvent(this, e);\n }\n\n function onKeyPress(e) {\n var cm = this;\n if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }\n var keyCode = e.keyCode, charCode = e.charCode;\n if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}\n if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }\n var ch = String.fromCharCode(charCode == null ? keyCode : charCode);\n // Some browsers fire keypress events for backspace\n if (ch == \"\\x08\") { return }\n if (handleCharBinding(cm, e, ch)) { return }\n cm.display.input.onKeyPress(e);\n }\n\n var DOUBLECLICK_DELAY = 400;\n\n var PastClick = function(time, pos, button) {\n this.time = time;\n this.pos = pos;\n this.button = button;\n };\n\n PastClick.prototype.compare = function (time, pos, button) {\n return this.time + DOUBLECLICK_DELAY > time &&\n cmp(pos, this.pos) == 0 && button == this.button\n };\n\n var lastClick, lastDoubleClick;\n function clickRepeat(pos, button) {\n var now = +new Date;\n if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {\n lastClick = lastDoubleClick = null;\n return \"triple\"\n } else if (lastClick && lastClick.compare(now, pos, button)) {\n lastDoubleClick = new PastClick(now, pos, button);\n lastClick = null;\n return \"double\"\n } else {\n lastClick = new PastClick(now, pos, button);\n lastDoubleClick = null;\n return \"single\"\n }\n }\n\n // A mouse down can be a single click, double click, triple click,\n // start of selection drag, start of text drag, new cursor\n // (ctrl-click), rectangle drag (alt-drag), or xwin\n // middle-click-paste. Or it might be a click on something we should\n // not interfere with, such as a scrollbar or widget.\n function onMouseDown(e) {\n var cm = this, display = cm.display;\n if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }\n display.input.ensurePolled();\n display.shift = e.shiftKey;\n\n if (eventInWidget(display, e)) {\n if (!webkit) {\n // Briefly turn off draggability, to allow widgets to do\n // normal dragging things.\n display.scroller.draggable = false;\n setTimeout(function () { return display.scroller.draggable = true; }, 100);\n }\n return\n }\n if (clickInGutter(cm, e)) { return }\n var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : \"single\";\n window.focus();\n\n // #3261: make sure, that we're not starting a second selection\n if (button == 1 && cm.state.selectingText)\n { cm.state.selectingText(e); }\n\n if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }\n\n if (button == 1) {\n if (pos) { leftButtonDown(cm, pos, repeat, e); }\n else if (e_target(e) == display.scroller) { e_preventDefault(e); }\n } else if (button == 2) {\n if (pos) { extendSelection(cm.doc, pos); }\n setTimeout(function () { return display.input.focus(); }, 20);\n } else if (button == 3) {\n if (captureRightClick) { cm.display.input.onContextMenu(e); }\n else { delayBlurEvent(cm); }\n }\n }\n\n function handleMappedButton(cm, button, pos, repeat, event) {\n var name = \"Click\";\n if (repeat == \"double\") { name = \"Double\" + name; }\n else if (repeat == \"triple\") { name = \"Triple\" + name; }\n name = (button == 1 ? \"Left\" : button == 2 ? \"Middle\" : \"Right\") + name;\n\n return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {\n if (typeof bound == \"string\") { bound = commands[bound]; }\n if (!bound) { return false }\n var done = false;\n try {\n if (cm.isReadOnly()) { cm.state.suppressEdits = true; }\n done = bound(cm, pos) != Pass;\n } finally {\n cm.state.suppressEdits = false;\n }\n return done\n })\n }\n\n function configureMouse(cm, repeat, event) {\n var option = cm.getOption(\"configureMouse\");\n var value = option ? option(cm, repeat, event) : {};\n if (value.unit == null) {\n var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;\n value.unit = rect ? \"rectangle\" : repeat == \"single\" ? \"char\" : repeat == \"double\" ? \"word\" : \"line\";\n }\n if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }\n if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }\n if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }\n return value\n }\n\n function leftButtonDown(cm, pos, repeat, event) {\n if (ie) { setTimeout(bind(ensureFocus, cm), 0); }\n else { cm.curOp.focus = activeElt(); }\n\n var behavior = configureMouse(cm, repeat, event);\n\n var sel = cm.doc.sel, contained;\n if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&\n repeat == \"single\" && (contained = sel.contains(pos)) > -1 &&\n (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&\n (cmp(contained.to(), pos) > 0 || pos.xRel < 0))\n { leftButtonStartDrag(cm, event, pos, behavior); }\n else\n { leftButtonSelect(cm, event, pos, behavior); }\n }\n\n // Start a text drag. When it ends, see if any dragging actually\n // happen, and treat as a click if it didn't.\n function leftButtonStartDrag(cm, event, pos, behavior) {\n var display = cm.display, moved = false;\n var dragEnd = operation(cm, function (e) {\n if (webkit) { display.scroller.draggable = false; }\n cm.state.draggingText = false;\n off(display.wrapper.ownerDocument, \"mouseup\", dragEnd);\n off(display.wrapper.ownerDocument, \"mousemove\", mouseMove);\n off(display.scroller, \"dragstart\", dragStart);\n off(display.scroller, \"drop\", dragEnd);\n if (!moved) {\n e_preventDefault(e);\n if (!behavior.addNew)\n { extendSelection(cm.doc, pos, null, null, behavior.extend); }\n // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)\n if (webkit || ie && ie_version == 9)\n { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }\n else\n { display.input.focus(); }\n }\n });\n var mouseMove = function(e2) {\n moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;\n };\n var dragStart = function () { return moved = true; };\n // Let the drag handler handle this.\n if (webkit) { display.scroller.draggable = true; }\n cm.state.draggingText = dragEnd;\n dragEnd.copy = !behavior.moveOnDrag;\n // IE's approach to draggable\n if (display.scroller.dragDrop) { display.scroller.dragDrop(); }\n on(display.wrapper.ownerDocument, \"mouseup\", dragEnd);\n on(display.wrapper.ownerDocument, \"mousemove\", mouseMove);\n on(display.scroller, \"dragstart\", dragStart);\n on(display.scroller, \"drop\", dragEnd);\n\n delayBlurEvent(cm);\n setTimeout(function () { return display.input.focus(); }, 20);\n }\n\n function rangeForUnit(cm, pos, unit) {\n if (unit == \"char\") { return new Range(pos, pos) }\n if (unit == \"word\") { return cm.findWordAt(pos) }\n if (unit == \"line\") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }\n var result = unit(cm, pos);\n return new Range(result.from, result.to)\n }\n\n // Normal selection, as opposed to text dragging.\n function leftButtonSelect(cm, event, start, behavior) {\n var display = cm.display, doc = cm.doc;\n e_preventDefault(event);\n\n var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;\n if (behavior.addNew && !behavior.extend) {\n ourIndex = doc.sel.contains(start);\n if (ourIndex > -1)\n { ourRange = ranges[ourIndex]; }\n else\n { ourRange = new Range(start, start); }\n } else {\n ourRange = doc.sel.primary();\n ourIndex = doc.sel.primIndex;\n }\n\n if (behavior.unit == \"rectangle\") {\n if (!behavior.addNew) { ourRange = new Range(start, start); }\n start = posFromMouse(cm, event, true, true);\n ourIndex = -1;\n } else {\n var range$$1 = rangeForUnit(cm, start, behavior.unit);\n if (behavior.extend)\n { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }\n else\n { ourRange = range$$1; }\n }\n\n if (!behavior.addNew) {\n ourIndex = 0;\n setSelection(doc, new Selection([ourRange], 0), sel_mouse);\n startSel = doc.sel;\n } else if (ourIndex == -1) {\n ourIndex = ranges.length;\n setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),\n {scroll: false, origin: \"*mouse\"});\n } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == \"char\" && !behavior.extend) {\n setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),\n {scroll: false, origin: \"*mouse\"});\n startSel = doc.sel;\n } else {\n replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);\n }\n\n var lastPos = start;\n function extendTo(pos) {\n if (cmp(lastPos, pos) == 0) { return }\n lastPos = pos;\n\n if (behavior.unit == \"rectangle\") {\n var ranges = [], tabSize = cm.options.tabSize;\n var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);\n var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);\n var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);\n for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));\n line <= end; line++) {\n var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);\n if (left == right)\n { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }\n else if (text.length > leftPos)\n { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }\n }\n if (!ranges.length) { ranges.push(new Range(start, start)); }\n setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),\n {origin: \"*mouse\", scroll: false});\n cm.scrollIntoView(pos);\n } else {\n var oldRange = ourRange;\n var range$$1 = rangeForUnit(cm, pos, behavior.unit);\n var anchor = oldRange.anchor, head;\n if (cmp(range$$1.anchor, anchor) > 0) {\n head = range$$1.head;\n anchor = minPos(oldRange.from(), range$$1.anchor);\n } else {\n head = range$$1.anchor;\n anchor = maxPos(oldRange.to(), range$$1.head);\n }\n var ranges$1 = startSel.ranges.slice(0);\n ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));\n setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);\n }\n }\n\n var editorSize = display.wrapper.getBoundingClientRect();\n // Used to ensure timeout re-tries don't fire when another extend\n // happened in the meantime (clearTimeout isn't reliable -- at\n // least on Chrome, the timeouts still happen even when cleared,\n // if the clear happens after their scheduled firing time).\n var counter = 0;\n\n function extend(e) {\n var curCount = ++counter;\n var cur = posFromMouse(cm, e, true, behavior.unit == \"rectangle\");\n if (!cur) { return }\n if (cmp(cur, lastPos) != 0) {\n cm.curOp.focus = activeElt();\n extendTo(cur);\n var visible = visibleLines(display, doc);\n if (cur.line >= visible.to || cur.line < visible.from)\n { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }\n } else {\n var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;\n if (outside) { setTimeout(operation(cm, function () {\n if (counter != curCount) { return }\n display.scroller.scrollTop += outside;\n extend(e);\n }), 50); }\n }\n }\n\n function done(e) {\n cm.state.selectingText = false;\n counter = Infinity;\n e_preventDefault(e);\n display.input.focus();\n off(display.wrapper.ownerDocument, \"mousemove\", move);\n off(display.wrapper.ownerDocument, \"mouseup\", up);\n doc.history.lastSelOrigin = null;\n }\n\n var move = operation(cm, function (e) {\n if (e.buttons === 0 || !e_button(e)) { done(e); }\n else { extend(e); }\n });\n var up = operation(cm, done);\n cm.state.selectingText = up;\n on(display.wrapper.ownerDocument, \"mousemove\", move);\n on(display.wrapper.ownerDocument, \"mouseup\", up);\n }\n\n // Used when mouse-selecting to adjust the anchor to the proper side\n // of a bidi jump depending on the visual position of the head.\n function bidiSimplify(cm, range$$1) {\n var anchor = range$$1.anchor;\n var head = range$$1.head;\n var anchorLine = getLine(cm.doc, anchor.line);\n if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }\n var order = getOrder(anchorLine);\n if (!order) { return range$$1 }\n var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];\n if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }\n var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);\n if (boundary == 0 || boundary == order.length) { return range$$1 }\n\n // Compute the relative visual position of the head compared to the\n // anchor (<0 is to the left, >0 to the right)\n var leftSide;\n if (head.line != anchor.line) {\n leftSide = (head.line - anchor.line) * (cm.doc.direction == \"ltr\" ? 1 : -1) > 0;\n } else {\n var headIndex = getBidiPartAt(order, head.ch, head.sticky);\n var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);\n if (headIndex == boundary - 1 || headIndex == boundary)\n { leftSide = dir < 0; }\n else\n { leftSide = dir > 0; }\n }\n\n var usePart = order[boundary + (leftSide ? -1 : 0)];\n var from = leftSide == (usePart.level == 1);\n var ch = from ? usePart.from : usePart.to, sticky = from ? \"after\" : \"before\";\n return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)\n }\n\n\n // Determines whether an event happened in the gutter, and fires the\n // handlers for the corresponding event.\n function gutterEvent(cm, e, type, prevent) {\n var mX, mY;\n if (e.touches) {\n mX = e.touches[0].clientX;\n mY = e.touches[0].clientY;\n } else {\n try { mX = e.clientX; mY = e.clientY; }\n catch(e) { return false }\n }\n if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }\n if (prevent) { e_preventDefault(e); }\n\n var display = cm.display;\n var lineBox = display.lineDiv.getBoundingClientRect();\n\n if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }\n mY -= lineBox.top - display.viewOffset;\n\n for (var i = 0; i < cm.options.gutters.length; ++i) {\n var g = display.gutters.childNodes[i];\n if (g && g.getBoundingClientRect().right >= mX) {\n var line = lineAtHeight(cm.doc, mY);\n var gutter = cm.options.gutters[i];\n signal(cm, type, cm, line, gutter, e);\n return e_defaultPrevented(e)\n }\n }\n }\n\n function clickInGutter(cm, e) {\n return gutterEvent(cm, e, \"gutterClick\", true)\n }\n\n // CONTEXT MENU HANDLING\n\n // To make the context menu work, we need to briefly unhide the\n // textarea (making it as unobtrusive as possible) to let the\n // right-click take effect on it.\n function onContextMenu(cm, e) {\n if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }\n if (signalDOMEvent(cm, e, \"contextmenu\")) { return }\n if (!captureRightClick) { cm.display.input.onContextMenu(e); }\n }\n\n function contextMenuInGutter(cm, e) {\n if (!hasHandler(cm, \"gutterContextMenu\")) { return false }\n return gutterEvent(cm, e, \"gutterContextMenu\", false)\n }\n\n function themeChanged(cm) {\n cm.display.wrapper.className = cm.display.wrapper.className.replace(/\\s*cm-s-\\S+/g, \"\") +\n cm.options.theme.replace(/(^|\\s)\\s*/g, \" cm-s-\");\n clearCaches(cm);\n }\n\n var Init = {toString: function(){return \"CodeMirror.Init\"}};\n\n var defaults = {};\n var optionHandlers = {};\n\n function defineOptions(CodeMirror) {\n var optionHandlers = CodeMirror.optionHandlers;\n\n function option(name, deflt, handle, notOnInit) {\n CodeMirror.defaults[name] = deflt;\n if (handle) { optionHandlers[name] =\n notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }\n }\n\n CodeMirror.defineOption = option;\n\n // Passed to option handlers when there is no old value.\n CodeMirror.Init = Init;\n\n // These two are, on init, called from the constructor because they\n // have to be initialized before the editor can start at all.\n option(\"value\", \"\", function (cm, val) { return cm.setValue(val); }, true);\n option(\"mode\", null, function (cm, val) {\n cm.doc.modeOption = val;\n loadMode(cm);\n }, true);\n\n option(\"indentUnit\", 2, loadMode, true);\n option(\"indentWithTabs\", false);\n option(\"smartIndent\", true);\n option(\"tabSize\", 4, function (cm) {\n resetModeState(cm);\n clearCaches(cm);\n regChange(cm);\n }, true);\n\n option(\"lineSeparator\", null, function (cm, val) {\n cm.doc.lineSep = val;\n if (!val) { return }\n var newBreaks = [], lineNo = cm.doc.first;\n cm.doc.iter(function (line) {\n for (var pos = 0;;) {\n var found = line.text.indexOf(val, pos);\n if (found == -1) { break }\n pos = found + val.length;\n newBreaks.push(Pos(lineNo, found));\n }\n lineNo++;\n });\n for (var i = newBreaks.length - 1; i >= 0; i--)\n { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }\n });\n option(\"specialChars\", /[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u061c\\u200b-\\u200f\\u2028\\u2029\\ufeff]/g, function (cm, val, old) {\n cm.state.specialChars = new RegExp(val.source + (val.test(\"\\t\") ? \"\" : \"|\\t\"), \"g\");\n if (old != Init) { cm.refresh(); }\n });\n option(\"specialCharPlaceholder\", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);\n option(\"electricChars\", true);\n option(\"inputStyle\", mobile ? \"contenteditable\" : \"textarea\", function () {\n throw new Error(\"inputStyle can not (yet) be changed in a running editor\") // FIXME\n }, true);\n option(\"spellcheck\", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);\n option(\"rtlMoveVisually\", !windows);\n option(\"wholeLineUpdateBefore\", true);\n\n option(\"theme\", \"default\", function (cm) {\n themeChanged(cm);\n guttersChanged(cm);\n }, true);\n option(\"keyMap\", \"default\", function (cm, val, old) {\n var next = getKeyMap(val);\n var prev = old != Init && getKeyMap(old);\n if (prev && prev.detach) { prev.detach(cm, next); }\n if (next.attach) { next.attach(cm, prev || null); }\n });\n option(\"extraKeys\", null);\n option(\"configureMouse\", null);\n\n option(\"lineWrapping\", false, wrappingChanged, true);\n option(\"gutters\", [], function (cm) {\n setGuttersForLineNumbers(cm.options);\n guttersChanged(cm);\n }, true);\n option(\"fixedGutter\", true, function (cm, val) {\n cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + \"px\" : \"0\";\n cm.refresh();\n }, true);\n option(\"coverGutterNextToScrollbar\", false, function (cm) { return updateScrollbars(cm); }, true);\n option(\"scrollbarStyle\", \"native\", function (cm) {\n initScrollbars(cm);\n updateScrollbars(cm);\n cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);\n cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);\n }, true);\n option(\"lineNumbers\", false, function (cm) {\n setGuttersForLineNumbers(cm.options);\n guttersChanged(cm);\n }, true);\n option(\"firstLineNumber\", 1, guttersChanged, true);\n option(\"lineNumberFormatter\", function (integer) { return integer; }, guttersChanged, true);\n option(\"showCursorWhenSelecting\", false, updateSelection, true);\n\n option(\"resetSelectionOnContextMenu\", true);\n option(\"lineWiseCopyCut\", true);\n option(\"pasteLinesPerSelection\", true);\n option(\"selectionsMayTouch\", false);\n\n option(\"readOnly\", false, function (cm, val) {\n if (val == \"nocursor\") {\n onBlur(cm);\n cm.display.input.blur();\n }\n cm.display.input.readOnlyChanged(val);\n });\n option(\"disableInput\", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);\n option(\"dragDrop\", true, dragDropChanged);\n option(\"allowDropFileTypes\", null);\n\n option(\"cursorBlinkRate\", 530);\n option(\"cursorScrollMargin\", 0);\n option(\"cursorHeight\", 1, updateSelection, true);\n option(\"singleCursorHeightPerLine\", true, updateSelection, true);\n option(\"workTime\", 100);\n option(\"workDelay\", 100);\n option(\"flattenSpans\", true, resetModeState, true);\n option(\"addModeClass\", false, resetModeState, true);\n option(\"pollInterval\", 100);\n option(\"undoDepth\", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });\n option(\"historyEventDelay\", 1250);\n option(\"viewportMargin\", 10, function (cm) { return cm.refresh(); }, true);\n option(\"maxHighlightLength\", 10000, resetModeState, true);\n option(\"moveInputWithCursor\", true, function (cm, val) {\n if (!val) { cm.display.input.resetPosition(); }\n });\n\n option(\"tabindex\", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || \"\"; });\n option(\"autofocus\", null);\n option(\"direction\", \"ltr\", function (cm, val) { return cm.doc.setDirection(val); }, true);\n option(\"phrases\", null);\n }\n\n function guttersChanged(cm) {\n updateGutters(cm);\n regChange(cm);\n alignHorizontally(cm);\n }\n\n function dragDropChanged(cm, value, old) {\n var wasOn = old && old != Init;\n if (!value != !wasOn) {\n var funcs = cm.display.dragFunctions;\n var toggle = value ? on : off;\n toggle(cm.display.scroller, \"dragstart\", funcs.start);\n toggle(cm.display.scroller, \"dragenter\", funcs.enter);\n toggle(cm.display.scroller, \"dragover\", funcs.over);\n toggle(cm.display.scroller, \"dragleave\", funcs.leave);\n toggle(cm.display.scroller, \"drop\", funcs.drop);\n }\n }\n\n function wrappingChanged(cm) {\n if (cm.options.lineWrapping) {\n addClass(cm.display.wrapper, \"CodeMirror-wrap\");\n cm.display.sizer.style.minWidth = \"\";\n cm.display.sizerWidth = null;\n } else {\n rmClass(cm.display.wrapper, \"CodeMirror-wrap\");\n findMaxLine(cm);\n }\n estimateLineHeights(cm);\n regChange(cm);\n clearCaches(cm);\n setTimeout(function () { return updateScrollbars(cm); }, 100);\n }\n\n // A CodeMirror instance represents an editor. This is the object\n // that user code is usually dealing with.\n\n function CodeMirror(place, options) {\n var this$1 = this;\n\n if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }\n\n this.options = options = options ? copyObj(options) : {};\n // Determine effective options based on given values and defaults.\n copyObj(defaults, options, false);\n setGuttersForLineNumbers(options);\n\n var doc = options.value;\n if (typeof doc == \"string\") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }\n else if (options.mode) { doc.modeOption = options.mode; }\n this.doc = doc;\n\n var input = new CodeMirror.inputStyles[options.inputStyle](this);\n var display = this.display = new Display(place, doc, input);\n display.wrapper.CodeMirror = this;\n updateGutters(this);\n themeChanged(this);\n if (options.lineWrapping)\n { this.display.wrapper.className += \" CodeMirror-wrap\"; }\n initScrollbars(this);\n\n this.state = {\n keyMaps: [], // stores maps added by addKeyMap\n overlays: [], // highlighting overlays, as added by addOverlay\n modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info\n overwrite: false,\n delayingBlurEvent: false,\n focused: false,\n suppressEdits: false, // used to disable editing during key handlers when in readOnly mode\n pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll\n selectingText: false,\n draggingText: false,\n highlight: new Delayed(), // stores highlight worker timeout\n keySeq: null, // Unfinished key sequence\n specialChars: null\n };\n\n if (options.autofocus && !mobile) { display.input.focus(); }\n\n // Override magic textarea content restore that IE sometimes does\n // on our hidden textarea on reload\n if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }\n\n registerEventHandlers(this);\n ensureGlobalHandlers();\n\n startOperation(this);\n this.curOp.forceUpdate = true;\n attachDoc(this, doc);\n\n if ((options.autofocus && !mobile) || this.hasFocus())\n { setTimeout(bind(onFocus, this), 20); }\n else\n { onBlur(this); }\n\n for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))\n { optionHandlers[opt](this$1, options[opt], Init); } }\n maybeUpdateLineNumberWidth(this);\n if (options.finishInit) { options.finishInit(this); }\n for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }\n endOperation(this);\n // Suppress optimizelegibility in Webkit, since it breaks text\n // measuring on line wrapping boundaries.\n if (webkit && options.lineWrapping &&\n getComputedStyle(display.lineDiv).textRendering == \"optimizelegibility\")\n { display.lineDiv.style.textRendering = \"auto\"; }\n }\n\n // The default configuration options.\n CodeMirror.defaults = defaults;\n // Functions to run when options are changed.\n CodeMirror.optionHandlers = optionHandlers;\n\n // Attach the necessary event handlers when initializing the editor\n function registerEventHandlers(cm) {\n var d = cm.display;\n on(d.scroller, \"mousedown\", operation(cm, onMouseDown));\n // Older IE's will not fire a second mousedown for a double click\n if (ie && ie_version < 11)\n { on(d.scroller, \"dblclick\", operation(cm, function (e) {\n if (signalDOMEvent(cm, e)) { return }\n var pos = posFromMouse(cm, e);\n if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }\n e_preventDefault(e);\n var word = cm.findWordAt(pos);\n extendSelection(cm.doc, word.anchor, word.head);\n })); }\n else\n { on(d.scroller, \"dblclick\", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }\n // Some browsers fire contextmenu *after* opening the menu, at\n // which point we can't mess with it anymore. Context menu is\n // handled in onMouseDown for these browsers.\n on(d.scroller, \"contextmenu\", function (e) { return onContextMenu(cm, e); });\n\n // Used to suppress mouse event handling when a touch happens\n var touchFinished, prevTouch = {end: 0};\n function finishTouch() {\n if (d.activeTouch) {\n touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);\n prevTouch = d.activeTouch;\n prevTouch.end = +new Date;\n }\n }\n function isMouseLikeTouchEvent(e) {\n if (e.touches.length != 1) { return false }\n var touch = e.touches[0];\n return touch.radiusX <= 1 && touch.radiusY <= 1\n }\n function farAway(touch, other) {\n if (other.left == null) { return true }\n var dx = other.left - touch.left, dy = other.top - touch.top;\n return dx * dx + dy * dy > 20 * 20\n }\n on(d.scroller, \"touchstart\", function (e) {\n if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {\n d.input.ensurePolled();\n clearTimeout(touchFinished);\n var now = +new Date;\n d.activeTouch = {start: now, moved: false,\n prev: now - prevTouch.end <= 300 ? prevTouch : null};\n if (e.touches.length == 1) {\n d.activeTouch.left = e.touches[0].pageX;\n d.activeTouch.top = e.touches[0].pageY;\n }\n }\n });\n on(d.scroller, \"touchmove\", function () {\n if (d.activeTouch) { d.activeTouch.moved = true; }\n });\n on(d.scroller, \"touchend\", function (e) {\n var touch = d.activeTouch;\n if (touch && !eventInWidget(d, e) && touch.left != null &&\n !touch.moved && new Date - touch.start < 300) {\n var pos = cm.coordsChar(d.activeTouch, \"page\"), range;\n if (!touch.prev || farAway(touch, touch.prev)) // Single tap\n { range = new Range(pos, pos); }\n else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap\n { range = cm.findWordAt(pos); }\n else // Triple tap\n { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }\n cm.setSelection(range.anchor, range.head);\n cm.focus();\n e_preventDefault(e);\n }\n finishTouch();\n });\n on(d.scroller, \"touchcancel\", finishTouch);\n\n // Sync scrolling between fake scrollbars and real scrollable\n // area, ensure viewport is updated when scrolling.\n on(d.scroller, \"scroll\", function () {\n if (d.scroller.clientHeight) {\n updateScrollTop(cm, d.scroller.scrollTop);\n setScrollLeft(cm, d.scroller.scrollLeft, true);\n signal(cm, \"scroll\", cm);\n }\n });\n\n // Listen to wheel events in order to try and update the viewport on time.\n on(d.scroller, \"mousewheel\", function (e) { return onScrollWheel(cm, e); });\n on(d.scroller, \"DOMMouseScroll\", function (e) { return onScrollWheel(cm, e); });\n\n // Prevent wrapper from ever scrolling\n on(d.wrapper, \"scroll\", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });\n\n d.dragFunctions = {\n enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},\n over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},\n start: function (e) { return onDragStart(cm, e); },\n drop: operation(cm, onDrop),\n leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}\n };\n\n var inp = d.input.getField();\n on(inp, \"keyup\", function (e) { return onKeyUp.call(cm, e); });\n on(inp, \"keydown\", operation(cm, onKeyDown));\n on(inp, \"keypress\", operation(cm, onKeyPress));\n on(inp, \"focus\", function (e) { return onFocus(cm, e); });\n on(inp, \"blur\", function (e) { return onBlur(cm, e); });\n }\n\n var initHooks = [];\n CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };\n\n // Indent the given line. The how parameter can be \"smart\",\n // \"add\"/null, \"subtract\", or \"prev\". When aggressive is false\n // (typically set to true for forced single-line indents), empty\n // lines are not indented, and places where the mode returns Pass\n // are left alone.\n function indentLine(cm, n, how, aggressive) {\n var doc = cm.doc, state;\n if (how == null) { how = \"add\"; }\n if (how == \"smart\") {\n // Fall back to \"prev\" when the mode doesn't have an indentation\n // method.\n if (!doc.mode.indent) { how = \"prev\"; }\n else { state = getContextBefore(cm, n).state; }\n }\n\n var tabSize = cm.options.tabSize;\n var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);\n if (line.stateAfter) { line.stateAfter = null; }\n var curSpaceString = line.text.match(/^\\s*/)[0], indentation;\n if (!aggressive && !/\\S/.test(line.text)) {\n indentation = 0;\n how = \"not\";\n } else if (how == \"smart\") {\n indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);\n if (indentation == Pass || indentation > 150) {\n if (!aggressive) { return }\n how = \"prev\";\n }\n }\n if (how == \"prev\") {\n if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }\n else { indentation = 0; }\n } else if (how == \"add\") {\n indentation = curSpace + cm.options.indentUnit;\n } else if (how == \"subtract\") {\n indentation = curSpace - cm.options.indentUnit;\n } else if (typeof how == \"number\") {\n indentation = curSpace + how;\n }\n indentation = Math.max(0, indentation);\n\n var indentString = \"\", pos = 0;\n if (cm.options.indentWithTabs)\n { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += \"\\t\";} }\n if (pos < indentation) { indentString += spaceStr(indentation - pos); }\n\n if (indentString != curSpaceString) {\n replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), \"+input\");\n line.stateAfter = null;\n return true\n } else {\n // Ensure that, if the cursor was in the whitespace at the start\n // of the line, it is moved to the end of that space.\n for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {\n var range = doc.sel.ranges[i$1];\n if (range.head.line == n && range.head.ch < curSpaceString.length) {\n var pos$1 = Pos(n, curSpaceString.length);\n replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));\n break\n }\n }\n }\n }\n\n // This will be set to a {lineWise: bool, text: [string]} object, so\n // that, when pasting, we know what kind of selections the copied\n // text was made out of.\n var lastCopied = null;\n\n function setLastCopied(newLastCopied) {\n lastCopied = newLastCopied;\n }\n\n function applyTextInput(cm, inserted, deleted, sel, origin) {\n var doc = cm.doc;\n cm.display.shift = false;\n if (!sel) { sel = doc.sel; }\n\n var paste = cm.state.pasteIncoming || origin == \"paste\";\n var textLines = splitLinesAuto(inserted), multiPaste = null;\n // When pasting N lines into N selections, insert one line per selection\n if (paste && sel.ranges.length > 1) {\n if (lastCopied && lastCopied.text.join(\"\\n\") == inserted) {\n if (sel.ranges.length % lastCopied.text.length == 0) {\n multiPaste = [];\n for (var i = 0; i < lastCopied.text.length; i++)\n { multiPaste.push(doc.splitLines(lastCopied.text[i])); }\n }\n } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {\n multiPaste = map(textLines, function (l) { return [l]; });\n }\n }\n\n var updateInput;\n // Normal behavior is to insert the new text into every selection\n for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {\n var range$$1 = sel.ranges[i$1];\n var from = range$$1.from(), to = range$$1.to();\n if (range$$1.empty()) {\n if (deleted && deleted > 0) // Handle deletion\n { from = Pos(from.line, from.ch - deleted); }\n else if (cm.state.overwrite && !paste) // Handle overwrite\n { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }\n else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join(\"\\n\") == inserted)\n { from = to = Pos(from.line, 0); }\n }\n updateInput = cm.curOp.updateInput;\n var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,\n origin: origin || (paste ? \"paste\" : cm.state.cutIncoming ? \"cut\" : \"+input\")};\n makeChange(cm.doc, changeEvent);\n signalLater(cm, \"inputRead\", cm, changeEvent);\n }\n if (inserted && !paste)\n { triggerElectric(cm, inserted); }\n\n ensureCursorVisible(cm);\n cm.curOp.updateInput = updateInput;\n cm.curOp.typing = true;\n cm.state.pasteIncoming = cm.state.cutIncoming = false;\n }\n\n function handlePaste(e, cm) {\n var pasted = e.clipboardData && e.clipboardData.getData(\"Text\");\n if (pasted) {\n e.preventDefault();\n if (!cm.isReadOnly() && !cm.options.disableInput)\n { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, \"paste\"); }); }\n return true\n }\n }\n\n function triggerElectric(cm, inserted) {\n // When an 'electric' character is inserted, immediately trigger a reindent\n if (!cm.options.electricChars || !cm.options.smartIndent) { return }\n var sel = cm.doc.sel;\n\n for (var i = sel.ranges.length - 1; i >= 0; i--) {\n var range$$1 = sel.ranges[i];\n if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }\n var mode = cm.getModeAt(range$$1.head);\n var indented = false;\n if (mode.electricChars) {\n for (var j = 0; j < mode.electricChars.length; j++)\n { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {\n indented = indentLine(cm, range$$1.head.line, \"smart\");\n break\n } }\n } else if (mode.electricInput) {\n if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))\n { indented = indentLine(cm, range$$1.head.line, \"smart\"); }\n }\n if (indented) { signalLater(cm, \"electricInput\", cm, range$$1.head.line); }\n }\n }\n\n function copyableRanges(cm) {\n var text = [], ranges = [];\n for (var i = 0; i < cm.doc.sel.ranges.length; i++) {\n var line = cm.doc.sel.ranges[i].head.line;\n var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};\n ranges.push(lineRange);\n text.push(cm.getRange(lineRange.anchor, lineRange.head));\n }\n return {text: text, ranges: ranges}\n }\n\n function disableBrowserMagic(field, spellcheck) {\n field.setAttribute(\"autocorrect\", \"off\");\n field.setAttribute(\"autocapitalize\", \"off\");\n field.setAttribute(\"spellcheck\", !!spellcheck);\n }\n\n function hiddenTextarea() {\n var te = elt(\"textarea\", null, null, \"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none\");\n var div = elt(\"div\", [te], null, \"overflow: hidden; position: relative; width: 3px; height: 0px;\");\n // The textarea is kept positioned near the cursor to prevent the\n // fact that it'll be scrolled into view on input from scrolling\n // our fake cursor out of view. On webkit, when wrap=off, paste is\n // very slow. So make the area wide instead.\n if (webkit) { te.style.width = \"1000px\"; }\n else { te.setAttribute(\"wrap\", \"off\"); }\n // If border: 0; -- iOS fails to open keyboard (issue #1287)\n if (ios) { te.style.border = \"1px solid black\"; }\n disableBrowserMagic(te);\n return div\n }\n\n // The publicly visible API. Note that methodOp(f) means\n // 'wrap f in an operation, performed on its `this` parameter'.\n\n // This is not the complete set of editor methods. Most of the\n // methods defined on the Doc type are also injected into\n // CodeMirror.prototype, for backwards compatibility and\n // convenience.\n\n function addEditorMethods(CodeMirror) {\n var optionHandlers = CodeMirror.optionHandlers;\n\n var helpers = CodeMirror.helpers = {};\n\n CodeMirror.prototype = {\n constructor: CodeMirror,\n focus: function(){window.focus(); this.display.input.focus();},\n\n setOption: function(option, value) {\n var options = this.options, old = options[option];\n if (options[option] == value && option != \"mode\") { return }\n options[option] = value;\n if (optionHandlers.hasOwnProperty(option))\n { operation(this, optionHandlers[option])(this, value, old); }\n signal(this, \"optionChange\", this, option);\n },\n\n getOption: function(option) {return this.options[option]},\n getDoc: function() {return this.doc},\n\n addKeyMap: function(map$$1, bottom) {\n this.state.keyMaps[bottom ? \"push\" : \"unshift\"](getKeyMap(map$$1));\n },\n removeKeyMap: function(map$$1) {\n var maps = this.state.keyMaps;\n for (var i = 0; i < maps.length; ++i)\n { if (maps[i] == map$$1 || maps[i].name == map$$1) {\n maps.splice(i, 1);\n return true\n } }\n },\n\n addOverlay: methodOp(function(spec, options) {\n var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);\n if (mode.startState) { throw new Error(\"Overlays may not be stateful.\") }\n insertSorted(this.state.overlays,\n {mode: mode, modeSpec: spec, opaque: options && options.opaque,\n priority: (options && options.priority) || 0},\n function (overlay) { return overlay.priority; });\n this.state.modeGen++;\n regChange(this);\n }),\n removeOverlay: methodOp(function(spec) {\n var this$1 = this;\n\n var overlays = this.state.overlays;\n for (var i = 0; i < overlays.length; ++i) {\n var cur = overlays[i].modeSpec;\n if (cur == spec || typeof spec == \"string\" && cur.name == spec) {\n overlays.splice(i, 1);\n this$1.state.modeGen++;\n regChange(this$1);\n return\n }\n }\n }),\n\n indentLine: methodOp(function(n, dir, aggressive) {\n if (typeof dir != \"string\" && typeof dir != \"number\") {\n if (dir == null) { dir = this.options.smartIndent ? \"smart\" : \"prev\"; }\n else { dir = dir ? \"add\" : \"subtract\"; }\n }\n if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }\n }),\n indentSelection: methodOp(function(how) {\n var this$1 = this;\n\n var ranges = this.doc.sel.ranges, end = -1;\n for (var i = 0; i < ranges.length; i++) {\n var range$$1 = ranges[i];\n if (!range$$1.empty()) {\n var from = range$$1.from(), to = range$$1.to();\n var start = Math.max(end, from.line);\n end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;\n for (var j = start; j < end; ++j)\n { indentLine(this$1, j, how); }\n var newRanges = this$1.doc.sel.ranges;\n if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)\n { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }\n } else if (range$$1.head.line > end) {\n indentLine(this$1, range$$1.head.line, how, true);\n end = range$$1.head.line;\n if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }\n }\n }\n }),\n\n // Fetch the parser token for a given character. Useful for hacks\n // that want to inspect the mode state (say, for completion).\n getTokenAt: function(pos, precise) {\n return takeToken(this, pos, precise)\n },\n\n getLineTokens: function(line, precise) {\n return takeToken(this, Pos(line), precise, true)\n },\n\n getTokenTypeAt: function(pos) {\n pos = clipPos(this.doc, pos);\n var styles = getLineStyles(this, getLine(this.doc, pos.line));\n var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;\n var type;\n if (ch == 0) { type = styles[2]; }\n else { for (;;) {\n var mid = (before + after) >> 1;\n if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }\n else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }\n else { type = styles[mid * 2 + 2]; break }\n } }\n var cut = type ? type.indexOf(\"overlay \") : -1;\n return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)\n },\n\n getModeAt: function(pos) {\n var mode = this.doc.mode;\n if (!mode.innerMode) { return mode }\n return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode\n },\n\n getHelper: function(pos, type) {\n return this.getHelpers(pos, type)[0]\n },\n\n getHelpers: function(pos, type) {\n var this$1 = this;\n\n var found = [];\n if (!helpers.hasOwnProperty(type)) { return found }\n var help = helpers[type], mode = this.getModeAt(pos);\n if (typeof mode[type] == \"string\") {\n if (help[mode[type]]) { found.push(help[mode[type]]); }\n } else if (mode[type]) {\n for (var i = 0; i < mode[type].length; i++) {\n var val = help[mode[type][i]];\n if (val) { found.push(val); }\n }\n } else if (mode.helperType && help[mode.helperType]) {\n found.push(help[mode.helperType]);\n } else if (help[mode.name]) {\n found.push(help[mode.name]);\n }\n for (var i$1 = 0; i$1 < help._global.length; i$1++) {\n var cur = help._global[i$1];\n if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)\n { found.push(cur.val); }\n }\n return found\n },\n\n getStateAfter: function(line, precise) {\n var doc = this.doc;\n line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);\n return getContextBefore(this, line + 1, precise).state\n },\n\n cursorCoords: function(start, mode) {\n var pos, range$$1 = this.doc.sel.primary();\n if (start == null) { pos = range$$1.head; }\n else if (typeof start == \"object\") { pos = clipPos(this.doc, start); }\n else { pos = start ? range$$1.from() : range$$1.to(); }\n return cursorCoords(this, pos, mode || \"page\")\n },\n\n charCoords: function(pos, mode) {\n return charCoords(this, clipPos(this.doc, pos), mode || \"page\")\n },\n\n coordsChar: function(coords, mode) {\n coords = fromCoordSystem(this, coords, mode || \"page\");\n return coordsChar(this, coords.left, coords.top)\n },\n\n lineAtHeight: function(height, mode) {\n height = fromCoordSystem(this, {top: height, left: 0}, mode || \"page\").top;\n return lineAtHeight(this.doc, height + this.display.viewOffset)\n },\n heightAtLine: function(line, mode, includeWidgets) {\n var end = false, lineObj;\n if (typeof line == \"number\") {\n var last = this.doc.first + this.doc.size - 1;\n if (line < this.doc.first) { line = this.doc.first; }\n else if (line > last) { line = last; end = true; }\n lineObj = getLine(this.doc, line);\n } else {\n lineObj = line;\n }\n return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || \"page\", includeWidgets || end).top +\n (end ? this.doc.height - heightAtLine(lineObj) : 0)\n },\n\n defaultTextHeight: function() { return textHeight(this.display) },\n defaultCharWidth: function() { return charWidth(this.display) },\n\n getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},\n\n addWidget: function(pos, node, scroll, vert, horiz) {\n var display = this.display;\n pos = cursorCoords(this, clipPos(this.doc, pos));\n var top = pos.bottom, left = pos.left;\n node.style.position = \"absolute\";\n node.setAttribute(\"cm-ignore-events\", \"true\");\n this.display.input.setUneditable(node);\n display.sizer.appendChild(node);\n if (vert == \"over\") {\n top = pos.top;\n } else if (vert == \"above\" || vert == \"near\") {\n var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),\n hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);\n // Default to positioning above (if specified and possible); otherwise default to positioning below\n if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)\n { top = pos.top - node.offsetHeight; }\n else if (pos.bottom + node.offsetHeight <= vspace)\n { top = pos.bottom; }\n if (left + node.offsetWidth > hspace)\n { left = hspace - node.offsetWidth; }\n }\n node.style.top = top + \"px\";\n node.style.left = node.style.right = \"\";\n if (horiz == \"right\") {\n left = display.sizer.clientWidth - node.offsetWidth;\n node.style.right = \"0px\";\n } else {\n if (horiz == \"left\") { left = 0; }\n else if (horiz == \"middle\") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }\n node.style.left = left + \"px\";\n }\n if (scroll)\n { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }\n },\n\n triggerOnKeyDown: methodOp(onKeyDown),\n triggerOnKeyPress: methodOp(onKeyPress),\n triggerOnKeyUp: onKeyUp,\n triggerOnMouseDown: methodOp(onMouseDown),\n\n execCommand: function(cmd) {\n if (commands.hasOwnProperty(cmd))\n { return commands[cmd].call(null, this) }\n },\n\n triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),\n\n findPosH: function(from, amount, unit, visually) {\n var this$1 = this;\n\n var dir = 1;\n if (amount < 0) { dir = -1; amount = -amount; }\n var cur = clipPos(this.doc, from);\n for (var i = 0; i < amount; ++i) {\n cur = findPosH(this$1.doc, cur, dir, unit, visually);\n if (cur.hitSide) { break }\n }\n return cur\n },\n\n moveH: methodOp(function(dir, unit) {\n var this$1 = this;\n\n this.extendSelectionsBy(function (range$$1) {\n if (this$1.display.shift || this$1.doc.extend || range$$1.empty())\n { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }\n else\n { return dir < 0 ? range$$1.from() : range$$1.to() }\n }, sel_move);\n }),\n\n deleteH: methodOp(function(dir, unit) {\n var sel = this.doc.sel, doc = this.doc;\n if (sel.somethingSelected())\n { doc.replaceSelection(\"\", null, \"+delete\"); }\n else\n { deleteNearSelection(this, function (range$$1) {\n var other = findPosH(doc, range$$1.head, dir, unit, false);\n return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}\n }); }\n }),\n\n findPosV: function(from, amount, unit, goalColumn) {\n var this$1 = this;\n\n var dir = 1, x = goalColumn;\n if (amount < 0) { dir = -1; amount = -amount; }\n var cur = clipPos(this.doc, from);\n for (var i = 0; i < amount; ++i) {\n var coords = cursorCoords(this$1, cur, \"div\");\n if (x == null) { x = coords.left; }\n else { coords.left = x; }\n cur = findPosV(this$1, coords, dir, unit);\n if (cur.hitSide) { break }\n }\n return cur\n },\n\n moveV: methodOp(function(dir, unit) {\n var this$1 = this;\n\n var doc = this.doc, goals = [];\n var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();\n doc.extendSelectionsBy(function (range$$1) {\n if (collapse)\n { return dir < 0 ? range$$1.from() : range$$1.to() }\n var headPos = cursorCoords(this$1, range$$1.head, \"div\");\n if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }\n goals.push(headPos.left);\n var pos = findPosV(this$1, headPos, dir, unit);\n if (unit == \"page\" && range$$1 == doc.sel.primary())\n { addToScrollTop(this$1, charCoords(this$1, pos, \"div\").top - headPos.top); }\n return pos\n }, sel_move);\n if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)\n { doc.sel.ranges[i].goalColumn = goals[i]; } }\n }),\n\n // Find the word at the given position (as returned by coordsChar).\n findWordAt: function(pos) {\n var doc = this.doc, line = getLine(doc, pos.line).text;\n var start = pos.ch, end = pos.ch;\n if (line) {\n var helper = this.getHelper(pos, \"wordChars\");\n if ((pos.sticky == \"before\" || end == line.length) && start) { --start; } else { ++end; }\n var startChar = line.charAt(start);\n var check = isWordChar(startChar, helper)\n ? function (ch) { return isWordChar(ch, helper); }\n : /\\s/.test(startChar) ? function (ch) { return /\\s/.test(ch); }\n : function (ch) { return (!/\\s/.test(ch) && !isWordChar(ch)); };\n while (start > 0 && check(line.charAt(start - 1))) { --start; }\n while (end < line.length && check(line.charAt(end))) { ++end; }\n }\n return new Range(Pos(pos.line, start), Pos(pos.line, end))\n },\n\n toggleOverwrite: function(value) {\n if (value != null && value == this.state.overwrite) { return }\n if (this.state.overwrite = !this.state.overwrite)\n { addClass(this.display.cursorDiv, \"CodeMirror-overwrite\"); }\n else\n { rmClass(this.display.cursorDiv, \"CodeMirror-overwrite\"); }\n\n signal(this, \"overwriteToggle\", this, this.state.overwrite);\n },\n hasFocus: function() { return this.display.input.getField() == activeElt() },\n isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },\n\n scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),\n getScrollInfo: function() {\n var scroller = this.display.scroller;\n return {left: scroller.scrollLeft, top: scroller.scrollTop,\n height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,\n width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,\n clientHeight: displayHeight(this), clientWidth: displayWidth(this)}\n },\n\n scrollIntoView: methodOp(function(range$$1, margin) {\n if (range$$1 == null) {\n range$$1 = {from: this.doc.sel.primary().head, to: null};\n if (margin == null) { margin = this.options.cursorScrollMargin; }\n } else if (typeof range$$1 == \"number\") {\n range$$1 = {from: Pos(range$$1, 0), to: null};\n } else if (range$$1.from == null) {\n range$$1 = {from: range$$1, to: null};\n }\n if (!range$$1.to) { range$$1.to = range$$1.from; }\n range$$1.margin = margin || 0;\n\n if (range$$1.from.line != null) {\n scrollToRange(this, range$$1);\n } else {\n scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);\n }\n }),\n\n setSize: methodOp(function(width, height) {\n var this$1 = this;\n\n var interpret = function (val) { return typeof val == \"number\" || /^\\d+$/.test(String(val)) ? val + \"px\" : val; };\n if (width != null) { this.display.wrapper.style.width = interpret(width); }\n if (height != null) { this.display.wrapper.style.height = interpret(height); }\n if (this.options.lineWrapping) { clearLineMeasurementCache(this); }\n var lineNo$$1 = this.display.viewFrom;\n this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {\n if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)\n { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, \"widget\"); break } } }\n ++lineNo$$1;\n });\n this.curOp.forceUpdate = true;\n signal(this, \"refresh\", this);\n }),\n\n operation: function(f){return runInOp(this, f)},\n startOperation: function(){return startOperation(this)},\n endOperation: function(){return endOperation(this)},\n\n refresh: methodOp(function() {\n var oldHeight = this.display.cachedTextHeight;\n regChange(this);\n this.curOp.forceUpdate = true;\n clearCaches(this);\n scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);\n updateGutterSpace(this);\n if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)\n { estimateLineHeights(this); }\n signal(this, \"refresh\", this);\n }),\n\n swapDoc: methodOp(function(doc) {\n var old = this.doc;\n old.cm = null;\n attachDoc(this, doc);\n clearCaches(this);\n this.display.input.reset();\n scrollToCoords(this, doc.scrollLeft, doc.scrollTop);\n this.curOp.forceScroll = true;\n signalLater(this, \"swapDoc\", this, old);\n return old\n }),\n\n phrase: function(phraseText) {\n var phrases = this.options.phrases;\n return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText\n },\n\n getInputField: function(){return this.display.input.getField()},\n getWrapperElement: function(){return this.display.wrapper},\n getScrollerElement: function(){return this.display.scroller},\n getGutterElement: function(){return this.display.gutters}\n };\n eventMixin(CodeMirror);\n\n CodeMirror.registerHelper = function(type, name, value) {\n if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }\n helpers[type][name] = value;\n };\n CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {\n CodeMirror.registerHelper(type, name, value);\n helpers[type]._global.push({pred: predicate, val: value});\n };\n }\n\n // Used for horizontal relative motion. Dir is -1 or 1 (left or\n // right), unit can be \"char\", \"column\" (like char, but doesn't\n // cross line boundaries), \"word\" (across next word), or \"group\" (to\n // the start of next group of word or non-word-non-whitespace\n // chars). The visually param controls whether, in right-to-left\n // text, direction 1 means to move towards the next index in the\n // string, or towards the character to the right of the current\n // position. The resulting position will have a hitSide=true\n // property if it reached the end of the document.\n function findPosH(doc, pos, dir, unit, visually) {\n var oldPos = pos;\n var origDir = dir;\n var lineObj = getLine(doc, pos.line);\n function findNextLine() {\n var l = pos.line + dir;\n if (l < doc.first || l >= doc.first + doc.size) { return false }\n pos = new Pos(l, pos.ch, pos.sticky);\n return lineObj = getLine(doc, l)\n }\n function moveOnce(boundToLine) {\n var next;\n if (visually) {\n next = moveVisually(doc.cm, lineObj, pos, dir);\n } else {\n next = moveLogically(lineObj, pos, dir);\n }\n if (next == null) {\n if (!boundToLine && findNextLine())\n { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }\n else\n { return false }\n } else {\n pos = next;\n }\n return true\n }\n\n if (unit == \"char\") {\n moveOnce();\n } else if (unit == \"column\") {\n moveOnce(true);\n } else if (unit == \"word\" || unit == \"group\") {\n var sawType = null, group = unit == \"group\";\n var helper = doc.cm && doc.cm.getHelper(pos, \"wordChars\");\n for (var first = true;; first = false) {\n if (dir < 0 && !moveOnce(!first)) { break }\n var cur = lineObj.text.charAt(pos.ch) || \"\\n\";\n var type = isWordChar(cur, helper) ? \"w\"\n : group && cur == \"\\n\" ? \"n\"\n : !group || /\\s/.test(cur) ? null\n : \"p\";\n if (group && !first && !type) { type = \"s\"; }\n if (sawType && sawType != type) {\n if (dir < 0) {dir = 1; moveOnce(); pos.sticky = \"after\";}\n break\n }\n\n if (type) { sawType = type; }\n if (dir > 0 && !moveOnce(!first)) { break }\n }\n }\n var result = skipAtomic(doc, pos, oldPos, origDir, true);\n if (equalCursorPos(oldPos, result)) { result.hitSide = true; }\n return result\n }\n\n // For relative vertical movement. Dir may be -1 or 1. Unit can be\n // \"page\" or \"line\". The resulting position will have a hitSide=true\n // property if it reached the end of the document.\n function findPosV(cm, pos, dir, unit) {\n var doc = cm.doc, x = pos.left, y;\n if (unit == \"page\") {\n var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);\n var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);\n y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;\n\n } else if (unit == \"line\") {\n y = dir > 0 ? pos.bottom + 3 : pos.top - 3;\n }\n var target;\n for (;;) {\n target = coordsChar(cm, x, y);\n if (!target.outside) { break }\n if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }\n y += dir * 5;\n }\n return target\n }\n\n // CONTENTEDITABLE INPUT STYLE\n\n var ContentEditableInput = function(cm) {\n this.cm = cm;\n this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;\n this.polling = new Delayed();\n this.composing = null;\n this.gracePeriod = false;\n this.readDOMTimeout = null;\n };\n\n ContentEditableInput.prototype.init = function (display) {\n var this$1 = this;\n\n var input = this, cm = input.cm;\n var div = input.div = display.lineDiv;\n disableBrowserMagic(div, cm.options.spellcheck);\n\n on(div, \"paste\", function (e) {\n if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }\n // IE doesn't fire input events, so we schedule a read for the pasted content in this way\n if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }\n });\n\n on(div, \"compositionstart\", function (e) {\n this$1.composing = {data: e.data, done: false};\n });\n on(div, \"compositionupdate\", function (e) {\n if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }\n });\n on(div, \"compositionend\", function (e) {\n if (this$1.composing) {\n if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }\n this$1.composing.done = true;\n }\n });\n\n on(div, \"touchstart\", function () { return input.forceCompositionEnd(); });\n\n on(div, \"input\", function () {\n if (!this$1.composing) { this$1.readFromDOMSoon(); }\n });\n\n function onCopyCut(e) {\n if (signalDOMEvent(cm, e)) { return }\n if (cm.somethingSelected()) {\n setLastCopied({lineWise: false, text: cm.getSelections()});\n if (e.type == \"cut\") { cm.replaceSelection(\"\", null, \"cut\"); }\n } else if (!cm.options.lineWiseCopyCut) {\n return\n } else {\n var ranges = copyableRanges(cm);\n setLastCopied({lineWise: true, text: ranges.text});\n if (e.type == \"cut\") {\n cm.operation(function () {\n cm.setSelections(ranges.ranges, 0, sel_dontScroll);\n cm.replaceSelection(\"\", null, \"cut\");\n });\n }\n }\n if (e.clipboardData) {\n e.clipboardData.clearData();\n var content = lastCopied.text.join(\"\\n\");\n // iOS exposes the clipboard API, but seems to discard content inserted into it\n e.clipboardData.setData(\"Text\", content);\n if (e.clipboardData.getData(\"Text\") == content) {\n e.preventDefault();\n return\n }\n }\n // Old-fashioned briefly-focus-a-textarea hack\n var kludge = hiddenTextarea(), te = kludge.firstChild;\n cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);\n te.value = lastCopied.text.join(\"\\n\");\n var hadFocus = document.activeElement;\n selectInput(te);\n setTimeout(function () {\n cm.display.lineSpace.removeChild(kludge);\n hadFocus.focus();\n if (hadFocus == div) { input.showPrimarySelection(); }\n }, 50);\n }\n on(div, \"copy\", onCopyCut);\n on(div, \"cut\", onCopyCut);\n };\n\n ContentEditableInput.prototype.prepareSelection = function () {\n var result = prepareSelection(this.cm, false);\n result.focus = this.cm.state.focused;\n return result\n };\n\n ContentEditableInput.prototype.showSelection = function (info, takeFocus) {\n if (!info || !this.cm.display.view.length) { return }\n if (info.focus || takeFocus) { this.showPrimarySelection(); }\n this.showMultipleSelections(info);\n };\n\n ContentEditableInput.prototype.getSelection = function () {\n return this.cm.display.wrapper.ownerDocument.getSelection()\n };\n\n ContentEditableInput.prototype.showPrimarySelection = function () {\n var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();\n var from = prim.from(), to = prim.to();\n\n if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {\n sel.removeAllRanges();\n return\n }\n\n var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);\n var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);\n if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&\n cmp(minPos(curAnchor, curFocus), from) == 0 &&\n cmp(maxPos(curAnchor, curFocus), to) == 0)\n { return }\n\n var view = cm.display.view;\n var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||\n {node: view[0].measure.map[2], offset: 0};\n var end = to.line < cm.display.viewTo && posToDOM(cm, to);\n if (!end) {\n var measure = view[view.length - 1].measure;\n var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;\n end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};\n }\n\n if (!start || !end) {\n sel.removeAllRanges();\n return\n }\n\n var old = sel.rangeCount && sel.getRangeAt(0), rng;\n try { rng = range(start.node, start.offset, end.offset, end.node); }\n catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible\n if (rng) {\n if (!gecko && cm.state.focused) {\n sel.collapse(start.node, start.offset);\n if (!rng.collapsed) {\n sel.removeAllRanges();\n sel.addRange(rng);\n }\n } else {\n sel.removeAllRanges();\n sel.addRange(rng);\n }\n if (old && sel.anchorNode == null) { sel.addRange(old); }\n else if (gecko) { this.startGracePeriod(); }\n }\n this.rememberSelection();\n };\n\n ContentEditableInput.prototype.startGracePeriod = function () {\n var this$1 = this;\n\n clearTimeout(this.gracePeriod);\n this.gracePeriod = setTimeout(function () {\n this$1.gracePeriod = false;\n if (this$1.selectionChanged())\n { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }\n }, 20);\n };\n\n ContentEditableInput.prototype.showMultipleSelections = function (info) {\n removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);\n removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);\n };\n\n ContentEditableInput.prototype.rememberSelection = function () {\n var sel = this.getSelection();\n this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;\n this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;\n };\n\n ContentEditableInput.prototype.selectionInEditor = function () {\n var sel = this.getSelection();\n if (!sel.rangeCount) { return false }\n var node = sel.getRangeAt(0).commonAncestorContainer;\n return contains(this.div, node)\n };\n\n ContentEditableInput.prototype.focus = function () {\n if (this.cm.options.readOnly != \"nocursor\") {\n if (!this.selectionInEditor())\n { this.showSelection(this.prepareSelection(), true); }\n this.div.focus();\n }\n };\n ContentEditableInput.prototype.blur = function () { this.div.blur(); };\n ContentEditableInput.prototype.getField = function () { return this.div };\n\n ContentEditableInput.prototype.supportsTouch = function () { return true };\n\n ContentEditableInput.prototype.receivedFocus = function () {\n var input = this;\n if (this.selectionInEditor())\n { this.pollSelection(); }\n else\n { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }\n\n function poll() {\n if (input.cm.state.focused) {\n input.pollSelection();\n input.polling.set(input.cm.options.pollInterval, poll);\n }\n }\n this.polling.set(this.cm.options.pollInterval, poll);\n };\n\n ContentEditableInput.prototype.selectionChanged = function () {\n var sel = this.getSelection();\n return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||\n sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset\n };\n\n ContentEditableInput.prototype.pollSelection = function () {\n if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }\n var sel = this.getSelection(), cm = this.cm;\n // On Android Chrome (version 56, at least), backspacing into an\n // uneditable block element will put the cursor in that element,\n // and then, because it's not editable, hide the virtual keyboard.\n // Because Android doesn't allow us to actually detect backspace\n // presses in a sane way, this code checks for when that happens\n // and simulates a backspace press in this case.\n if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {\n this.cm.triggerOnKeyDown({type: \"keydown\", keyCode: 8, preventDefault: Math.abs});\n this.blur();\n this.focus();\n return\n }\n if (this.composing) { return }\n this.rememberSelection();\n var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);\n var head = domToPos(cm, sel.focusNode, sel.focusOffset);\n if (anchor && head) { runInOp(cm, function () {\n setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);\n if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }\n }); }\n };\n\n ContentEditableInput.prototype.pollContent = function () {\n if (this.readDOMTimeout != null) {\n clearTimeout(this.readDOMTimeout);\n this.readDOMTimeout = null;\n }\n\n var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();\n var from = sel.from(), to = sel.to();\n if (from.ch == 0 && from.line > cm.firstLine())\n { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }\n if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())\n { to = Pos(to.line + 1, 0); }\n if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }\n\n var fromIndex, fromLine, fromNode;\n if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {\n fromLine = lineNo(display.view[0].line);\n fromNode = display.view[0].node;\n } else {\n fromLine = lineNo(display.view[fromIndex].line);\n fromNode = display.view[fromIndex - 1].node.nextSibling;\n }\n var toIndex = findViewIndex(cm, to.line);\n var toLine, toNode;\n if (toIndex == display.view.length - 1) {\n toLine = display.viewTo - 1;\n toNode = display.lineDiv.lastChild;\n } else {\n toLine = lineNo(display.view[toIndex + 1].line) - 1;\n toNode = display.view[toIndex + 1].node.previousSibling;\n }\n\n if (!fromNode) { return false }\n var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));\n var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));\n while (newText.length > 1 && oldText.length > 1) {\n if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }\n else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }\n else { break }\n }\n\n var cutFront = 0, cutEnd = 0;\n var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);\n while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))\n { ++cutFront; }\n var newBot = lst(newText), oldBot = lst(oldText);\n var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),\n oldBot.length - (oldText.length == 1 ? cutFront : 0));\n while (cutEnd < maxCutEnd &&\n newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))\n { ++cutEnd; }\n // Try to move start of change to start of selection if ambiguous\n if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {\n while (cutFront && cutFront > from.ch &&\n newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {\n cutFront--;\n cutEnd++;\n }\n }\n\n newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\\u200b+/, \"\");\n newText[0] = newText[0].slice(cutFront).replace(/\\u200b+$/, \"\");\n\n var chFrom = Pos(fromLine, cutFront);\n var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);\n if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {\n replaceRange(cm.doc, newText, chFrom, chTo, \"+input\");\n return true\n }\n };\n\n ContentEditableInput.prototype.ensurePolled = function () {\n this.forceCompositionEnd();\n };\n ContentEditableInput.prototype.reset = function () {\n this.forceCompositionEnd();\n };\n ContentEditableInput.prototype.forceCompositionEnd = function () {\n if (!this.composing) { return }\n clearTimeout(this.readDOMTimeout);\n this.composing = null;\n this.updateFromDOM();\n this.div.blur();\n this.div.focus();\n };\n ContentEditableInput.prototype.readFromDOMSoon = function () {\n var this$1 = this;\n\n if (this.readDOMTimeout != null) { return }\n this.readDOMTimeout = setTimeout(function () {\n this$1.readDOMTimeout = null;\n if (this$1.composing) {\n if (this$1.composing.done) { this$1.composing = null; }\n else { return }\n }\n this$1.updateFromDOM();\n }, 80);\n };\n\n ContentEditableInput.prototype.updateFromDOM = function () {\n var this$1 = this;\n\n if (this.cm.isReadOnly() || !this.pollContent())\n { runInOp(this.cm, function () { return regChange(this$1.cm); }); }\n };\n\n ContentEditableInput.prototype.setUneditable = function (node) {\n node.contentEditable = \"false\";\n };\n\n ContentEditableInput.prototype.onKeyPress = function (e) {\n if (e.charCode == 0 || this.composing) { return }\n e.preventDefault();\n if (!this.cm.isReadOnly())\n { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }\n };\n\n ContentEditableInput.prototype.readOnlyChanged = function (val) {\n this.div.contentEditable = String(val != \"nocursor\");\n };\n\n ContentEditableInput.prototype.onContextMenu = function () {};\n ContentEditableInput.prototype.resetPosition = function () {};\n\n ContentEditableInput.prototype.needsContentAttribute = true;\n\n function posToDOM(cm, pos) {\n var view = findViewForLine(cm, pos.line);\n if (!view || view.hidden) { return null }\n var line = getLine(cm.doc, pos.line);\n var info = mapFromLineView(view, line, pos.line);\n\n var order = getOrder(line, cm.doc.direction), side = \"left\";\n if (order) {\n var partPos = getBidiPartAt(order, pos.ch);\n side = partPos % 2 ? \"right\" : \"left\";\n }\n var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);\n result.offset = result.collapse == \"right\" ? result.end : result.start;\n return result\n }\n\n function isInGutter(node) {\n for (var scan = node; scan; scan = scan.parentNode)\n { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }\n return false\n }\n\n function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }\n\n function domTextBetween(cm, from, to, fromLine, toLine) {\n var text = \"\", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;\n function recognizeMarker(id) { return function (marker) { return marker.id == id; } }\n function close() {\n if (closing) {\n text += lineSep;\n if (extraLinebreak) { text += lineSep; }\n closing = extraLinebreak = false;\n }\n }\n function addText(str) {\n if (str) {\n close();\n text += str;\n }\n }\n function walk(node) {\n if (node.nodeType == 1) {\n var cmText = node.getAttribute(\"cm-text\");\n if (cmText) {\n addText(cmText);\n return\n }\n var markerID = node.getAttribute(\"cm-marker\"), range$$1;\n if (markerID) {\n var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));\n if (found.length && (range$$1 = found[0].find(0)))\n { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }\n return\n }\n if (node.getAttribute(\"contenteditable\") == \"false\") { return }\n var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);\n if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }\n\n if (isBlock) { close(); }\n for (var i = 0; i < node.childNodes.length; i++)\n { walk(node.childNodes[i]); }\n\n if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }\n if (isBlock) { closing = true; }\n } else if (node.nodeType == 3) {\n addText(node.nodeValue.replace(/\\u200b/g, \"\").replace(/\\u00a0/g, \" \"));\n }\n }\n for (;;) {\n walk(from);\n if (from == to) { break }\n from = from.nextSibling;\n extraLinebreak = false;\n }\n return text\n }\n\n function domToPos(cm, node, offset) {\n var lineNode;\n if (node == cm.display.lineDiv) {\n lineNode = cm.display.lineDiv.childNodes[offset];\n if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }\n node = null; offset = 0;\n } else {\n for (lineNode = node;; lineNode = lineNode.parentNode) {\n if (!lineNode || lineNode == cm.display.lineDiv) { return null }\n if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }\n }\n }\n for (var i = 0; i < cm.display.view.length; i++) {\n var lineView = cm.display.view[i];\n if (lineView.node == lineNode)\n { return locateNodeInLineView(lineView, node, offset) }\n }\n }\n\n function locateNodeInLineView(lineView, node, offset) {\n var wrapper = lineView.text.firstChild, bad = false;\n if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }\n if (node == wrapper) {\n bad = true;\n node = wrapper.childNodes[offset];\n offset = 0;\n if (!node) {\n var line = lineView.rest ? lst(lineView.rest) : lineView.line;\n return badPos(Pos(lineNo(line), line.text.length), bad)\n }\n }\n\n var textNode = node.nodeType == 3 ? node : null, topNode = node;\n if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {\n textNode = node.firstChild;\n if (offset) { offset = textNode.nodeValue.length; }\n }\n while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }\n var measure = lineView.measure, maps = measure.maps;\n\n function find(textNode, topNode, offset) {\n for (var i = -1; i < (maps ? maps.length : 0); i++) {\n var map$$1 = i < 0 ? measure.map : maps[i];\n for (var j = 0; j < map$$1.length; j += 3) {\n var curNode = map$$1[j + 2];\n if (curNode == textNode || curNode == topNode) {\n var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);\n var ch = map$$1[j] + offset;\n if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }\n return Pos(line, ch)\n }\n }\n }\n }\n var found = find(textNode, topNode, offset);\n if (found) { return badPos(found, bad) }\n\n // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems\n for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {\n found = find(after, after.firstChild, 0);\n if (found)\n { return badPos(Pos(found.line, found.ch - dist), bad) }\n else\n { dist += after.textContent.length; }\n }\n for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {\n found = find(before, before.firstChild, -1);\n if (found)\n { return badPos(Pos(found.line, found.ch + dist$1), bad) }\n else\n { dist$1 += before.textContent.length; }\n }\n }\n\n // TEXTAREA INPUT STYLE\n\n var TextareaInput = function(cm) {\n this.cm = cm;\n // See input.poll and input.reset\n this.prevInput = \"\";\n\n // Flag that indicates whether we expect input to appear real soon\n // now (after some event like 'keypress' or 'input') and are\n // polling intensively.\n this.pollingFast = false;\n // Self-resetting timeout for the poller\n this.polling = new Delayed();\n // Used to work around IE issue with selection being forgotten when focus moves away from textarea\n this.hasSelection = false;\n this.composing = null;\n };\n\n TextareaInput.prototype.init = function (display) {\n var this$1 = this;\n\n var input = this, cm = this.cm;\n this.createField(display);\n var te = this.textarea;\n\n display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);\n\n // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)\n if (ios) { te.style.width = \"0px\"; }\n\n on(te, \"input\", function () {\n if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }\n input.poll();\n });\n\n on(te, \"paste\", function (e) {\n if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }\n\n cm.state.pasteIncoming = true;\n input.fastPoll();\n });\n\n function prepareCopyCut(e) {\n if (signalDOMEvent(cm, e)) { return }\n if (cm.somethingSelected()) {\n setLastCopied({lineWise: false, text: cm.getSelections()});\n } else if (!cm.options.lineWiseCopyCut) {\n return\n } else {\n var ranges = copyableRanges(cm);\n setLastCopied({lineWise: true, text: ranges.text});\n if (e.type == \"cut\") {\n cm.setSelections(ranges.ranges, null, sel_dontScroll);\n } else {\n input.prevInput = \"\";\n te.value = ranges.text.join(\"\\n\");\n selectInput(te);\n }\n }\n if (e.type == \"cut\") { cm.state.cutIncoming = true; }\n }\n on(te, \"cut\", prepareCopyCut);\n on(te, \"copy\", prepareCopyCut);\n\n on(display.scroller, \"paste\", function (e) {\n if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }\n cm.state.pasteIncoming = true;\n input.focus();\n });\n\n // Prevent normal selection in the editor (we handle our own)\n on(display.lineSpace, \"selectstart\", function (e) {\n if (!eventInWidget(display, e)) { e_preventDefault(e); }\n });\n\n on(te, \"compositionstart\", function () {\n var start = cm.getCursor(\"from\");\n if (input.composing) { input.composing.range.clear(); }\n input.composing = {\n start: start,\n range: cm.markText(start, cm.getCursor(\"to\"), {className: \"CodeMirror-composing\"})\n };\n });\n on(te, \"compositionend\", function () {\n if (input.composing) {\n input.poll();\n input.composing.range.clear();\n input.composing = null;\n }\n });\n };\n\n TextareaInput.prototype.createField = function (_display) {\n // Wraps and hides input textarea\n this.wrapper = hiddenTextarea();\n // The semihidden textarea that is focused when the editor is\n // focused, and receives input.\n this.textarea = this.wrapper.firstChild;\n };\n\n TextareaInput.prototype.prepareSelection = function () {\n // Redraw the selection and/or cursor\n var cm = this.cm, display = cm.display, doc = cm.doc;\n var result = prepareSelection(cm);\n\n // Move the hidden textarea near the cursor to prevent scrolling artifacts\n if (cm.options.moveInputWithCursor) {\n var headPos = cursorCoords(cm, doc.sel.primary().head, \"div\");\n var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();\n result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,\n headPos.top + lineOff.top - wrapOff.top));\n result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,\n headPos.left + lineOff.left - wrapOff.left));\n }\n\n return result\n };\n\n TextareaInput.prototype.showSelection = function (drawn) {\n var cm = this.cm, display = cm.display;\n removeChildrenAndAdd(display.cursorDiv, drawn.cursors);\n removeChildrenAndAdd(display.selectionDiv, drawn.selection);\n if (drawn.teTop != null) {\n this.wrapper.style.top = drawn.teTop + \"px\";\n this.wrapper.style.left = drawn.teLeft + \"px\";\n }\n };\n\n // Reset the input to correspond to the selection (or to be empty,\n // when not typing and nothing is selected)\n TextareaInput.prototype.reset = function (typing) {\n if (this.contextMenuPending || this.composing) { return }\n var cm = this.cm;\n if (cm.somethingSelected()) {\n this.prevInput = \"\";\n var content = cm.getSelection();\n this.textarea.value = content;\n if (cm.state.focused) { selectInput(this.textarea); }\n if (ie && ie_version >= 9) { this.hasSelection = content; }\n } else if (!typing) {\n this.prevInput = this.textarea.value = \"\";\n if (ie && ie_version >= 9) { this.hasSelection = null; }\n }\n };\n\n TextareaInput.prototype.getField = function () { return this.textarea };\n\n TextareaInput.prototype.supportsTouch = function () { return false };\n\n TextareaInput.prototype.focus = function () {\n if (this.cm.options.readOnly != \"nocursor\" && (!mobile || activeElt() != this.textarea)) {\n try { this.textarea.focus(); }\n catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM\n }\n };\n\n TextareaInput.prototype.blur = function () { this.textarea.blur(); };\n\n TextareaInput.prototype.resetPosition = function () {\n this.wrapper.style.top = this.wrapper.style.left = 0;\n };\n\n TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };\n\n // Poll for input changes, using the normal rate of polling. This\n // runs as long as the editor is focused.\n TextareaInput.prototype.slowPoll = function () {\n var this$1 = this;\n\n if (this.pollingFast) { return }\n this.polling.set(this.cm.options.pollInterval, function () {\n this$1.poll();\n if (this$1.cm.state.focused) { this$1.slowPoll(); }\n });\n };\n\n // When an event has just come in that is likely to add or change\n // something in the input textarea, we poll faster, to ensure that\n // the change appears on the screen quickly.\n TextareaInput.prototype.fastPoll = function () {\n var missed = false, input = this;\n input.pollingFast = true;\n function p() {\n var changed = input.poll();\n if (!changed && !missed) {missed = true; input.polling.set(60, p);}\n else {input.pollingFast = false; input.slowPoll();}\n }\n input.polling.set(20, p);\n };\n\n // Read input from the textarea, and update the document to match.\n // When something is selected, it is present in the textarea, and\n // selected (unless it is huge, in which case a placeholder is\n // used). When nothing is selected, the cursor sits after previously\n // seen text (can be empty), which is stored in prevInput (we must\n // not reset the textarea when typing, because that breaks IME).\n TextareaInput.prototype.poll = function () {\n var this$1 = this;\n\n var cm = this.cm, input = this.textarea, prevInput = this.prevInput;\n // Since this is called a *lot*, try to bail out as cheaply as\n // possible when it is clear that nothing happened. hasSelection\n // will be the case when there is a lot of text in the textarea,\n // in which case reading its value would be expensive.\n if (this.contextMenuPending || !cm.state.focused ||\n (hasSelection(input) && !prevInput && !this.composing) ||\n cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)\n { return false }\n\n var text = input.value;\n // If nothing changed, bail.\n if (text == prevInput && !cm.somethingSelected()) { return false }\n // Work around nonsensical selection resetting in IE9/10, and\n // inexplicable appearance of private area unicode characters on\n // some key combos in Mac (#2689).\n if (ie && ie_version >= 9 && this.hasSelection === text ||\n mac && /[\\uf700-\\uf7ff]/.test(text)) {\n cm.display.input.reset();\n return false\n }\n\n if (cm.doc.sel == cm.display.selForContextMenu) {\n var first = text.charCodeAt(0);\n if (first == 0x200b && !prevInput) { prevInput = \"\\u200b\"; }\n if (first == 0x21da) { this.reset(); return this.cm.execCommand(\"undo\") }\n }\n // Find the part of the input that is actually new\n var same = 0, l = Math.min(prevInput.length, text.length);\n while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }\n\n runInOp(cm, function () {\n applyTextInput(cm, text.slice(same), prevInput.length - same,\n null, this$1.composing ? \"*compose\" : null);\n\n // Don't leave long text in the textarea, since it makes further polling slow\n if (text.length > 1000 || text.indexOf(\"\\n\") > -1) { input.value = this$1.prevInput = \"\"; }\n else { this$1.prevInput = text; }\n\n if (this$1.composing) {\n this$1.composing.range.clear();\n this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor(\"to\"),\n {className: \"CodeMirror-composing\"});\n }\n });\n return true\n };\n\n TextareaInput.prototype.ensurePolled = function () {\n if (this.pollingFast && this.poll()) { this.pollingFast = false; }\n };\n\n TextareaInput.prototype.onKeyPress = function () {\n if (ie && ie_version >= 9) { this.hasSelection = null; }\n this.fastPoll();\n };\n\n TextareaInput.prototype.onContextMenu = function (e) {\n var input = this, cm = input.cm, display = cm.display, te = input.textarea;\n var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;\n if (!pos || presto) { return } // Opera is difficult.\n\n // Reset the current text selection only if the click is done outside of the selection\n // and 'resetSelectionOnContextMenu' option is true.\n var reset = cm.options.resetSelectionOnContextMenu;\n if (reset && cm.doc.sel.contains(pos) == -1)\n { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }\n\n var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;\n input.wrapper.style.cssText = \"position: absolute\";\n var wrapperBox = input.wrapper.getBoundingClientRect();\n te.style.cssText = \"position: absolute; width: 30px; height: 30px;\\n top: \" + (e.clientY - wrapperBox.top - 5) + \"px; left: \" + (e.clientX - wrapperBox.left - 5) + \"px;\\n z-index: 1000; background: \" + (ie ? \"rgba(255, 255, 255, .05)\" : \"transparent\") + \";\\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);\";\n var oldScrollY;\n if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)\n display.input.focus();\n if (webkit) { window.scrollTo(null, oldScrollY); }\n display.input.reset();\n // Adds \"Select all\" to context menu in FF\n if (!cm.somethingSelected()) { te.value = input.prevInput = \" \"; }\n input.contextMenuPending = true;\n display.selForContextMenu = cm.doc.sel;\n clearTimeout(display.detectingSelectAll);\n\n // Select-all will be greyed out if there's nothing to select, so\n // this adds a zero-width space so that we can later check whether\n // it got selected.\n function prepareSelectAllHack() {\n if (te.selectionStart != null) {\n var selected = cm.somethingSelected();\n var extval = \"\\u200b\" + (selected ? te.value : \"\");\n te.value = \"\\u21da\"; // Used to catch context-menu undo\n te.value = extval;\n input.prevInput = selected ? \"\" : \"\\u200b\";\n te.selectionStart = 1; te.selectionEnd = extval.length;\n // Re-set this, in case some other handler touched the\n // selection in the meantime.\n display.selForContextMenu = cm.doc.sel;\n }\n }\n function rehide() {\n input.contextMenuPending = false;\n input.wrapper.style.cssText = oldWrapperCSS;\n te.style.cssText = oldCSS;\n if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }\n\n // Try to detect the user choosing select-all\n if (te.selectionStart != null) {\n if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }\n var i = 0, poll = function () {\n if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&\n te.selectionEnd > 0 && input.prevInput == \"\\u200b\") {\n operation(cm, selectAll)(cm);\n } else if (i++ < 10) {\n display.detectingSelectAll = setTimeout(poll, 500);\n } else {\n display.selForContextMenu = null;\n display.input.reset();\n }\n };\n display.detectingSelectAll = setTimeout(poll, 200);\n }\n }\n\n if (ie && ie_version >= 9) { prepareSelectAllHack(); }\n if (captureRightClick) {\n e_stop(e);\n var mouseup = function () {\n off(window, \"mouseup\", mouseup);\n setTimeout(rehide, 20);\n };\n on(window, \"mouseup\", mouseup);\n } else {\n setTimeout(rehide, 50);\n }\n };\n\n TextareaInput.prototype.readOnlyChanged = function (val) {\n if (!val) { this.reset(); }\n this.textarea.disabled = val == \"nocursor\";\n };\n\n TextareaInput.prototype.setUneditable = function () {};\n\n TextareaInput.prototype.needsContentAttribute = false;\n\n function fromTextArea(textarea, options) {\n options = options ? copyObj(options) : {};\n options.value = textarea.value;\n if (!options.tabindex && textarea.tabIndex)\n { options.tabindex = textarea.tabIndex; }\n if (!options.placeholder && textarea.placeholder)\n { options.placeholder = textarea.placeholder; }\n // Set autofocus to true if this textarea is focused, or if it has\n // autofocus and no other element is focused.\n if (options.autofocus == null) {\n var hasFocus = activeElt();\n options.autofocus = hasFocus == textarea ||\n textarea.getAttribute(\"autofocus\") != null && hasFocus == document.body;\n }\n\n function save() {textarea.value = cm.getValue();}\n\n var realSubmit;\n if (textarea.form) {\n on(textarea.form, \"submit\", save);\n // Deplorable hack to make the submit method do the right thing.\n if (!options.leaveSubmitMethodAlone) {\n var form = textarea.form;\n realSubmit = form.submit;\n try {\n var wrappedSubmit = form.submit = function () {\n save();\n form.submit = realSubmit;\n form.submit();\n form.submit = wrappedSubmit;\n };\n } catch(e) {}\n }\n }\n\n options.finishInit = function (cm) {\n cm.save = save;\n cm.getTextArea = function () { return textarea; };\n cm.toTextArea = function () {\n cm.toTextArea = isNaN; // Prevent this from being ran twice\n save();\n textarea.parentNode.removeChild(cm.getWrapperElement());\n textarea.style.display = \"\";\n if (textarea.form) {\n off(textarea.form, \"submit\", save);\n if (typeof textarea.form.submit == \"function\")\n { textarea.form.submit = realSubmit; }\n }\n };\n };\n\n textarea.style.display = \"none\";\n var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },\n options);\n return cm\n }\n\n function addLegacyProps(CodeMirror) {\n CodeMirror.off = off;\n CodeMirror.on = on;\n CodeMirror.wheelEventPixels = wheelEventPixels;\n CodeMirror.Doc = Doc;\n CodeMirror.splitLines = splitLinesAuto;\n CodeMirror.countColumn = countColumn;\n CodeMirror.findColumn = findColumn;\n CodeMirror.isWordChar = isWordCharBasic;\n CodeMirror.Pass = Pass;\n CodeMirror.signal = signal;\n CodeMirror.Line = Line;\n CodeMirror.changeEnd = changeEnd;\n CodeMirror.scrollbarModel = scrollbarModel;\n CodeMirror.Pos = Pos;\n CodeMirror.cmpPos = cmp;\n CodeMirror.modes = modes;\n CodeMirror.mimeModes = mimeModes;\n CodeMirror.resolveMode = resolveMode;\n CodeMirror.getMode = getMode;\n CodeMirror.modeExtensions = modeExtensions;\n CodeMirror.extendMode = extendMode;\n CodeMirror.copyState = copyState;\n CodeMirror.startState = startState;\n CodeMirror.innerMode = innerMode;\n CodeMirror.commands = commands;\n CodeMirror.keyMap = keyMap;\n CodeMirror.keyName = keyName;\n CodeMirror.isModifierKey = isModifierKey;\n CodeMirror.lookupKey = lookupKey;\n CodeMirror.normalizeKeyMap = normalizeKeyMap;\n CodeMirror.StringStream = StringStream;\n CodeMirror.SharedTextMarker = SharedTextMarker;\n CodeMirror.TextMarker = TextMarker;\n CodeMirror.LineWidget = LineWidget;\n CodeMirror.e_preventDefault = e_preventDefault;\n CodeMirror.e_stopPropagation = e_stopPropagation;\n CodeMirror.e_stop = e_stop;\n CodeMirror.addClass = addClass;\n CodeMirror.contains = contains;\n CodeMirror.rmClass = rmClass;\n CodeMirror.keyNames = keyNames;\n }\n\n // EDITOR CONSTRUCTOR\n\n defineOptions(CodeMirror);\n\n addEditorMethods(CodeMirror);\n\n // Set up methods on CodeMirror's prototype to redirect to the editor's document.\n var dontDelegate = \"iter insert remove copy getEditor constructor\".split(\" \");\n for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)\n { CodeMirror.prototype[prop] = (function(method) {\n return function() {return method.apply(this.doc, arguments)}\n })(Doc.prototype[prop]); } }\n\n eventMixin(Doc);\n CodeMirror.inputStyles = {\"textarea\": TextareaInput, \"contenteditable\": ContentEditableInput};\n\n // Extra arguments are stored as the mode's dependencies, which is\n // used by (legacy) mechanisms like loadmode.js to automatically\n // load a mode. (Preferred mechanism is the require/define calls.)\n CodeMirror.defineMode = function(name/*, mode, …*/) {\n if (!CodeMirror.defaults.mode && name != \"null\") { CodeMirror.defaults.mode = name; }\n defineMode.apply(this, arguments);\n };\n\n CodeMirror.defineMIME = defineMIME;\n\n // Minimal default mode.\n CodeMirror.defineMode(\"null\", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });\n CodeMirror.defineMIME(\"text/plain\", \"null\");\n\n // EXTENSIONS\n\n CodeMirror.defineExtension = function (name, func) {\n CodeMirror.prototype[name] = func;\n };\n CodeMirror.defineDocExtension = function (name, func) {\n Doc.prototype[name] = func;\n };\n\n CodeMirror.fromTextArea = fromTextArea;\n\n addLegacyProps(CodeMirror);\n\n CodeMirror.version = \"5.42.0\";\n\n return CodeMirror;\n\n})));\n\n},{}],18:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"css\", function(config, parserConfig) {\n var inline = parserConfig.inline\n if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode(\"text/css\");\n\n var indentUnit = config.indentUnit,\n tokenHooks = parserConfig.tokenHooks,\n documentTypes = parserConfig.documentTypes || {},\n mediaTypes = parserConfig.mediaTypes || {},\n mediaFeatures = parserConfig.mediaFeatures || {},\n mediaValueKeywords = parserConfig.mediaValueKeywords || {},\n propertyKeywords = parserConfig.propertyKeywords || {},\n nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},\n fontProperties = parserConfig.fontProperties || {},\n counterDescriptors = parserConfig.counterDescriptors || {},\n colorKeywords = parserConfig.colorKeywords || {},\n valueKeywords = parserConfig.valueKeywords || {},\n allowNested = parserConfig.allowNested,\n lineComment = parserConfig.lineComment,\n supportsAtComponent = parserConfig.supportsAtComponent === true;\n\n var type, override;\n function ret(style, tp) { type = tp; return style; }\n\n // Tokenizers\n\n function tokenBase(stream, state) {\n var ch = stream.next();\n if (tokenHooks[ch]) {\n var result = tokenHooks[ch](stream, state);\n if (result !== false) return result;\n }\n if (ch == \"@\") {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"def\", stream.current());\n } else if (ch == \"=\" || (ch == \"~\" || ch == \"|\") && stream.eat(\"=\")) {\n return ret(null, \"compare\");\n } else if (ch == \"\\\"\" || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n } else if (ch == \"#\") {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"atom\", \"hash\");\n } else if (ch == \"!\") {\n stream.match(/^\\s*\\w*/);\n return ret(\"keyword\", \"important\");\n } else if (/\\d/.test(ch) || ch == \".\" && stream.eat(/\\d/)) {\n stream.eatWhile(/[\\w.%]/);\n return ret(\"number\", \"unit\");\n } else if (ch === \"-\") {\n if (/[\\d.]/.test(stream.peek())) {\n stream.eatWhile(/[\\w.%]/);\n return ret(\"number\", \"unit\");\n } else if (stream.match(/^-[\\w\\\\\\-]+/)) {\n stream.eatWhile(/[\\w\\\\\\-]/);\n if (stream.match(/^\\s*:/, false))\n return ret(\"variable-2\", \"variable-definition\");\n return ret(\"variable-2\", \"variable\");\n } else if (stream.match(/^\\w+-/)) {\n return ret(\"meta\", \"meta\");\n }\n } else if (/[,+>*\\/]/.test(ch)) {\n return ret(null, \"select-op\");\n } else if (ch == \".\" && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {\n return ret(\"qualifier\", \"qualifier\");\n } else if (/[:;{}\\[\\]\\(\\)]/.test(ch)) {\n return ret(null, ch);\n } else if (((ch == \"u\" || ch == \"U\") && stream.match(/rl(-prefix)?\\(/i)) ||\n ((ch == \"d\" || ch == \"D\") && stream.match(\"omain(\", true, true)) ||\n ((ch == \"r\" || ch == \"R\") && stream.match(\"egexp(\", true, true))) {\n stream.backUp(1);\n state.tokenize = tokenParenthesized;\n return ret(\"property\", \"word\");\n } else if (/[\\w\\\\\\-]/.test(ch)) {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"property\", \"word\");\n } else {\n return ret(null, null);\n }\n }\n\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped) {\n if (quote == \")\") stream.backUp(1);\n break;\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n if (ch == quote || !escaped && quote != \")\") state.tokenize = null;\n return ret(\"string\", \"string\");\n };\n }\n\n function tokenParenthesized(stream, state) {\n stream.next(); // Must be '('\n if (!stream.match(/\\s*[\\\"\\')]/, false))\n state.tokenize = tokenString(\")\");\n else\n state.tokenize = null;\n return ret(null, \"(\");\n }\n\n // Context management\n\n function Context(type, indent, prev) {\n this.type = type;\n this.indent = indent;\n this.prev = prev;\n }\n\n function pushContext(state, stream, type, indent) {\n state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);\n return type;\n }\n\n function popContext(state) {\n if (state.context.prev)\n state.context = state.context.prev;\n return state.context.type;\n }\n\n function pass(type, stream, state) {\n return states[state.context.type](type, stream, state);\n }\n function popAndPass(type, stream, state, n) {\n for (var i = n || 1; i > 0; i--)\n state.context = state.context.prev;\n return pass(type, stream, state);\n }\n\n // Parser\n\n function wordAsValue(stream) {\n var word = stream.current().toLowerCase();\n if (valueKeywords.hasOwnProperty(word))\n override = \"atom\";\n else if (colorKeywords.hasOwnProperty(word))\n override = \"keyword\";\n else\n override = \"variable\";\n }\n\n var states = {};\n\n states.top = function(type, stream, state) {\n if (type == \"{\") {\n return pushContext(state, stream, \"block\");\n } else if (type == \"}\" && state.context.prev) {\n return popContext(state);\n } else if (supportsAtComponent && /@component/i.test(type)) {\n return pushContext(state, stream, \"atComponentBlock\");\n } else if (/^@(-moz-)?document$/i.test(type)) {\n return pushContext(state, stream, \"documentTypes\");\n } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {\n return pushContext(state, stream, \"atBlock\");\n } else if (/^@(font-face|counter-style)/i.test(type)) {\n state.stateArg = type;\n return \"restricted_atBlock_before\";\n } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {\n return \"keyframes\";\n } else if (type && type.charAt(0) == \"@\") {\n return pushContext(state, stream, \"at\");\n } else if (type == \"hash\") {\n override = \"builtin\";\n } else if (type == \"word\") {\n override = \"tag\";\n } else if (type == \"variable-definition\") {\n return \"maybeprop\";\n } else if (type == \"interpolation\") {\n return pushContext(state, stream, \"interpolation\");\n } else if (type == \":\") {\n return \"pseudo\";\n } else if (allowNested && type == \"(\") {\n return pushContext(state, stream, \"parens\");\n }\n return state.context.type;\n };\n\n states.block = function(type, stream, state) {\n if (type == \"word\") {\n var word = stream.current().toLowerCase();\n if (propertyKeywords.hasOwnProperty(word)) {\n override = \"property\";\n return \"maybeprop\";\n } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {\n override = \"string-2\";\n return \"maybeprop\";\n } else if (allowNested) {\n override = stream.match(/^\\s*:(?:\\s|$)/, false) ? \"property\" : \"tag\";\n return \"block\";\n } else {\n override += \" error\";\n return \"maybeprop\";\n }\n } else if (type == \"meta\") {\n return \"block\";\n } else if (!allowNested && (type == \"hash\" || type == \"qualifier\")) {\n override = \"error\";\n return \"block\";\n } else {\n return states.top(type, stream, state);\n }\n };\n\n states.maybeprop = function(type, stream, state) {\n if (type == \":\") return pushContext(state, stream, \"prop\");\n return pass(type, stream, state);\n };\n\n states.prop = function(type, stream, state) {\n if (type == \";\") return popContext(state);\n if (type == \"{\" && allowNested) return pushContext(state, stream, \"propBlock\");\n if (type == \"}\" || type == \"{\") return popAndPass(type, stream, state);\n if (type == \"(\") return pushContext(state, stream, \"parens\");\n\n if (type == \"hash\" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {\n override += \" error\";\n } else if (type == \"word\") {\n wordAsValue(stream);\n } else if (type == \"interpolation\") {\n return pushContext(state, stream, \"interpolation\");\n }\n return \"prop\";\n };\n\n states.propBlock = function(type, _stream, state) {\n if (type == \"}\") return popContext(state);\n if (type == \"word\") { override = \"property\"; return \"maybeprop\"; }\n return state.context.type;\n };\n\n states.parens = function(type, stream, state) {\n if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state);\n if (type == \")\") return popContext(state);\n if (type == \"(\") return pushContext(state, stream, \"parens\");\n if (type == \"interpolation\") return pushContext(state, stream, \"interpolation\");\n if (type == \"word\") wordAsValue(stream);\n return \"parens\";\n };\n\n states.pseudo = function(type, stream, state) {\n if (type == \"meta\") return \"pseudo\";\n\n if (type == \"word\") {\n override = \"variable-3\";\n return state.context.type;\n }\n return pass(type, stream, state);\n };\n\n states.documentTypes = function(type, stream, state) {\n if (type == \"word\" && documentTypes.hasOwnProperty(stream.current())) {\n override = \"tag\";\n return state.context.type;\n } else {\n return states.atBlock(type, stream, state);\n }\n };\n\n states.atBlock = function(type, stream, state) {\n if (type == \"(\") return pushContext(state, stream, \"atBlock_parens\");\n if (type == \"}\" || type == \";\") return popAndPass(type, stream, state);\n if (type == \"{\") return popContext(state) && pushContext(state, stream, allowNested ? \"block\" : \"top\");\n\n if (type == \"interpolation\") return pushContext(state, stream, \"interpolation\");\n\n if (type == \"word\") {\n var word = stream.current().toLowerCase();\n if (word == \"only\" || word == \"not\" || word == \"and\" || word == \"or\")\n override = \"keyword\";\n else if (mediaTypes.hasOwnProperty(word))\n override = \"attribute\";\n else if (mediaFeatures.hasOwnProperty(word))\n override = \"property\";\n else if (mediaValueKeywords.hasOwnProperty(word))\n override = \"keyword\";\n else if (propertyKeywords.hasOwnProperty(word))\n override = \"property\";\n else if (nonStandardPropertyKeywords.hasOwnProperty(word))\n override = \"string-2\";\n else if (valueKeywords.hasOwnProperty(word))\n override = \"atom\";\n else if (colorKeywords.hasOwnProperty(word))\n override = \"keyword\";\n else\n override = \"error\";\n }\n return state.context.type;\n };\n\n states.atComponentBlock = function(type, stream, state) {\n if (type == \"}\")\n return popAndPass(type, stream, state);\n if (type == \"{\")\n return popContext(state) && pushContext(state, stream, allowNested ? \"block\" : \"top\", false);\n if (type == \"word\")\n override = \"error\";\n return state.context.type;\n };\n\n states.atBlock_parens = function(type, stream, state) {\n if (type == \")\") return popContext(state);\n if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state, 2);\n return states.atBlock(type, stream, state);\n };\n\n states.restricted_atBlock_before = function(type, stream, state) {\n if (type == \"{\")\n return pushContext(state, stream, \"restricted_atBlock\");\n if (type == \"word\" && state.stateArg == \"@counter-style\") {\n override = \"variable\";\n return \"restricted_atBlock_before\";\n }\n return pass(type, stream, state);\n };\n\n states.restricted_atBlock = function(type, stream, state) {\n if (type == \"}\") {\n state.stateArg = null;\n return popContext(state);\n }\n if (type == \"word\") {\n if ((state.stateArg == \"@font-face\" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||\n (state.stateArg == \"@counter-style\" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))\n override = \"error\";\n else\n override = \"property\";\n return \"maybeprop\";\n }\n return \"restricted_atBlock\";\n };\n\n states.keyframes = function(type, stream, state) {\n if (type == \"word\") { override = \"variable\"; return \"keyframes\"; }\n if (type == \"{\") return pushContext(state, stream, \"top\");\n return pass(type, stream, state);\n };\n\n states.at = function(type, stream, state) {\n if (type == \";\") return popContext(state);\n if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state);\n if (type == \"word\") override = \"tag\";\n else if (type == \"hash\") override = \"builtin\";\n return \"at\";\n };\n\n states.interpolation = function(type, stream, state) {\n if (type == \"}\") return popContext(state);\n if (type == \"{\" || type == \";\") return popAndPass(type, stream, state);\n if (type == \"word\") override = \"variable\";\n else if (type != \"variable\" && type != \"(\" && type != \")\") override = \"error\";\n return \"interpolation\";\n };\n\n return {\n startState: function(base) {\n return {tokenize: null,\n state: inline ? \"block\" : \"top\",\n stateArg: null,\n context: new Context(inline ? \"block\" : \"top\", base || 0, null)};\n },\n\n token: function(stream, state) {\n if (!state.tokenize && stream.eatSpace()) return null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style && typeof style == \"object\") {\n type = style[1];\n style = style[0];\n }\n override = style;\n if (type != \"comment\")\n state.state = states[state.state](type, stream, state);\n return override;\n },\n\n indent: function(state, textAfter) {\n var cx = state.context, ch = textAfter && textAfter.charAt(0);\n var indent = cx.indent;\n if (cx.type == \"prop\" && (ch == \"}\" || ch == \")\")) cx = cx.prev;\n if (cx.prev) {\n if (ch == \"}\" && (cx.type == \"block\" || cx.type == \"top\" ||\n cx.type == \"interpolation\" || cx.type == \"restricted_atBlock\")) {\n // Resume indentation from parent context.\n cx = cx.prev;\n indent = cx.indent;\n } else if (ch == \")\" && (cx.type == \"parens\" || cx.type == \"atBlock_parens\") ||\n ch == \"{\" && (cx.type == \"at\" || cx.type == \"atBlock\")) {\n // Dedent relative to current context.\n indent = Math.max(0, cx.indent - indentUnit);\n }\n }\n return indent;\n },\n\n electricChars: \"}\",\n blockCommentStart: \"/*\",\n blockCommentEnd: \"*/\",\n blockCommentContinue: \" * \",\n lineComment: lineComment,\n fold: \"brace\"\n };\n});\n\n function keySet(array) {\n var keys = {};\n for (var i = 0; i < array.length; ++i) {\n keys[array[i].toLowerCase()] = true;\n }\n return keys;\n }\n\n var documentTypes_ = [\n \"domain\", \"regexp\", \"url\", \"url-prefix\"\n ], documentTypes = keySet(documentTypes_);\n\n var mediaTypes_ = [\n \"all\", \"aural\", \"braille\", \"handheld\", \"print\", \"projection\", \"screen\",\n \"tty\", \"tv\", \"embossed\"\n ], mediaTypes = keySet(mediaTypes_);\n\n var mediaFeatures_ = [\n \"width\", \"min-width\", \"max-width\", \"height\", \"min-height\", \"max-height\",\n \"device-width\", \"min-device-width\", \"max-device-width\", \"device-height\",\n \"min-device-height\", \"max-device-height\", \"aspect-ratio\",\n \"min-aspect-ratio\", \"max-aspect-ratio\", \"device-aspect-ratio\",\n \"min-device-aspect-ratio\", \"max-device-aspect-ratio\", \"color\", \"min-color\",\n \"max-color\", \"color-index\", \"min-color-index\", \"max-color-index\",\n \"monochrome\", \"min-monochrome\", \"max-monochrome\", \"resolution\",\n \"min-resolution\", \"max-resolution\", \"scan\", \"grid\", \"orientation\",\n \"device-pixel-ratio\", \"min-device-pixel-ratio\", \"max-device-pixel-ratio\",\n \"pointer\", \"any-pointer\", \"hover\", \"any-hover\"\n ], mediaFeatures = keySet(mediaFeatures_);\n\n var mediaValueKeywords_ = [\n \"landscape\", \"portrait\", \"none\", \"coarse\", \"fine\", \"on-demand\", \"hover\",\n \"interlace\", \"progressive\"\n ], mediaValueKeywords = keySet(mediaValueKeywords_);\n\n var propertyKeywords_ = [\n \"align-content\", \"align-items\", \"align-self\", \"alignment-adjust\",\n \"alignment-baseline\", \"anchor-point\", \"animation\", \"animation-delay\",\n \"animation-direction\", \"animation-duration\", \"animation-fill-mode\",\n \"animation-iteration-count\", \"animation-name\", \"animation-play-state\",\n \"animation-timing-function\", \"appearance\", \"azimuth\", \"backface-visibility\",\n \"background\", \"background-attachment\", \"background-blend-mode\", \"background-clip\",\n \"background-color\", \"background-image\", \"background-origin\", \"background-position\",\n \"background-repeat\", \"background-size\", \"baseline-shift\", \"binding\",\n \"bleed\", \"bookmark-label\", \"bookmark-level\", \"bookmark-state\",\n \"bookmark-target\", \"border\", \"border-bottom\", \"border-bottom-color\",\n \"border-bottom-left-radius\", \"border-bottom-right-radius\",\n \"border-bottom-style\", \"border-bottom-width\", \"border-collapse\",\n \"border-color\", \"border-image\", \"border-image-outset\",\n \"border-image-repeat\", \"border-image-slice\", \"border-image-source\",\n \"border-image-width\", \"border-left\", \"border-left-color\",\n \"border-left-style\", \"border-left-width\", \"border-radius\", \"border-right\",\n \"border-right-color\", \"border-right-style\", \"border-right-width\",\n \"border-spacing\", \"border-style\", \"border-top\", \"border-top-color\",\n \"border-top-left-radius\", \"border-top-right-radius\", \"border-top-style\",\n \"border-top-width\", \"border-width\", \"bottom\", \"box-decoration-break\",\n \"box-shadow\", \"box-sizing\", \"break-after\", \"break-before\", \"break-inside\",\n \"caption-side\", \"caret-color\", \"clear\", \"clip\", \"color\", \"color-profile\", \"column-count\",\n \"column-fill\", \"column-gap\", \"column-rule\", \"column-rule-color\",\n \"column-rule-style\", \"column-rule-width\", \"column-span\", \"column-width\",\n \"columns\", \"content\", \"counter-increment\", \"counter-reset\", \"crop\", \"cue\",\n \"cue-after\", \"cue-before\", \"cursor\", \"direction\", \"display\",\n \"dominant-baseline\", \"drop-initial-after-adjust\",\n \"drop-initial-after-align\", \"drop-initial-before-adjust\",\n \"drop-initial-before-align\", \"drop-initial-size\", \"drop-initial-value\",\n \"elevation\", \"empty-cells\", \"fit\", \"fit-position\", \"flex\", \"flex-basis\",\n \"flex-direction\", \"flex-flow\", \"flex-grow\", \"flex-shrink\", \"flex-wrap\",\n \"float\", \"float-offset\", \"flow-from\", \"flow-into\", \"font\", \"font-feature-settings\",\n \"font-family\", \"font-kerning\", \"font-language-override\", \"font-size\", \"font-size-adjust\",\n \"font-stretch\", \"font-style\", \"font-synthesis\", \"font-variant\",\n \"font-variant-alternates\", \"font-variant-caps\", \"font-variant-east-asian\",\n \"font-variant-ligatures\", \"font-variant-numeric\", \"font-variant-position\",\n \"font-weight\", \"grid\", \"grid-area\", \"grid-auto-columns\", \"grid-auto-flow\",\n \"grid-auto-rows\", \"grid-column\", \"grid-column-end\", \"grid-column-gap\",\n \"grid-column-start\", \"grid-gap\", \"grid-row\", \"grid-row-end\", \"grid-row-gap\",\n \"grid-row-start\", \"grid-template\", \"grid-template-areas\", \"grid-template-columns\",\n \"grid-template-rows\", \"hanging-punctuation\", \"height\", \"hyphens\",\n \"icon\", \"image-orientation\", \"image-rendering\", \"image-resolution\",\n \"inline-box-align\", \"justify-content\", \"justify-items\", \"justify-self\", \"left\", \"letter-spacing\",\n \"line-break\", \"line-height\", \"line-stacking\", \"line-stacking-ruby\",\n \"line-stacking-shift\", \"line-stacking-strategy\", \"list-style\",\n \"list-style-image\", \"list-style-position\", \"list-style-type\", \"margin\",\n \"margin-bottom\", \"margin-left\", \"margin-right\", \"margin-top\",\n \"marks\", \"marquee-direction\", \"marquee-loop\",\n \"marquee-play-count\", \"marquee-speed\", \"marquee-style\", \"max-height\",\n \"max-width\", \"min-height\", \"min-width\", \"mix-blend-mode\", \"move-to\", \"nav-down\", \"nav-index\",\n \"nav-left\", \"nav-right\", \"nav-up\", \"object-fit\", \"object-position\",\n \"opacity\", \"order\", \"orphans\", \"outline\",\n \"outline-color\", \"outline-offset\", \"outline-style\", \"outline-width\",\n \"overflow\", \"overflow-style\", \"overflow-wrap\", \"overflow-x\", \"overflow-y\",\n \"padding\", \"padding-bottom\", \"padding-left\", \"padding-right\", \"padding-top\",\n \"page\", \"page-break-after\", \"page-break-before\", \"page-break-inside\",\n \"page-policy\", \"pause\", \"pause-after\", \"pause-before\", \"perspective\",\n \"perspective-origin\", \"pitch\", \"pitch-range\", \"place-content\", \"place-items\", \"place-self\", \"play-during\", \"position\",\n \"presentation-level\", \"punctuation-trim\", \"quotes\", \"region-break-after\",\n \"region-break-before\", \"region-break-inside\", \"region-fragment\",\n \"rendering-intent\", \"resize\", \"rest\", \"rest-after\", \"rest-before\", \"richness\",\n \"right\", \"rotation\", \"rotation-point\", \"ruby-align\", \"ruby-overhang\",\n \"ruby-position\", \"ruby-span\", \"shape-image-threshold\", \"shape-inside\", \"shape-margin\",\n \"shape-outside\", \"size\", \"speak\", \"speak-as\", \"speak-header\",\n \"speak-numeral\", \"speak-punctuation\", \"speech-rate\", \"stress\", \"string-set\",\n \"tab-size\", \"table-layout\", \"target\", \"target-name\", \"target-new\",\n \"target-position\", \"text-align\", \"text-align-last\", \"text-decoration\",\n \"text-decoration-color\", \"text-decoration-line\", \"text-decoration-skip\",\n \"text-decoration-style\", \"text-emphasis\", \"text-emphasis-color\",\n \"text-emphasis-position\", \"text-emphasis-style\", \"text-height\",\n \"text-indent\", \"text-justify\", \"text-outline\", \"text-overflow\", \"text-shadow\",\n \"text-size-adjust\", \"text-space-collapse\", \"text-transform\", \"text-underline-position\",\n \"text-wrap\", \"top\", \"transform\", \"transform-origin\", \"transform-style\",\n \"transition\", \"transition-delay\", \"transition-duration\",\n \"transition-property\", \"transition-timing-function\", \"unicode-bidi\",\n \"user-select\", \"vertical-align\", \"visibility\", \"voice-balance\", \"voice-duration\",\n \"voice-family\", \"voice-pitch\", \"voice-range\", \"voice-rate\", \"voice-stress\",\n \"voice-volume\", \"volume\", \"white-space\", \"widows\", \"width\", \"will-change\", \"word-break\",\n \"word-spacing\", \"word-wrap\", \"z-index\",\n // SVG-specific\n \"clip-path\", \"clip-rule\", \"mask\", \"enable-background\", \"filter\", \"flood-color\",\n \"flood-opacity\", \"lighting-color\", \"stop-color\", \"stop-opacity\", \"pointer-events\",\n \"color-interpolation\", \"color-interpolation-filters\",\n \"color-rendering\", \"fill\", \"fill-opacity\", \"fill-rule\", \"image-rendering\",\n \"marker\", \"marker-end\", \"marker-mid\", \"marker-start\", \"shape-rendering\", \"stroke\",\n \"stroke-dasharray\", \"stroke-dashoffset\", \"stroke-linecap\", \"stroke-linejoin\",\n \"stroke-miterlimit\", \"stroke-opacity\", \"stroke-width\", \"text-rendering\",\n \"baseline-shift\", \"dominant-baseline\", \"glyph-orientation-horizontal\",\n \"glyph-orientation-vertical\", \"text-anchor\", \"writing-mode\"\n ], propertyKeywords = keySet(propertyKeywords_);\n\n var nonStandardPropertyKeywords_ = [\n \"scrollbar-arrow-color\", \"scrollbar-base-color\", \"scrollbar-dark-shadow-color\",\n \"scrollbar-face-color\", \"scrollbar-highlight-color\", \"scrollbar-shadow-color\",\n \"scrollbar-3d-light-color\", \"scrollbar-track-color\", \"shape-inside\",\n \"searchfield-cancel-button\", \"searchfield-decoration\", \"searchfield-results-button\",\n \"searchfield-results-decoration\", \"zoom\"\n ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);\n\n var fontProperties_ = [\n \"font-family\", \"src\", \"unicode-range\", \"font-variant\", \"font-feature-settings\",\n \"font-stretch\", \"font-weight\", \"font-style\"\n ], fontProperties = keySet(fontProperties_);\n\n var counterDescriptors_ = [\n \"additive-symbols\", \"fallback\", \"negative\", \"pad\", \"prefix\", \"range\",\n \"speak-as\", \"suffix\", \"symbols\", \"system\"\n ], counterDescriptors = keySet(counterDescriptors_);\n\n var colorKeywords_ = [\n \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\",\n \"bisque\", \"black\", \"blanchedalmond\", \"blue\", \"blueviolet\", \"brown\",\n \"burlywood\", \"cadetblue\", \"chartreuse\", \"chocolate\", \"coral\", \"cornflowerblue\",\n \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"darkcyan\", \"darkgoldenrod\",\n \"darkgray\", \"darkgreen\", \"darkkhaki\", \"darkmagenta\", \"darkolivegreen\",\n \"darkorange\", \"darkorchid\", \"darkred\", \"darksalmon\", \"darkseagreen\",\n \"darkslateblue\", \"darkslategray\", \"darkturquoise\", \"darkviolet\",\n \"deeppink\", \"deepskyblue\", \"dimgray\", \"dodgerblue\", \"firebrick\",\n \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\",\n \"gold\", \"goldenrod\", \"gray\", \"grey\", \"green\", \"greenyellow\", \"honeydew\",\n \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\",\n \"lavenderblush\", \"lawngreen\", \"lemonchiffon\", \"lightblue\", \"lightcoral\",\n \"lightcyan\", \"lightgoldenrodyellow\", \"lightgray\", \"lightgreen\", \"lightpink\",\n \"lightsalmon\", \"lightseagreen\", \"lightskyblue\", \"lightslategray\",\n \"lightsteelblue\", \"lightyellow\", \"lime\", \"limegreen\", \"linen\", \"magenta\",\n \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"mediumpurple\",\n \"mediumseagreen\", \"mediumslateblue\", \"mediumspringgreen\", \"mediumturquoise\",\n \"mediumvioletred\", \"midnightblue\", \"mintcream\", \"mistyrose\", \"moccasin\",\n \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\",\n \"orchid\", \"palegoldenrod\", \"palegreen\", \"paleturquoise\", \"palevioletred\",\n \"papayawhip\", \"peachpuff\", \"peru\", \"pink\", \"plum\", \"powderblue\",\n \"purple\", \"rebeccapurple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\",\n \"salmon\", \"sandybrown\", \"seagreen\", \"seashell\", \"sienna\", \"silver\", \"skyblue\",\n \"slateblue\", \"slategray\", \"snow\", \"springgreen\", \"steelblue\", \"tan\",\n \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\",\n \"whitesmoke\", \"yellow\", \"yellowgreen\"\n ], colorKeywords = keySet(colorKeywords_);\n\n var valueKeywords_ = [\n \"above\", \"absolute\", \"activeborder\", \"additive\", \"activecaption\", \"afar\",\n \"after-white-space\", \"ahead\", \"alias\", \"all\", \"all-scroll\", \"alphabetic\", \"alternate\",\n \"always\", \"amharic\", \"amharic-abegede\", \"antialiased\", \"appworkspace\",\n \"arabic-indic\", \"armenian\", \"asterisks\", \"attr\", \"auto\", \"auto-flow\", \"avoid\", \"avoid-column\", \"avoid-page\",\n \"avoid-region\", \"background\", \"backwards\", \"baseline\", \"below\", \"bidi-override\", \"binary\",\n \"bengali\", \"blink\", \"block\", \"block-axis\", \"bold\", \"bolder\", \"border\", \"border-box\",\n \"both\", \"bottom\", \"break\", \"break-all\", \"break-word\", \"bullets\", \"button\", \"button-bevel\",\n \"buttonface\", \"buttonhighlight\", \"buttonshadow\", \"buttontext\", \"calc\", \"cambodian\",\n \"capitalize\", \"caps-lock-indicator\", \"caption\", \"captiontext\", \"caret\",\n \"cell\", \"center\", \"checkbox\", \"circle\", \"cjk-decimal\", \"cjk-earthly-branch\",\n \"cjk-heavenly-stem\", \"cjk-ideographic\", \"clear\", \"clip\", \"close-quote\",\n \"col-resize\", \"collapse\", \"color\", \"color-burn\", \"color-dodge\", \"column\", \"column-reverse\",\n \"compact\", \"condensed\", \"contain\", \"content\", \"contents\",\n \"content-box\", \"context-menu\", \"continuous\", \"copy\", \"counter\", \"counters\", \"cover\", \"crop\",\n \"cross\", \"crosshair\", \"currentcolor\", \"cursive\", \"cyclic\", \"darken\", \"dashed\", \"decimal\",\n \"decimal-leading-zero\", \"default\", \"default-button\", \"dense\", \"destination-atop\",\n \"destination-in\", \"destination-out\", \"destination-over\", \"devanagari\", \"difference\",\n \"disc\", \"discard\", \"disclosure-closed\", \"disclosure-open\", \"document\",\n \"dot-dash\", \"dot-dot-dash\",\n \"dotted\", \"double\", \"down\", \"e-resize\", \"ease\", \"ease-in\", \"ease-in-out\", \"ease-out\",\n \"element\", \"ellipse\", \"ellipsis\", \"embed\", \"end\", \"ethiopic\", \"ethiopic-abegede\",\n \"ethiopic-abegede-am-et\", \"ethiopic-abegede-gez\", \"ethiopic-abegede-ti-er\",\n \"ethiopic-abegede-ti-et\", \"ethiopic-halehame-aa-er\",\n \"ethiopic-halehame-aa-et\", \"ethiopic-halehame-am-et\",\n \"ethiopic-halehame-gez\", \"ethiopic-halehame-om-et\",\n \"ethiopic-halehame-sid-et\", \"ethiopic-halehame-so-et\",\n \"ethiopic-halehame-ti-er\", \"ethiopic-halehame-ti-et\", \"ethiopic-halehame-tig\",\n \"ethiopic-numeric\", \"ew-resize\", \"exclusion\", \"expanded\", \"extends\", \"extra-condensed\",\n \"extra-expanded\", \"fantasy\", \"fast\", \"fill\", \"fixed\", \"flat\", \"flex\", \"flex-end\", \"flex-start\", \"footnotes\",\n \"forwards\", \"from\", \"geometricPrecision\", \"georgian\", \"graytext\", \"grid\", \"groove\",\n \"gujarati\", \"gurmukhi\", \"hand\", \"hangul\", \"hangul-consonant\", \"hard-light\", \"hebrew\",\n \"help\", \"hidden\", \"hide\", \"higher\", \"highlight\", \"highlighttext\",\n \"hiragana\", \"hiragana-iroha\", \"horizontal\", \"hsl\", \"hsla\", \"hue\", \"icon\", \"ignore\",\n \"inactiveborder\", \"inactivecaption\", \"inactivecaptiontext\", \"infinite\",\n \"infobackground\", \"infotext\", \"inherit\", \"initial\", \"inline\", \"inline-axis\",\n \"inline-block\", \"inline-flex\", \"inline-grid\", \"inline-table\", \"inset\", \"inside\", \"intrinsic\", \"invert\",\n \"italic\", \"japanese-formal\", \"japanese-informal\", \"justify\", \"kannada\",\n \"katakana\", \"katakana-iroha\", \"keep-all\", \"khmer\",\n \"korean-hangul-formal\", \"korean-hanja-formal\", \"korean-hanja-informal\",\n \"landscape\", \"lao\", \"large\", \"larger\", \"left\", \"level\", \"lighter\", \"lighten\",\n \"line-through\", \"linear\", \"linear-gradient\", \"lines\", \"list-item\", \"listbox\", \"listitem\",\n \"local\", \"logical\", \"loud\", \"lower\", \"lower-alpha\", \"lower-armenian\",\n \"lower-greek\", \"lower-hexadecimal\", \"lower-latin\", \"lower-norwegian\",\n \"lower-roman\", \"lowercase\", \"ltr\", \"luminosity\", \"malayalam\", \"match\", \"matrix\", \"matrix3d\",\n \"media-controls-background\", \"media-current-time-display\",\n \"media-fullscreen-button\", \"media-mute-button\", \"media-play-button\",\n \"media-return-to-realtime-button\", \"media-rewind-button\",\n \"media-seek-back-button\", \"media-seek-forward-button\", \"media-slider\",\n \"media-sliderthumb\", \"media-time-remaining-display\", \"media-volume-slider\",\n \"media-volume-slider-container\", \"media-volume-sliderthumb\", \"medium\",\n \"menu\", \"menulist\", \"menulist-button\", \"menulist-text\",\n \"menulist-textfield\", \"menutext\", \"message-box\", \"middle\", \"min-intrinsic\",\n \"mix\", \"mongolian\", \"monospace\", \"move\", \"multiple\", \"multiply\", \"myanmar\", \"n-resize\",\n \"narrower\", \"ne-resize\", \"nesw-resize\", \"no-close-quote\", \"no-drop\",\n \"no-open-quote\", \"no-repeat\", \"none\", \"normal\", \"not-allowed\", \"nowrap\",\n \"ns-resize\", \"numbers\", \"numeric\", \"nw-resize\", \"nwse-resize\", \"oblique\", \"octal\", \"opacity\", \"open-quote\",\n \"optimizeLegibility\", \"optimizeSpeed\", \"oriya\", \"oromo\", \"outset\",\n \"outside\", \"outside-shape\", \"overlay\", \"overline\", \"padding\", \"padding-box\",\n \"painted\", \"page\", \"paused\", \"persian\", \"perspective\", \"plus-darker\", \"plus-lighter\",\n \"pointer\", \"polygon\", \"portrait\", \"pre\", \"pre-line\", \"pre-wrap\", \"preserve-3d\",\n \"progress\", \"push-button\", \"radial-gradient\", \"radio\", \"read-only\",\n \"read-write\", \"read-write-plaintext-only\", \"rectangle\", \"region\",\n \"relative\", \"repeat\", \"repeating-linear-gradient\",\n \"repeating-radial-gradient\", \"repeat-x\", \"repeat-y\", \"reset\", \"reverse\",\n \"rgb\", \"rgba\", \"ridge\", \"right\", \"rotate\", \"rotate3d\", \"rotateX\", \"rotateY\",\n \"rotateZ\", \"round\", \"row\", \"row-resize\", \"row-reverse\", \"rtl\", \"run-in\", \"running\",\n \"s-resize\", \"sans-serif\", \"saturation\", \"scale\", \"scale3d\", \"scaleX\", \"scaleY\", \"scaleZ\", \"screen\",\n \"scroll\", \"scrollbar\", \"scroll-position\", \"se-resize\", \"searchfield\",\n \"searchfield-cancel-button\", \"searchfield-decoration\",\n \"searchfield-results-button\", \"searchfield-results-decoration\", \"self-start\", \"self-end\",\n \"semi-condensed\", \"semi-expanded\", \"separate\", \"serif\", \"show\", \"sidama\",\n \"simp-chinese-formal\", \"simp-chinese-informal\", \"single\",\n \"skew\", \"skewX\", \"skewY\", \"skip-white-space\", \"slide\", \"slider-horizontal\",\n \"slider-vertical\", \"sliderthumb-horizontal\", \"sliderthumb-vertical\", \"slow\",\n \"small\", \"small-caps\", \"small-caption\", \"smaller\", \"soft-light\", \"solid\", \"somali\",\n \"source-atop\", \"source-in\", \"source-out\", \"source-over\", \"space\", \"space-around\", \"space-between\", \"space-evenly\", \"spell-out\", \"square\",\n \"square-button\", \"start\", \"static\", \"status-bar\", \"stretch\", \"stroke\", \"sub\",\n \"subpixel-antialiased\", \"super\", \"sw-resize\", \"symbolic\", \"symbols\", \"system-ui\", \"table\",\n \"table-caption\", \"table-cell\", \"table-column\", \"table-column-group\",\n \"table-footer-group\", \"table-header-group\", \"table-row\", \"table-row-group\",\n \"tamil\",\n \"telugu\", \"text\", \"text-bottom\", \"text-top\", \"textarea\", \"textfield\", \"thai\",\n \"thick\", \"thin\", \"threeddarkshadow\", \"threedface\", \"threedhighlight\",\n \"threedlightshadow\", \"threedshadow\", \"tibetan\", \"tigre\", \"tigrinya-er\",\n \"tigrinya-er-abegede\", \"tigrinya-et\", \"tigrinya-et-abegede\", \"to\", \"top\",\n \"trad-chinese-formal\", \"trad-chinese-informal\", \"transform\",\n \"translate\", \"translate3d\", \"translateX\", \"translateY\", \"translateZ\",\n \"transparent\", \"ultra-condensed\", \"ultra-expanded\", \"underline\", \"unset\", \"up\",\n \"upper-alpha\", \"upper-armenian\", \"upper-greek\", \"upper-hexadecimal\",\n \"upper-latin\", \"upper-norwegian\", \"upper-roman\", \"uppercase\", \"urdu\", \"url\",\n \"var\", \"vertical\", \"vertical-text\", \"visible\", \"visibleFill\", \"visiblePainted\",\n \"visibleStroke\", \"visual\", \"w-resize\", \"wait\", \"wave\", \"wider\",\n \"window\", \"windowframe\", \"windowtext\", \"words\", \"wrap\", \"wrap-reverse\", \"x-large\", \"x-small\", \"xor\",\n \"xx-large\", \"xx-small\"\n ], valueKeywords = keySet(valueKeywords_);\n\n var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)\n .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)\n .concat(valueKeywords_);\n CodeMirror.registerHelper(\"hintWords\", \"css\", allWords);\n\n function tokenCComment(stream, state) {\n var maybeEnd = false, ch;\n while ((ch = stream.next()) != null) {\n if (maybeEnd && ch == \"/\") {\n state.tokenize = null;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return [\"comment\", \"comment\"];\n }\n\n CodeMirror.defineMIME(\"text/css\", {\n documentTypes: documentTypes,\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n mediaValueKeywords: mediaValueKeywords,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n fontProperties: fontProperties,\n counterDescriptors: counterDescriptors,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n tokenHooks: {\n \"/\": function(stream, state) {\n if (!stream.eat(\"*\")) return false;\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n }\n },\n name: \"css\"\n });\n\n CodeMirror.defineMIME(\"text/x-scss\", {\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n mediaValueKeywords: mediaValueKeywords,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n fontProperties: fontProperties,\n allowNested: true,\n lineComment: \"//\",\n tokenHooks: {\n \"/\": function(stream, state) {\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return [\"comment\", \"comment\"];\n } else if (stream.eat(\"*\")) {\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n } else {\n return [\"operator\", \"operator\"];\n }\n },\n \":\": function(stream) {\n if (stream.match(/\\s*\\{/, false))\n return [null, null]\n return false;\n },\n \"$\": function(stream) {\n stream.match(/^[\\w-]+/);\n if (stream.match(/^\\s*:/, false))\n return [\"variable-2\", \"variable-definition\"];\n return [\"variable-2\", \"variable\"];\n },\n \"#\": function(stream) {\n if (!stream.eat(\"{\")) return false;\n return [null, \"interpolation\"];\n }\n },\n name: \"css\",\n helperType: \"scss\"\n });\n\n CodeMirror.defineMIME(\"text/x-less\", {\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n mediaValueKeywords: mediaValueKeywords,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n fontProperties: fontProperties,\n allowNested: true,\n lineComment: \"//\",\n tokenHooks: {\n \"/\": function(stream, state) {\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return [\"comment\", \"comment\"];\n } else if (stream.eat(\"*\")) {\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n } else {\n return [\"operator\", \"operator\"];\n }\n },\n \"@\": function(stream) {\n if (stream.eat(\"{\")) return [null, \"interpolation\"];\n if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\\b/i, false)) return false;\n stream.eatWhile(/[\\w\\\\\\-]/);\n if (stream.match(/^\\s*:/, false))\n return [\"variable-2\", \"variable-definition\"];\n return [\"variable-2\", \"variable\"];\n },\n \"&\": function() {\n return [\"atom\", \"atom\"];\n }\n },\n name: \"css\",\n helperType: \"less\"\n });\n\n CodeMirror.defineMIME(\"text/x-gss\", {\n documentTypes: documentTypes,\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n fontProperties: fontProperties,\n counterDescriptors: counterDescriptors,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n supportsAtComponent: true,\n tokenHooks: {\n \"/\": function(stream, state) {\n if (!stream.eat(\"*\")) return false;\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n }\n },\n name: \"css\",\n helperType: \"gss\"\n });\n\n});\n\n},{\"../../lib/codemirror\":17}],19:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"), require(\"../xml/xml\"), require(\"../javascript/javascript\"), require(\"../css/css\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\", \"../xml/xml\", \"../javascript/javascript\", \"../css/css\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n\n var defaultTags = {\n script: [\n [\"lang\", /(javascript|babel)/i, \"javascript\"],\n [\"type\", /^(?:text|application)\\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, \"javascript\"],\n [\"type\", /./, \"text/plain\"],\n [null, null, \"javascript\"]\n ],\n style: [\n [\"lang\", /^css$/i, \"css\"],\n [\"type\", /^(text\\/)?(x-)?(stylesheet|css)$/i, \"css\"],\n [\"type\", /./, \"text/plain\"],\n [null, null, \"css\"]\n ]\n };\n\n function maybeBackup(stream, pat, style) {\n var cur = stream.current(), close = cur.search(pat);\n if (close > -1) {\n stream.backUp(cur.length - close);\n } else if (cur.match(/<\\/?$/)) {\n stream.backUp(cur.length);\n if (!stream.match(pat, false)) stream.match(cur);\n }\n return style;\n }\n\n var attrRegexpCache = {};\n function getAttrRegexp(attr) {\n var regexp = attrRegexpCache[attr];\n if (regexp) return regexp;\n return attrRegexpCache[attr] = new RegExp(\"\\\\s+\" + attr + \"\\\\s*=\\\\s*('|\\\")?([^'\\\"]+)('|\\\")?\\\\s*\");\n }\n\n function getAttrValue(text, attr) {\n var match = text.match(getAttrRegexp(attr))\n return match ? /^\\s*(.*?)\\s*$/.exec(match[2])[1] : \"\"\n }\n\n function getTagRegexp(tagName, anchored) {\n return new RegExp((anchored ? \"^\" : \"\") + \"<\\/\\s*\" + tagName + \"\\s*>\", \"i\");\n }\n\n function addTags(from, to) {\n for (var tag in from) {\n var dest = to[tag] || (to[tag] = []);\n var source = from[tag];\n for (var i = source.length - 1; i >= 0; i--)\n dest.unshift(source[i])\n }\n }\n\n function findMatchingMode(tagInfo, tagText) {\n for (var i = 0; i < tagInfo.length; i++) {\n var spec = tagInfo[i];\n if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];\n }\n }\n\n CodeMirror.defineMode(\"htmlmixed\", function (config, parserConfig) {\n var htmlMode = CodeMirror.getMode(config, {\n name: \"xml\",\n htmlMode: true,\n multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,\n multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag\n });\n\n var tags = {};\n var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;\n addTags(defaultTags, tags);\n if (configTags) addTags(configTags, tags);\n if (configScript) for (var i = configScript.length - 1; i >= 0; i--)\n tags.script.unshift([\"type\", configScript[i].matches, configScript[i].mode])\n\n function html(stream, state) {\n var style = htmlMode.token(stream, state.htmlState), tag = /\\btag\\b/.test(style), tagName\n if (tag && !/[<>\\s\\/]/.test(stream.current()) &&\n (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) &&\n tags.hasOwnProperty(tagName)) {\n state.inTag = tagName + \" \"\n } else if (state.inTag && tag && />$/.test(stream.current())) {\n var inTag = /^([\\S]+) (.*)/.exec(state.inTag)\n state.inTag = null\n var modeSpec = stream.current() == \">\" && findMatchingMode(tags[inTag[1]], inTag[2])\n var mode = CodeMirror.getMode(config, modeSpec)\n var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);\n state.token = function (stream, state) {\n if (stream.match(endTagA, false)) {\n state.token = html;\n state.localState = state.localMode = null;\n return null;\n }\n return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));\n };\n state.localMode = mode;\n state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, \"\"));\n } else if (state.inTag) {\n state.inTag += stream.current()\n if (stream.eol()) state.inTag += \" \"\n }\n return style;\n };\n\n return {\n startState: function () {\n var state = CodeMirror.startState(htmlMode);\n return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};\n },\n\n copyState: function (state) {\n var local;\n if (state.localState) {\n local = CodeMirror.copyState(state.localMode, state.localState);\n }\n return {token: state.token, inTag: state.inTag,\n localMode: state.localMode, localState: local,\n htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};\n },\n\n token: function (stream, state) {\n return state.token(stream, state);\n },\n\n indent: function (state, textAfter, line) {\n if (!state.localMode || /^\\s*<\\//.test(textAfter))\n return htmlMode.indent(state.htmlState, textAfter);\n else if (state.localMode.indent)\n return state.localMode.indent(state.localState, textAfter, line);\n else\n return CodeMirror.Pass;\n },\n\n innerMode: function (state) {\n return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};\n }\n };\n }, \"xml\", \"javascript\", \"css\");\n\n CodeMirror.defineMIME(\"text/html\", \"htmlmixed\");\n});\n\n},{\"../../lib/codemirror\":17,\"../css/css\":18,\"../javascript/javascript\":20,\"../xml/xml\":21}],20:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nCodeMirror.defineMode(\"javascript\", function(config, parserConfig) {\n var indentUnit = config.indentUnit;\n var statementIndent = parserConfig.statementIndent;\n var jsonldMode = parserConfig.jsonld;\n var jsonMode = parserConfig.json || jsonldMode;\n var isTS = parserConfig.typescript;\n var wordRE = parserConfig.wordCharacters || /[\\w$\\xa1-\\uffff]/;\n\n // Tokenizer\n\n var keywords = function(){\n function kw(type) {return {type: type, style: \"keyword\"};}\n var A = kw(\"keyword a\"), B = kw(\"keyword b\"), C = kw(\"keyword c\"), D = kw(\"keyword d\");\n var operator = kw(\"operator\"), atom = {type: \"atom\", style: \"atom\"};\n\n return {\n \"if\": kw(\"if\"), \"while\": A, \"with\": A, \"else\": B, \"do\": B, \"try\": B, \"finally\": B,\n \"return\": D, \"break\": D, \"continue\": D, \"new\": kw(\"new\"), \"delete\": C, \"void\": C, \"throw\": C,\n \"debugger\": kw(\"debugger\"), \"var\": kw(\"var\"), \"const\": kw(\"var\"), \"let\": kw(\"var\"),\n \"function\": kw(\"function\"), \"catch\": kw(\"catch\"),\n \"for\": kw(\"for\"), \"switch\": kw(\"switch\"), \"case\": kw(\"case\"), \"default\": kw(\"default\"),\n \"in\": operator, \"typeof\": operator, \"instanceof\": operator,\n \"true\": atom, \"false\": atom, \"null\": atom, \"undefined\": atom, \"NaN\": atom, \"Infinity\": atom,\n \"this\": kw(\"this\"), \"class\": kw(\"class\"), \"super\": kw(\"atom\"),\n \"yield\": C, \"export\": kw(\"export\"), \"import\": kw(\"import\"), \"extends\": C,\n \"await\": C\n };\n }();\n\n var isOperatorChar = /[+\\-*&%=<>!?|~^@]/;\n var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)\"/;\n\n function readRegexp(stream) {\n var escaped = false, next, inSet = false;\n while ((next = stream.next()) != null) {\n if (!escaped) {\n if (next == \"/\" && !inSet) return;\n if (next == \"[\") inSet = true;\n else if (inSet && next == \"]\") inSet = false;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n }\n\n // Used as scratch variables to communicate multiple values without\n // consing up tons of objects.\n var type, content;\n function ret(tp, style, cont) {\n type = tp; content = cont;\n return style;\n }\n function tokenBase(stream, state) {\n var ch = stream.next();\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n } else if (ch == \".\" && stream.match(/^\\d+(?:[eE][+\\-]?\\d+)?/)) {\n return ret(\"number\", \"number\");\n } else if (ch == \".\" && stream.match(\"..\")) {\n return ret(\"spread\", \"meta\");\n } else if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n return ret(ch);\n } else if (ch == \"=\" && stream.eat(\">\")) {\n return ret(\"=>\", \"operator\");\n } else if (ch == \"0\" && stream.match(/^(?:x[\\da-f]+|o[0-7]+|b[01]+)n?/i)) {\n return ret(\"number\", \"number\");\n } else if (/\\d/.test(ch)) {\n stream.match(/^\\d*(?:n|(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)?/);\n return ret(\"number\", \"number\");\n } else if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n } else if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return ret(\"comment\", \"comment\");\n } else if (expressionAllowed(stream, state, 1)) {\n readRegexp(stream);\n stream.match(/^\\b(([gimyus])(?![gimyus]*\\2))+\\b/);\n return ret(\"regexp\", \"string-2\");\n } else {\n stream.eat(\"=\");\n return ret(\"operator\", \"operator\", stream.current());\n }\n } else if (ch == \"`\") {\n state.tokenize = tokenQuasi;\n return tokenQuasi(stream, state);\n } else if (ch == \"#\") {\n stream.skipToEnd();\n return ret(\"error\", \"error\");\n } else if (isOperatorChar.test(ch)) {\n if (ch != \">\" || !state.lexical || state.lexical.type != \">\") {\n if (stream.eat(\"=\")) {\n if (ch == \"!\" || ch == \"=\") stream.eat(\"=\")\n } else if (/[<>*+\\-]/.test(ch)) {\n stream.eat(ch)\n if (ch == \">\") stream.eat(ch)\n }\n }\n return ret(\"operator\", \"operator\", stream.current());\n } else if (wordRE.test(ch)) {\n stream.eatWhile(wordRE);\n var word = stream.current()\n if (state.lastType != \".\") {\n if (keywords.propertyIsEnumerable(word)) {\n var kw = keywords[word]\n return ret(kw.type, kw.style, word)\n }\n if (word == \"async\" && stream.match(/^(\\s|\\/\\*.*?\\*\\/)*[\\[\\(\\w]/, false))\n return ret(\"async\", \"keyword\", word)\n }\n return ret(\"variable\", \"variable\", word)\n }\n }\n\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next;\n if (jsonldMode && stream.peek() == \"@\" && stream.match(isJsonldKeyword)){\n state.tokenize = tokenBase;\n return ret(\"jsonld-keyword\", \"meta\");\n }\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) break;\n escaped = !escaped && next == \"\\\\\";\n }\n if (!escaped) state.tokenize = tokenBase;\n return ret(\"string\", \"string\");\n };\n }\n\n function tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return ret(\"comment\", \"comment\");\n }\n\n function tokenQuasi(stream, state) {\n var escaped = false, next;\n while ((next = stream.next()) != null) {\n if (!escaped && (next == \"`\" || next == \"$\" && stream.eat(\"{\"))) {\n state.tokenize = tokenBase;\n break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n return ret(\"quasi\", \"string-2\", stream.current());\n }\n\n var brackets = \"([{}])\";\n // This is a crude lookahead trick to try and notice that we're\n // parsing the argument patterns for a fat-arrow function before we\n // actually hit the arrow token. It only works if the arrow is on\n // the same line as the arguments and there's no strange noise\n // (comments) in between. Fallback is to only notice when we hit the\n // arrow, and not declare the arguments as locals for the arrow\n // body.\n function findFatArrow(stream, state) {\n if (state.fatArrowAt) state.fatArrowAt = null;\n var arrow = stream.string.indexOf(\"=>\", stream.start);\n if (arrow < 0) return;\n\n if (isTS) { // Try to skip TypeScript return type declarations after the arguments\n var m = /:\\s*(?:\\w+(?:<[^>]*>|\\[\\])?|\\{[^}]*\\})\\s*$/.exec(stream.string.slice(stream.start, arrow))\n if (m) arrow = m.index\n }\n\n var depth = 0, sawSomething = false;\n for (var pos = arrow - 1; pos >= 0; --pos) {\n var ch = stream.string.charAt(pos);\n var bracket = brackets.indexOf(ch);\n if (bracket >= 0 && bracket < 3) {\n if (!depth) { ++pos; break; }\n if (--depth == 0) { if (ch == \"(\") sawSomething = true; break; }\n } else if (bracket >= 3 && bracket < 6) {\n ++depth;\n } else if (wordRE.test(ch)) {\n sawSomething = true;\n } else if (/[\"'\\/]/.test(ch)) {\n return;\n } else if (sawSomething && !depth) {\n ++pos;\n break;\n }\n }\n if (sawSomething && !depth) state.fatArrowAt = pos;\n }\n\n // Parser\n\n var atomicTypes = {\"atom\": true, \"number\": true, \"variable\": true, \"string\": true, \"regexp\": true, \"this\": true, \"jsonld-keyword\": true};\n\n function JSLexical(indented, column, type, align, prev, info) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.prev = prev;\n this.info = info;\n if (align != null) this.align = align;\n }\n\n function inScope(state, varname) {\n for (var v = state.localVars; v; v = v.next)\n if (v.name == varname) return true;\n for (var cx = state.context; cx; cx = cx.prev) {\n for (var v = cx.vars; v; v = v.next)\n if (v.name == varname) return true;\n }\n }\n\n function parseJS(state, style, type, content, stream) {\n var cc = state.cc;\n // Communicate our context to the combinators.\n // (Less wasteful than consing up a hundred closures on every call.)\n cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;\n\n if (!state.lexical.hasOwnProperty(\"align\"))\n state.lexical.align = true;\n\n while(true) {\n var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;\n if (combinator(type, content)) {\n while(cc.length && cc[cc.length - 1].lex)\n cc.pop()();\n if (cx.marked) return cx.marked;\n if (type == \"variable\" && inScope(state, content)) return \"variable-2\";\n return style;\n }\n }\n }\n\n // Combinator utils\n\n var cx = {state: null, column: null, marked: null, cc: null};\n function pass() {\n for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);\n }\n function cont() {\n pass.apply(null, arguments);\n return true;\n }\n function inList(name, list) {\n for (var v = list; v; v = v.next) if (v.name == name) return true\n return false;\n }\n function register(varname) {\n var state = cx.state;\n cx.marked = \"def\";\n if (state.context) {\n if (state.lexical.info == \"var\" && state.context && state.context.block) {\n // FIXME function decls are also not block scoped\n var newContext = registerVarScoped(varname, state.context)\n if (newContext != null) {\n state.context = newContext\n return\n }\n } else if (!inList(varname, state.localVars)) {\n state.localVars = new Var(varname, state.localVars)\n return\n }\n }\n // Fall through means this is global\n if (parserConfig.globalVars && !inList(varname, state.globalVars))\n state.globalVars = new Var(varname, state.globalVars)\n }\n function registerVarScoped(varname, context) {\n if (!context) {\n return null\n } else if (context.block) {\n var inner = registerVarScoped(varname, context.prev)\n if (!inner) return null\n if (inner == context.prev) return context\n return new Context(inner, context.vars, true)\n } else if (inList(varname, context.vars)) {\n return context\n } else {\n return new Context(context.prev, new Var(varname, context.vars), false)\n }\n }\n\n function isModifier(name) {\n return name == \"public\" || name == \"private\" || name == \"protected\" || name == \"abstract\" || name == \"readonly\"\n }\n\n // Combinators\n\n function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }\n function Var(name, next) { this.name = name; this.next = next }\n\n var defaultVars = new Var(\"this\", new Var(\"arguments\", null))\n function pushcontext() {\n cx.state.context = new Context(cx.state.context, cx.state.localVars, false)\n cx.state.localVars = defaultVars\n }\n function pushblockcontext() {\n cx.state.context = new Context(cx.state.context, cx.state.localVars, true)\n cx.state.localVars = null\n }\n function popcontext() {\n cx.state.localVars = cx.state.context.vars\n cx.state.context = cx.state.context.prev\n }\n popcontext.lex = true\n function pushlex(type, info) {\n var result = function() {\n var state = cx.state, indent = state.indented;\n if (state.lexical.type == \"stat\") indent = state.lexical.indented;\n else for (var outer = state.lexical; outer && outer.type == \")\" && outer.align; outer = outer.prev)\n indent = outer.indented;\n state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);\n };\n result.lex = true;\n return result;\n }\n function poplex() {\n var state = cx.state;\n if (state.lexical.prev) {\n if (state.lexical.type == \")\")\n state.indented = state.lexical.indented;\n state.lexical = state.lexical.prev;\n }\n }\n poplex.lex = true;\n\n function expect(wanted) {\n function exp(type) {\n if (type == wanted) return cont();\n else if (wanted == \";\" || type == \"}\" || type == \")\" || type == \"]\") return pass();\n else return cont(exp);\n };\n return exp;\n }\n\n function statement(type, value) {\n if (type == \"var\") return cont(pushlex(\"vardef\", value), vardef, expect(\";\"), poplex);\n if (type == \"keyword a\") return cont(pushlex(\"form\"), parenExpr, statement, poplex);\n if (type == \"keyword b\") return cont(pushlex(\"form\"), statement, poplex);\n if (type == \"keyword d\") return cx.stream.match(/^\\s*$/, false) ? cont() : cont(pushlex(\"stat\"), maybeexpression, expect(\";\"), poplex);\n if (type == \"debugger\") return cont(expect(\";\"));\n if (type == \"{\") return cont(pushlex(\"}\"), pushblockcontext, block, poplex, popcontext);\n if (type == \";\") return cont();\n if (type == \"if\") {\n if (cx.state.lexical.info == \"else\" && cx.state.cc[cx.state.cc.length - 1] == poplex)\n cx.state.cc.pop()();\n return cont(pushlex(\"form\"), parenExpr, statement, poplex, maybeelse);\n }\n if (type == \"function\") return cont(functiondef);\n if (type == \"for\") return cont(pushlex(\"form\"), forspec, statement, poplex);\n if (type == \"class\" || (isTS && value == \"interface\")) { cx.marked = \"keyword\"; return cont(pushlex(\"form\"), className, poplex); }\n if (type == \"variable\") {\n if (isTS && value == \"declare\") {\n cx.marked = \"keyword\"\n return cont(statement)\n } else if (isTS && (value == \"module\" || value == \"enum\" || value == \"type\") && cx.stream.match(/^\\s*\\w/, false)) {\n cx.marked = \"keyword\"\n if (value == \"enum\") return cont(enumdef);\n else if (value == \"type\") return cont(typeexpr, expect(\"operator\"), typeexpr, expect(\";\"));\n else return cont(pushlex(\"form\"), pattern, expect(\"{\"), pushlex(\"}\"), block, poplex, poplex)\n } else if (isTS && value == \"namespace\") {\n cx.marked = \"keyword\"\n return cont(pushlex(\"form\"), expression, block, poplex)\n } else if (isTS && value == \"abstract\") {\n cx.marked = \"keyword\"\n return cont(statement)\n } else {\n return cont(pushlex(\"stat\"), maybelabel);\n }\n }\n if (type == \"switch\") return cont(pushlex(\"form\"), parenExpr, expect(\"{\"), pushlex(\"}\", \"switch\"), pushblockcontext,\n block, poplex, poplex, popcontext);\n if (type == \"case\") return cont(expression, expect(\":\"));\n if (type == \"default\") return cont(expect(\":\"));\n if (type == \"catch\") return cont(pushlex(\"form\"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);\n if (type == \"export\") return cont(pushlex(\"stat\"), afterExport, poplex);\n if (type == \"import\") return cont(pushlex(\"stat\"), afterImport, poplex);\n if (type == \"async\") return cont(statement)\n if (value == \"@\") return cont(expression, statement)\n return pass(pushlex(\"stat\"), expression, expect(\";\"), poplex);\n }\n function maybeCatchBinding(type) {\n if (type == \"(\") return cont(funarg, expect(\")\"))\n }\n function expression(type, value) {\n return expressionInner(type, value, false);\n }\n function expressionNoComma(type, value) {\n return expressionInner(type, value, true);\n }\n function parenExpr(type) {\n if (type != \"(\") return pass()\n return cont(pushlex(\")\"), expression, expect(\")\"), poplex)\n }\n function expressionInner(type, value, noComma) {\n if (cx.state.fatArrowAt == cx.stream.start) {\n var body = noComma ? arrowBodyNoComma : arrowBody;\n if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, expect(\"=>\"), body, popcontext);\n else if (type == \"variable\") return pass(pushcontext, pattern, expect(\"=>\"), body, popcontext);\n }\n\n var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;\n if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);\n if (type == \"function\") return cont(functiondef, maybeop);\n if (type == \"class\" || (isTS && value == \"interface\")) { cx.marked = \"keyword\"; return cont(pushlex(\"form\"), classExpression, poplex); }\n if (type == \"keyword c\" || type == \"async\") return cont(noComma ? expressionNoComma : expression);\n if (type == \"(\") return cont(pushlex(\")\"), maybeexpression, expect(\")\"), poplex, maybeop);\n if (type == \"operator\" || type == \"spread\") return cont(noComma ? expressionNoComma : expression);\n if (type == \"[\") return cont(pushlex(\"]\"), arrayLiteral, poplex, maybeop);\n if (type == \"{\") return contCommasep(objprop, \"}\", null, maybeop);\n if (type == \"quasi\") return pass(quasi, maybeop);\n if (type == \"new\") return cont(maybeTarget(noComma));\n if (type == \"import\") return cont(expression);\n return cont();\n }\n function maybeexpression(type) {\n if (type.match(/[;\\}\\)\\],]/)) return pass();\n return pass(expression);\n }\n\n function maybeoperatorComma(type, value) {\n if (type == \",\") return cont(expression);\n return maybeoperatorNoComma(type, value, false);\n }\n function maybeoperatorNoComma(type, value, noComma) {\n var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;\n var expr = noComma == false ? expression : expressionNoComma;\n if (type == \"=>\") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);\n if (type == \"operator\") {\n if (/\\+\\+|--/.test(value) || isTS && value == \"!\") return cont(me);\n if (isTS && value == \"<\" && cx.stream.match(/^([^>]|<.*?>)*>\\s*\\(/, false))\n return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, me);\n if (value == \"?\") return cont(expression, expect(\":\"), expr);\n return cont(expr);\n }\n if (type == \"quasi\") { return pass(quasi, me); }\n if (type == \";\") return;\n if (type == \"(\") return contCommasep(expressionNoComma, \")\", \"call\", me);\n if (type == \".\") return cont(property, me);\n if (type == \"[\") return cont(pushlex(\"]\"), maybeexpression, expect(\"]\"), poplex, me);\n if (isTS && value == \"as\") { cx.marked = \"keyword\"; return cont(typeexpr, me) }\n if (type == \"regexp\") {\n cx.state.lastType = cx.marked = \"operator\"\n cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)\n return cont(expr)\n }\n }\n function quasi(type, value) {\n if (type != \"quasi\") return pass();\n if (value.slice(value.length - 2) != \"${\") return cont(quasi);\n return cont(expression, continueQuasi);\n }\n function continueQuasi(type) {\n if (type == \"}\") {\n cx.marked = \"string-2\";\n cx.state.tokenize = tokenQuasi;\n return cont(quasi);\n }\n }\n function arrowBody(type) {\n findFatArrow(cx.stream, cx.state);\n return pass(type == \"{\" ? statement : expression);\n }\n function arrowBodyNoComma(type) {\n findFatArrow(cx.stream, cx.state);\n return pass(type == \"{\" ? statement : expressionNoComma);\n }\n function maybeTarget(noComma) {\n return function(type) {\n if (type == \".\") return cont(noComma ? targetNoComma : target);\n else if (type == \"variable\" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)\n else return pass(noComma ? expressionNoComma : expression);\n };\n }\n function target(_, value) {\n if (value == \"target\") { cx.marked = \"keyword\"; return cont(maybeoperatorComma); }\n }\n function targetNoComma(_, value) {\n if (value == \"target\") { cx.marked = \"keyword\"; return cont(maybeoperatorNoComma); }\n }\n function maybelabel(type) {\n if (type == \":\") return cont(poplex, statement);\n return pass(maybeoperatorComma, expect(\";\"), poplex);\n }\n function property(type) {\n if (type == \"variable\") {cx.marked = \"property\"; return cont();}\n }\n function objprop(type, value) {\n if (type == \"async\") {\n cx.marked = \"property\";\n return cont(objprop);\n } else if (type == \"variable\" || cx.style == \"keyword\") {\n cx.marked = \"property\";\n if (value == \"get\" || value == \"set\") return cont(getterSetter);\n var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params\n if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\\s*:\\s*/, false)))\n cx.state.fatArrowAt = cx.stream.pos + m[0].length\n return cont(afterprop);\n } else if (type == \"number\" || type == \"string\") {\n cx.marked = jsonldMode ? \"property\" : (cx.style + \" property\");\n return cont(afterprop);\n } else if (type == \"jsonld-keyword\") {\n return cont(afterprop);\n } else if (isTS && isModifier(value)) {\n cx.marked = \"keyword\"\n return cont(objprop)\n } else if (type == \"[\") {\n return cont(expression, maybetype, expect(\"]\"), afterprop);\n } else if (type == \"spread\") {\n return cont(expressionNoComma, afterprop);\n } else if (value == \"*\") {\n cx.marked = \"keyword\";\n return cont(objprop);\n } else if (type == \":\") {\n return pass(afterprop)\n }\n }\n function getterSetter(type) {\n if (type != \"variable\") return pass(afterprop);\n cx.marked = \"property\";\n return cont(functiondef);\n }\n function afterprop(type) {\n if (type == \":\") return cont(expressionNoComma);\n if (type == \"(\") return pass(functiondef);\n }\n function commasep(what, end, sep) {\n function proceed(type, value) {\n if (sep ? sep.indexOf(type) > -1 : type == \",\") {\n var lex = cx.state.lexical;\n if (lex.info == \"call\") lex.pos = (lex.pos || 0) + 1;\n return cont(function(type, value) {\n if (type == end || value == end) return pass()\n return pass(what)\n }, proceed);\n }\n if (type == end || value == end) return cont();\n return cont(expect(end));\n }\n return function(type, value) {\n if (type == end || value == end) return cont();\n return pass(what, proceed);\n };\n }\n function contCommasep(what, end, info) {\n for (var i = 3; i < arguments.length; i++)\n cx.cc.push(arguments[i]);\n return cont(pushlex(end, info), commasep(what, end), poplex);\n }\n function block(type) {\n if (type == \"}\") return cont();\n return pass(statement, block);\n }\n function maybetype(type, value) {\n if (isTS) {\n if (type == \":\") return cont(typeexpr);\n if (value == \"?\") return cont(maybetype);\n }\n }\n function mayberettype(type) {\n if (isTS && type == \":\") {\n if (cx.stream.match(/^\\s*\\w+\\s+is\\b/, false)) return cont(expression, isKW, typeexpr)\n else return cont(typeexpr)\n }\n }\n function isKW(_, value) {\n if (value == \"is\") {\n cx.marked = \"keyword\"\n return cont()\n }\n }\n function typeexpr(type, value) {\n if (value == \"keyof\" || value == \"typeof\") {\n cx.marked = \"keyword\"\n return cont(value == \"keyof\" ? typeexpr : expressionNoComma)\n }\n if (type == \"variable\" || value == \"void\") {\n cx.marked = \"type\"\n return cont(afterType)\n }\n if (type == \"string\" || type == \"number\" || type == \"atom\") return cont(afterType);\n if (type == \"[\") return cont(pushlex(\"]\"), commasep(typeexpr, \"]\", \",\"), poplex, afterType)\n if (type == \"{\") return cont(pushlex(\"}\"), commasep(typeprop, \"}\", \",;\"), poplex, afterType)\n if (type == \"(\") return cont(commasep(typearg, \")\"), maybeReturnType)\n if (type == \"<\") return cont(commasep(typeexpr, \">\"), typeexpr)\n }\n function maybeReturnType(type) {\n if (type == \"=>\") return cont(typeexpr)\n }\n function typeprop(type, value) {\n if (type == \"variable\" || cx.style == \"keyword\") {\n cx.marked = \"property\"\n return cont(typeprop)\n } else if (value == \"?\") {\n return cont(typeprop)\n } else if (type == \":\") {\n return cont(typeexpr)\n } else if (type == \"[\") {\n return cont(expression, maybetype, expect(\"]\"), typeprop)\n }\n }\n function typearg(type, value) {\n if (type == \"variable\" && cx.stream.match(/^\\s*[?:]/, false) || value == \"?\") return cont(typearg)\n if (type == \":\") return cont(typeexpr)\n return pass(typeexpr)\n }\n function afterType(type, value) {\n if (value == \"<\") return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, afterType)\n if (value == \"|\" || type == \".\" || value == \"&\") return cont(typeexpr)\n if (type == \"[\") return cont(expect(\"]\"), afterType)\n if (value == \"extends\" || value == \"implements\") { cx.marked = \"keyword\"; return cont(typeexpr) }\n }\n function maybeTypeArgs(_, value) {\n if (value == \"<\") return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, afterType)\n }\n function typeparam() {\n return pass(typeexpr, maybeTypeDefault)\n }\n function maybeTypeDefault(_, value) {\n if (value == \"=\") return cont(typeexpr)\n }\n function vardef(_, value) {\n if (value == \"enum\") {cx.marked = \"keyword\"; return cont(enumdef)}\n return pass(pattern, maybetype, maybeAssign, vardefCont);\n }\n function pattern(type, value) {\n if (isTS && isModifier(value)) { cx.marked = \"keyword\"; return cont(pattern) }\n if (type == \"variable\") { register(value); return cont(); }\n if (type == \"spread\") return cont(pattern);\n if (type == \"[\") return contCommasep(eltpattern, \"]\");\n if (type == \"{\") return contCommasep(proppattern, \"}\");\n }\n function proppattern(type, value) {\n if (type == \"variable\" && !cx.stream.match(/^\\s*:/, false)) {\n register(value);\n return cont(maybeAssign);\n }\n if (type == \"variable\") cx.marked = \"property\";\n if (type == \"spread\") return cont(pattern);\n if (type == \"}\") return pass();\n if (type == \"[\") return cont(expression, expect(']'), expect(':'), proppattern);\n return cont(expect(\":\"), pattern, maybeAssign);\n }\n function eltpattern() {\n return pass(pattern, maybeAssign)\n }\n function maybeAssign(_type, value) {\n if (value == \"=\") return cont(expressionNoComma);\n }\n function vardefCont(type) {\n if (type == \",\") return cont(vardef);\n }\n function maybeelse(type, value) {\n if (type == \"keyword b\" && value == \"else\") return cont(pushlex(\"form\", \"else\"), statement, poplex);\n }\n function forspec(type, value) {\n if (value == \"await\") return cont(forspec);\n if (type == \"(\") return cont(pushlex(\")\"), forspec1, expect(\")\"), poplex);\n }\n function forspec1(type) {\n if (type == \"var\") return cont(vardef, expect(\";\"), forspec2);\n if (type == \";\") return cont(forspec2);\n if (type == \"variable\") return cont(formaybeinof);\n return pass(expression, expect(\";\"), forspec2);\n }\n function formaybeinof(_type, value) {\n if (value == \"in\" || value == \"of\") { cx.marked = \"keyword\"; return cont(expression); }\n return cont(maybeoperatorComma, forspec2);\n }\n function forspec2(type, value) {\n if (type == \";\") return cont(forspec3);\n if (value == \"in\" || value == \"of\") { cx.marked = \"keyword\"; return cont(expression); }\n return pass(expression, expect(\";\"), forspec3);\n }\n function forspec3(type) {\n if (type != \")\") cont(expression);\n }\n function functiondef(type, value) {\n if (value == \"*\") {cx.marked = \"keyword\"; return cont(functiondef);}\n if (type == \"variable\") {register(value); return cont(functiondef);}\n if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, mayberettype, statement, popcontext);\n if (isTS && value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, functiondef)\n }\n function funarg(type, value) {\n if (value == \"@\") cont(expression, funarg)\n if (type == \"spread\") return cont(funarg);\n if (isTS && isModifier(value)) { cx.marked = \"keyword\"; return cont(funarg); }\n return pass(pattern, maybetype, maybeAssign);\n }\n function classExpression(type, value) {\n // Class expressions may have an optional name.\n if (type == \"variable\") return className(type, value);\n return classNameAfter(type, value);\n }\n function className(type, value) {\n if (type == \"variable\") {register(value); return cont(classNameAfter);}\n }\n function classNameAfter(type, value) {\n if (value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, classNameAfter)\n if (value == \"extends\" || value == \"implements\" || (isTS && type == \",\")) {\n if (value == \"implements\") cx.marked = \"keyword\";\n return cont(isTS ? typeexpr : expression, classNameAfter);\n }\n if (type == \"{\") return cont(pushlex(\"}\"), classBody, poplex);\n }\n function classBody(type, value) {\n if (type == \"async\" ||\n (type == \"variable\" &&\n (value == \"static\" || value == \"get\" || value == \"set\" || (isTS && isModifier(value))) &&\n cx.stream.match(/^\\s+[\\w$\\xa1-\\uffff]/, false))) {\n cx.marked = \"keyword\";\n return cont(classBody);\n }\n if (type == \"variable\" || cx.style == \"keyword\") {\n cx.marked = \"property\";\n return cont(isTS ? classfield : functiondef, classBody);\n }\n if (type == \"[\")\n return cont(expression, maybetype, expect(\"]\"), isTS ? classfield : functiondef, classBody)\n if (value == \"*\") {\n cx.marked = \"keyword\";\n return cont(classBody);\n }\n if (type == \";\") return cont(classBody);\n if (type == \"}\") return cont();\n if (value == \"@\") return cont(expression, classBody)\n }\n function classfield(type, value) {\n if (value == \"?\") return cont(classfield)\n if (type == \":\") return cont(typeexpr, maybeAssign)\n if (value == \"=\") return cont(expressionNoComma)\n return pass(functiondef)\n }\n function afterExport(type, value) {\n if (value == \"*\") { cx.marked = \"keyword\"; return cont(maybeFrom, expect(\";\")); }\n if (value == \"default\") { cx.marked = \"keyword\"; return cont(expression, expect(\";\")); }\n if (type == \"{\") return cont(commasep(exportField, \"}\"), maybeFrom, expect(\";\"));\n return pass(statement);\n }\n function exportField(type, value) {\n if (value == \"as\") { cx.marked = \"keyword\"; return cont(expect(\"variable\")); }\n if (type == \"variable\") return pass(expressionNoComma, exportField);\n }\n function afterImport(type) {\n if (type == \"string\") return cont();\n if (type == \"(\") return pass(expression);\n return pass(importSpec, maybeMoreImports, maybeFrom);\n }\n function importSpec(type, value) {\n if (type == \"{\") return contCommasep(importSpec, \"}\");\n if (type == \"variable\") register(value);\n if (value == \"*\") cx.marked = \"keyword\";\n return cont(maybeAs);\n }\n function maybeMoreImports(type) {\n if (type == \",\") return cont(importSpec, maybeMoreImports)\n }\n function maybeAs(_type, value) {\n if (value == \"as\") { cx.marked = \"keyword\"; return cont(importSpec); }\n }\n function maybeFrom(_type, value) {\n if (value == \"from\") { cx.marked = \"keyword\"; return cont(expression); }\n }\n function arrayLiteral(type) {\n if (type == \"]\") return cont();\n return pass(commasep(expressionNoComma, \"]\"));\n }\n function enumdef() {\n return pass(pushlex(\"form\"), pattern, expect(\"{\"), pushlex(\"}\"), commasep(enummember, \"}\"), poplex, poplex)\n }\n function enummember() {\n return pass(pattern, maybeAssign);\n }\n\n function isContinuedStatement(state, textAfter) {\n return state.lastType == \"operator\" || state.lastType == \",\" ||\n isOperatorChar.test(textAfter.charAt(0)) ||\n /[,.]/.test(textAfter.charAt(0));\n }\n\n function expressionAllowed(stream, state, backUp) {\n return state.tokenize == tokenBase &&\n /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\\[{}\\(,;:]|=>)$/.test(state.lastType) ||\n (state.lastType == \"quasi\" && /\\{\\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))\n }\n\n // Interface\n\n return {\n startState: function(basecolumn) {\n var state = {\n tokenize: tokenBase,\n lastType: \"sof\",\n cc: [],\n lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, \"block\", false),\n localVars: parserConfig.localVars,\n context: parserConfig.localVars && new Context(null, null, false),\n indented: basecolumn || 0\n };\n if (parserConfig.globalVars && typeof parserConfig.globalVars == \"object\")\n state.globalVars = parserConfig.globalVars;\n return state;\n },\n\n token: function(stream, state) {\n if (stream.sol()) {\n if (!state.lexical.hasOwnProperty(\"align\"))\n state.lexical.align = false;\n state.indented = stream.indentation();\n findFatArrow(stream, state);\n }\n if (state.tokenize != tokenComment && stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n if (type == \"comment\") return style;\n state.lastType = type == \"operator\" && (content == \"++\" || content == \"--\") ? \"incdec\" : type;\n return parseJS(state, style, type, content, stream);\n },\n\n indent: function(state, textAfter) {\n if (state.tokenize == tokenComment) return CodeMirror.Pass;\n if (state.tokenize != tokenBase) return 0;\n var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top\n // Kludge to prevent 'maybelse' from blocking lexical scope pops\n if (!/^\\s*else\\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {\n var c = state.cc[i];\n if (c == poplex) lexical = lexical.prev;\n else if (c != maybeelse) break;\n }\n while ((lexical.type == \"stat\" || lexical.type == \"form\") &&\n (firstChar == \"}\" || ((top = state.cc[state.cc.length - 1]) &&\n (top == maybeoperatorComma || top == maybeoperatorNoComma) &&\n !/^[,\\.=+\\-*:?[\\(]/.test(textAfter))))\n lexical = lexical.prev;\n if (statementIndent && lexical.type == \")\" && lexical.prev.type == \"stat\")\n lexical = lexical.prev;\n var type = lexical.type, closing = firstChar == type;\n\n if (type == \"vardef\") return lexical.indented + (state.lastType == \"operator\" || state.lastType == \",\" ? lexical.info.length + 1 : 0);\n else if (type == \"form\" && firstChar == \"{\") return lexical.indented;\n else if (type == \"form\") return lexical.indented + indentUnit;\n else if (type == \"stat\")\n return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);\n else if (lexical.info == \"switch\" && !closing && parserConfig.doubleIndentSwitch != false)\n return lexical.indented + (/^(?:case|default)\\b/.test(textAfter) ? indentUnit : 2 * indentUnit);\n else if (lexical.align) return lexical.column + (closing ? 0 : 1);\n else return lexical.indented + (closing ? 0 : indentUnit);\n },\n\n electricInput: /^\\s*(?:case .*?:|default:|\\{|\\})$/,\n blockCommentStart: jsonMode ? null : \"/*\",\n blockCommentEnd: jsonMode ? null : \"*/\",\n blockCommentContinue: jsonMode ? null : \" * \",\n lineComment: jsonMode ? null : \"//\",\n fold: \"brace\",\n closeBrackets: \"()[]{}''\\\"\\\"``\",\n\n helperType: jsonMode ? \"json\" : \"javascript\",\n jsonldMode: jsonldMode,\n jsonMode: jsonMode,\n\n expressionAllowed: expressionAllowed,\n\n skipExpression: function(state) {\n var top = state.cc[state.cc.length - 1]\n if (top == expression || top == expressionNoComma) state.cc.pop()\n }\n };\n});\n\nCodeMirror.registerHelper(\"wordChars\", \"javascript\", /[\\w$]/);\n\nCodeMirror.defineMIME(\"text/javascript\", \"javascript\");\nCodeMirror.defineMIME(\"text/ecmascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/javascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/x-javascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/ecmascript\", \"javascript\");\nCodeMirror.defineMIME(\"application/json\", {name: \"javascript\", json: true});\nCodeMirror.defineMIME(\"application/x-json\", {name: \"javascript\", json: true});\nCodeMirror.defineMIME(\"application/ld+json\", {name: \"javascript\", jsonld: true});\nCodeMirror.defineMIME(\"text/typescript\", { name: \"javascript\", typescript: true });\nCodeMirror.defineMIME(\"application/typescript\", { name: \"javascript\", typescript: true });\n\n});\n\n},{\"../../lib/codemirror\":17}],21:[function(require,module,exports){\n// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n\"use strict\";\n\nvar htmlConfig = {\n autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,\n 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,\n 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,\n 'track': true, 'wbr': true, 'menuitem': true},\n implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,\n 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,\n 'th': true, 'tr': true},\n contextGrabbers: {\n 'dd': {'dd': true, 'dt': true},\n 'dt': {'dd': true, 'dt': true},\n 'li': {'li': true},\n 'option': {'option': true, 'optgroup': true},\n 'optgroup': {'optgroup': true},\n 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,\n 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,\n 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,\n 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,\n 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},\n 'rp': {'rp': true, 'rt': true},\n 'rt': {'rp': true, 'rt': true},\n 'tbody': {'tbody': true, 'tfoot': true},\n 'td': {'td': true, 'th': true},\n 'tfoot': {'tbody': true},\n 'th': {'td': true, 'th': true},\n 'thead': {'tbody': true, 'tfoot': true},\n 'tr': {'tr': true}\n },\n doNotIndent: {\"pre\": true},\n allowUnquoted: true,\n allowMissing: true,\n caseFold: true\n}\n\nvar xmlConfig = {\n autoSelfClosers: {},\n implicitlyClosed: {},\n contextGrabbers: {},\n doNotIndent: {},\n allowUnquoted: false,\n allowMissing: false,\n allowMissingTagName: false,\n caseFold: false\n}\n\nCodeMirror.defineMode(\"xml\", function(editorConf, config_) {\n var indentUnit = editorConf.indentUnit\n var config = {}\n var defaults = config_.htmlMode ? htmlConfig : xmlConfig\n for (var prop in defaults) config[prop] = defaults[prop]\n for (var prop in config_) config[prop] = config_[prop]\n\n // Return variables for tokenizers\n var type, setStyle;\n\n function inText(stream, state) {\n function chain(parser) {\n state.tokenize = parser;\n return parser(stream, state);\n }\n\n var ch = stream.next();\n if (ch == \"<\") {\n if (stream.eat(\"!\")) {\n if (stream.eat(\"[\")) {\n if (stream.match(\"CDATA[\")) return chain(inBlock(\"atom\", \"]]>\"));\n else return null;\n } else if (stream.match(\"--\")) {\n return chain(inBlock(\"comment\", \"-->\"));\n } else if (stream.match(\"DOCTYPE\", true, true)) {\n stream.eatWhile(/[\\w\\._\\-]/);\n return chain(doctype(1));\n } else {\n return null;\n }\n } else if (stream.eat(\"?\")) {\n stream.eatWhile(/[\\w\\._\\-]/);\n state.tokenize = inBlock(\"meta\", \"?>\");\n return \"meta\";\n } else {\n type = stream.eat(\"/\") ? \"closeTag\" : \"openTag\";\n state.tokenize = inTag;\n return \"tag bracket\";\n }\n } else if (ch == \"&\") {\n var ok;\n if (stream.eat(\"#\")) {\n if (stream.eat(\"x\")) {\n ok = stream.eatWhile(/[a-fA-F\\d]/) && stream.eat(\";\");\n } else {\n ok = stream.eatWhile(/[\\d]/) && stream.eat(\";\");\n }\n } else {\n ok = stream.eatWhile(/[\\w\\.\\-:]/) && stream.eat(\";\");\n }\n return ok ? \"atom\" : \"error\";\n } else {\n stream.eatWhile(/[^&<]/);\n return null;\n }\n }\n inText.isInText = true;\n\n function inTag(stream, state) {\n var ch = stream.next();\n if (ch == \">\" || (ch == \"/\" && stream.eat(\">\"))) {\n state.tokenize = inText;\n type = ch == \">\" ? \"endTag\" : \"selfcloseTag\";\n return \"tag bracket\";\n } else if (ch == \"=\") {\n type = \"equals\";\n return null;\n } else if (ch == \"<\") {\n state.tokenize = inText;\n state.state = baseState;\n state.tagName = state.tagStart = null;\n var next = state.tokenize(stream, state);\n return next ? next + \" tag error\" : \"tag error\";\n } else if (/[\\'\\\"]/.test(ch)) {\n state.tokenize = inAttribute(ch);\n state.stringStartCol = stream.column();\n return state.tokenize(stream, state);\n } else {\n stream.match(/^[^\\s\\u00a0=<>\\\"\\']*[^\\s\\u00a0=<>\\\"\\'\\/]/);\n return \"word\";\n }\n }\n\n function inAttribute(quote) {\n var closure = function(stream, state) {\n while (!stream.eol()) {\n if (stream.next() == quote) {\n state.tokenize = inTag;\n break;\n }\n }\n return \"string\";\n };\n closure.isInAttribute = true;\n return closure;\n }\n\n function inBlock(style, terminator) {\n return function(stream, state) {\n while (!stream.eol()) {\n if (stream.match(terminator)) {\n state.tokenize = inText;\n break;\n }\n stream.next();\n }\n return style;\n }\n }\n\n function doctype(depth) {\n return function(stream, state) {\n var ch;\n while ((ch = stream.next()) != null) {\n if (ch == \"<\") {\n state.tokenize = doctype(depth + 1);\n return state.tokenize(stream, state);\n } else if (ch == \">\") {\n if (depth == 1) {\n state.tokenize = inText;\n break;\n } else {\n state.tokenize = doctype(depth - 1);\n return state.tokenize(stream, state);\n }\n }\n }\n return \"meta\";\n };\n }\n\n function Context(state, tagName, startOfLine) {\n this.prev = state.context;\n this.tagName = tagName;\n this.indent = state.indented;\n this.startOfLine = startOfLine;\n if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))\n this.noIndent = true;\n }\n function popContext(state) {\n if (state.context) state.context = state.context.prev;\n }\n function maybePopContext(state, nextTagName) {\n var parentTagName;\n while (true) {\n if (!state.context) {\n return;\n }\n parentTagName = state.context.tagName;\n if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||\n !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {\n return;\n }\n popContext(state);\n }\n }\n\n function baseState(type, stream, state) {\n if (type == \"openTag\") {\n state.tagStart = stream.column();\n return tagNameState;\n } else if (type == \"closeTag\") {\n return closeTagNameState;\n } else {\n return baseState;\n }\n }\n function tagNameState(type, stream, state) {\n if (type == \"word\") {\n state.tagName = stream.current();\n setStyle = \"tag\";\n return attrState;\n } else if (config.allowMissingTagName && type == \"endTag\") {\n setStyle = \"tag bracket\";\n return attrState(type, stream, state);\n } else {\n setStyle = \"error\";\n return tagNameState;\n }\n }\n function closeTagNameState(type, stream, state) {\n if (type == \"word\") {\n var tagName = stream.current();\n if (state.context && state.context.tagName != tagName &&\n config.implicitlyClosed.hasOwnProperty(state.context.tagName))\n popContext(state);\n if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {\n setStyle = \"tag\";\n return closeState;\n } else {\n setStyle = \"tag error\";\n return closeStateErr;\n }\n } else if (config.allowMissingTagName && type == \"endTag\") {\n setStyle = \"tag bracket\";\n return closeState(type, stream, state);\n } else {\n setStyle = \"error\";\n return closeStateErr;\n }\n }\n\n function closeState(type, _stream, state) {\n if (type != \"endTag\") {\n setStyle = \"error\";\n return closeState;\n }\n popContext(state);\n return baseState;\n }\n function closeStateErr(type, stream, state) {\n setStyle = \"error\";\n return closeState(type, stream, state);\n }\n\n function attrState(type, _stream, state) {\n if (type == \"word\") {\n setStyle = \"attribute\";\n return attrEqState;\n } else if (type == \"endTag\" || type == \"selfcloseTag\") {\n var tagName = state.tagName, tagStart = state.tagStart;\n state.tagName = state.tagStart = null;\n if (type == \"selfcloseTag\" ||\n config.autoSelfClosers.hasOwnProperty(tagName)) {\n maybePopContext(state, tagName);\n } else {\n maybePopContext(state, tagName);\n state.context = new Context(state, tagName, tagStart == state.indented);\n }\n return baseState;\n }\n setStyle = \"error\";\n return attrState;\n }\n function attrEqState(type, stream, state) {\n if (type == \"equals\") return attrValueState;\n if (!config.allowMissing) setStyle = \"error\";\n return attrState(type, stream, state);\n }\n function attrValueState(type, stream, state) {\n if (type == \"string\") return attrContinuedState;\n if (type == \"word\" && config.allowUnquoted) {setStyle = \"string\"; return attrState;}\n setStyle = \"error\";\n return attrState(type, stream, state);\n }\n function attrContinuedState(type, stream, state) {\n if (type == \"string\") return attrContinuedState;\n return attrState(type, stream, state);\n }\n\n return {\n startState: function(baseIndent) {\n var state = {tokenize: inText,\n state: baseState,\n indented: baseIndent || 0,\n tagName: null, tagStart: null,\n context: null}\n if (baseIndent != null) state.baseIndent = baseIndent\n return state\n },\n\n token: function(stream, state) {\n if (!state.tagName && stream.sol())\n state.indented = stream.indentation();\n\n if (stream.eatSpace()) return null;\n type = null;\n var style = state.tokenize(stream, state);\n if ((style || type) && style != \"comment\") {\n setStyle = null;\n state.state = state.state(type || style, stream, state);\n if (setStyle)\n style = setStyle == \"error\" ? style + \" error\" : setStyle;\n }\n return style;\n },\n\n indent: function(state, textAfter, fullLine) {\n var context = state.context;\n // Indent multi-line strings (e.g. css).\n if (state.tokenize.isInAttribute) {\n if (state.tagStart == state.indented)\n return state.stringStartCol + 1;\n else\n return state.indented + indentUnit;\n }\n if (context && context.noIndent) return CodeMirror.Pass;\n if (state.tokenize != inTag && state.tokenize != inText)\n return fullLine ? fullLine.match(/^(\\s*)/)[0].length : 0;\n // Indent the starts of attribute names.\n if (state.tagName) {\n if (config.multilineTagIndentPastTag !== false)\n return state.tagStart + state.tagName.length + 2;\n else\n return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);\n }\n if (config.alignCDATA && /$/,\n blockCommentStart: \"\",\n\n configuration: config.htmlMode ? \"html\" : \"xml\",\n helperType: config.htmlMode ? \"html\" : \"xml\",\n\n skipAttribute: function(state) {\n if (state.state == attrValueState)\n state.state = attrState\n }\n };\n});\n\nCodeMirror.defineMIME(\"text/xml\", \"xml\");\nCodeMirror.defineMIME(\"application/xml\", \"xml\");\nif (!CodeMirror.mimeModes.hasOwnProperty(\"text/html\"))\n CodeMirror.defineMIME(\"text/html\", {name: \"xml\", htmlMode: true});\n\n});\n\n},{\"../../lib/codemirror\":17}],22:[function(require,module,exports){\n/*\n\n Style HTML\n---------------\n\n Written by Nochum Sossonko, (nsossonko@hotmail.com)\n\n Based on code initially developed by: Einar Lielmanis, \n http://jsbeautifier.org/\n\n\n You are free to use this in any way you want, in case you find this useful or working for you.\n\n Usage:\n style_html(html_source);\n\n style_html(html_source, options);\n\n The options are:\n indent_size (default 4) — indentation size,\n indent_char (default space) — character to indent with,\n max_char (default 70) - maximum amount of characters per line,\n brace_style (default \"collapse\") - \"collapse\" | \"expand\" | \"end-expand\"\n put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line.\n unformatted (defaults to inline tags) - list of tags, that shouldn't be reformatted\n indent_scripts (default normal) - \"keep\"|\"separate\"|\"normal\"\n\n e.g.\n\n style_html(html_source, {\n 'indent_size': 2,\n 'indent_char': ' ',\n 'max_char': 78,\n 'brace_style': 'expand',\n 'unformatted': ['a', 'sub', 'sup', 'b', 'i', 'u']\n });\n*/\n\nfunction style_html(html_source, options) {\n//Wrapper function to invoke all the necessary constructors and deal with the output.\n\n var multi_parser,\n indent_size,\n indent_character,\n max_char,\n brace_style,\n unformatted;\n\n options = options || {};\n indent_size = options.indent_size || 4;\n indent_character = options.indent_char || ' ';\n brace_style = options.brace_style || 'collapse';\n max_char = options.max_char == 0 ? Infinity : options.max_char || 70;\n unformatted = options.unformatted || ['a', 'span', 'bdo', 'em', 'strong', 'dfn', 'code', 'samp', 'kbd', 'var', 'cite', 'abbr', 'acronym', 'q', 'sub', 'sup', 'tt', 'i', 'b', 'big', 'small', 'u', 's', 'strike', 'font', 'ins', 'del', 'pre', 'address', 'dt', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];\n\n function Parser() {\n\n this.pos = 0; //Parser position\n this.token = '';\n this.current_mode = 'CONTENT'; //reflects the current Parser mode: TAG/CONTENT\n this.tags = { //An object to hold tags, their position, and their parent-tags, initiated with default values\n parent: 'parent1',\n parentcount: 1,\n parent1: ''\n };\n this.tag_type = '';\n this.token_text = this.last_token = this.last_text = this.token_type = '';\n\n this.Utils = { //Uilities made available to the various functions\n whitespace: \"\\n\\r\\t \".split(''),\n single_token: 'br,input,link,meta,!doctype,basefont,base,area,hr,wbr,param,img,isindex,?xml,embed,?php,?,?='.split(','), //all the single tags for HTML\n extra_liners: 'head,body,/html'.split(','), //for tags that need a line of whitespace before them\n in_array: function (what, arr) {\n for (var i=0; i= this.input.length) {\n return content.length?content.join(''):['', 'TK_EOF'];\n }\n\n input_char = this.input.charAt(this.pos);\n this.pos++;\n this.line_char_count++;\n\n if (this.Utils.in_array(input_char, this.Utils.whitespace)) {\n if (content.length) {\n space = true;\n }\n this.line_char_count--;\n continue; //don't want to insert unnecessary space\n }\n else if (space) {\n if (this.line_char_count >= this.max_char) { //insert a line when the max_char is reached\n content.push('\\n');\n for (var i=0; i', 'igm');\n reg_match.lastIndex = this.pos;\n var reg_array = reg_match.exec(this.input);\n var end_script = reg_array?reg_array.index:this.input.length; //absolute end of script\n if(this.pos < end_script) { //get everything in between the script tags\n content = this.input.substring(this.pos, end_script);\n this.pos = end_script;\n }\n return content;\n }\n\n this.record_tag = function (tag){ //function to record a tag and its parent in this.tags Object\n if (this.tags[tag + 'count']) { //check for the existence of this tag type\n this.tags[tag + 'count']++;\n this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level\n }\n else { //otherwise initialize this tag type\n this.tags[tag + 'count'] = 1;\n this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level\n }\n this.tags[tag + this.tags[tag + 'count'] + 'parent'] = this.tags.parent; //set the parent (i.e. in the case of a div this.tags.div1parent)\n this.tags.parent = tag + this.tags[tag + 'count']; //and make this the current parent (i.e. in the case of a div 'div1')\n }\n\n this.retrieve_tag = function (tag) { //function to retrieve the opening tag to the corresponding closer\n if (this.tags[tag + 'count']) { //if the openener is not in the Object we ignore it\n var temp_parent = this.tags.parent; //check to see if it's a closable tag.\n while (temp_parent) { //till we reach '' (the initial value);\n if (tag + this.tags[tag + 'count'] === temp_parent) { //if this is it use it\n break;\n }\n temp_parent = this.tags[temp_parent + 'parent']; //otherwise keep on climbing up the DOM Tree\n }\n if (temp_parent) { //if we caught something\n this.indent_level = this.tags[tag + this.tags[tag + 'count']]; //set the indent_level accordingly\n this.tags.parent = this.tags[temp_parent + 'parent']; //and set the current parent\n }\n delete this.tags[tag + this.tags[tag + 'count'] + 'parent']; //delete the closed tags parent reference...\n delete this.tags[tag + this.tags[tag + 'count']]; //...and the tag itself\n if (this.tags[tag + 'count'] == 1) {\n delete this.tags[tag + 'count'];\n }\n else {\n this.tags[tag + 'count']--;\n }\n }\n }\n\n this.get_tag = function () { //function to get a full tag and parse its type\n var input_char = '',\n content = [],\n space = false,\n tag_start, tag_end;\n\n do {\n if (this.pos >= this.input.length) {\n return content.length?content.join(''):['', 'TK_EOF'];\n }\n\n input_char = this.input.charAt(this.pos);\n this.pos++;\n this.line_char_count++;\n\n if (this.Utils.in_array(input_char, this.Utils.whitespace)) { //don't want to insert unnecessary space\n space = true;\n this.line_char_count--;\n continue;\n }\n\n if (input_char === \"'\" || input_char === '\"') {\n if (!content[1] || content[1] !== '!') { //if we're in a comment strings don't get treated specially\n input_char += this.get_unformatted(input_char);\n space = true;\n }\n }\n\n if (input_char === '=') { //no space before =\n space = false;\n }\n\n if (content.length && content[content.length-1] !== '=' && input_char !== '>'\n && space) { //no space after = or before >\n if (this.line_char_count >= this.max_char) {\n this.print_newline(false, content);\n this.line_char_count = 0;\n }\n else {\n content.push(' ');\n this.line_char_count++;\n }\n space = false;\n }\n if (input_char === '<') {\n tag_start = this.pos - 1;\n }\n content.push(input_char); //inserts character at-a-time (or string)\n } while (input_char !== '>');\n\n var tag_complete = content.join('');\n var tag_index;\n if (tag_complete.indexOf(' ') != -1) { //if there's whitespace, thats where the tag name ends\n tag_index = tag_complete.indexOf(' ');\n }\n else { //otherwise go with the tag ending\n tag_index = tag_complete.indexOf('>');\n }\n var tag_check = tag_complete.substring(1, tag_index).toLowerCase();\n if (tag_complete.charAt(tag_complete.length-2) === '/' ||\n this.Utils.in_array(tag_check, this.Utils.single_token)) { //if this tag name is a single tag type (either in the list or has a closing /)\n this.tag_type = 'SINGLE';\n }\n else if (tag_check === 'script') { //for later script handling\n this.record_tag(tag_check);\n this.tag_type = 'SCRIPT';\n }\n else if (tag_check === 'style') { //for future style handling (for now it justs uses get_content)\n this.record_tag(tag_check);\n this.tag_type = 'STYLE';\n }\n else if (this.Utils.in_array(tag_check, unformatted)) { // do not reformat the \"unformatted\" tags\n var comment = this.get_unformatted('', tag_complete); //...delegate to get_unformatted function\n content.push(comment);\n // Preserve collapsed whitespace either before or after this tag.\n if (tag_start > 0 && this.Utils.in_array(this.input.charAt(tag_start - 1), this.Utils.whitespace)){\n content.splice(0, 0, this.input.charAt(tag_start - 1));\n }\n tag_end = this.pos - 1;\n if (this.Utils.in_array(this.input.charAt(tag_end + 1), this.Utils.whitespace)){\n content.push(this.input.charAt(tag_end + 1));\n }\n this.tag_type = 'SINGLE';\n }\n else if (tag_check.charAt(0) === '!') { //peek for so...\n var comment = this.get_unformatted('-->', tag_complete); //...delegate to get_unformatted\n content.push(comment);\n }\n this.tag_type = 'START';\n }\n else if (tag_check.indexOf('[endif') != -1) {//peek for ', tag_complete);\n content.push(comment);\n this.tag_type = 'SINGLE';\n }\n }\n else {\n if (tag_check.charAt(0) === '/') { //this tag is a double tag so check for tag-ending\n this.retrieve_tag(tag_check.substring(1)); //remove it and all ancestors\n this.tag_type = 'END';\n }\n else { //otherwise it's a start-tag\n this.record_tag(tag_check); //push it on the tag stack\n this.tag_type = 'START';\n }\n if (this.Utils.in_array(tag_check, this.Utils.extra_liners)) { //check if this double needs an extra line\n this.print_newline(true, this.output);\n }\n }\n return content.join(''); //returns fully formatted tag\n }\n\n this.get_unformatted = function (delimiter, orig_tag) { //function to return unformatted content in its entirety\n\n if (orig_tag && orig_tag.toLowerCase().indexOf(delimiter) != -1) {\n return '';\n }\n var input_char = '';\n var content = '';\n var space = true;\n do {\n\n if (this.pos >= this.input.length) {\n return content;\n }\n\n input_char = this.input.charAt(this.pos);\n this.pos++\n\n if (this.Utils.in_array(input_char, this.Utils.whitespace)) {\n if (!space) {\n this.line_char_count--;\n continue;\n }\n if (input_char === '\\n' || input_char === '\\r') {\n content += '\\n';\n /* Don't change tab indention for unformatted blocks. If using code for html editing, this will greatly affect
 tags if they are specified in the 'unformatted array'\n            for (var i=0; i 0) {\n          this.indent_level--;\n        }\n      }\n    }\n    return this;\n  }\n\n  /*_____________________--------------------_____________________*/\n\n  multi_parser = new Parser(); //wrapping functions Parser\n  multi_parser.printer(html_source, indent_character, indent_size, max_char, brace_style); //initialize starting values\n\n  while (true) {\n      var t = multi_parser.get_token();\n      multi_parser.token_text = t[0];\n      multi_parser.token_type = t[1];\n\n    if (multi_parser.token_type === 'TK_EOF') {\n      break;\n    }\n\n    switch (multi_parser.token_type) {\n      case 'TK_TAG_START':\n        multi_parser.print_newline(false, multi_parser.output);\n        multi_parser.print_token(multi_parser.token_text);\n        multi_parser.indent();\n        multi_parser.current_mode = 'CONTENT';\n        break;\n      case 'TK_TAG_STYLE':\n      case 'TK_TAG_SCRIPT':\n        multi_parser.print_newline(false, multi_parser.output);\n        multi_parser.print_token(multi_parser.token_text);\n        multi_parser.current_mode = 'CONTENT';\n        break;\n      case 'TK_TAG_END':\n        //Print new line only if the tag has no content and has child\n        if (multi_parser.last_token === 'TK_CONTENT' && multi_parser.last_text === '') {\n            var tag_name = multi_parser.token_text.match(/\\w+/)[0];\n            var tag_extracted_from_last_output = multi_parser.output[multi_parser.output.length -1].match(/<\\s*(\\w+)/);\n            if (tag_extracted_from_last_output === null || tag_extracted_from_last_output[1] !== tag_name)\n                multi_parser.print_newline(true, multi_parser.output);\n        }\n        multi_parser.print_token(multi_parser.token_text);\n        multi_parser.current_mode = 'CONTENT';\n        break;\n      case 'TK_TAG_SINGLE':\n        // Don't add a newline before elements that should remain unformatted.\n        var tag_check = multi_parser.token_text.match(/^\\s*<([a-z]+)/i);\n        if (!tag_check || !multi_parser.Utils.in_array(tag_check[1], unformatted)){\n            multi_parser.print_newline(false, multi_parser.output);\n        }\n        multi_parser.print_token(multi_parser.token_text);\n        multi_parser.current_mode = 'CONTENT';\n        break;\n      case 'TK_CONTENT':\n        if (multi_parser.token_text !== '') {\n          multi_parser.print_token(multi_parser.token_text);\n        }\n        multi_parser.current_mode = 'TAG';\n        break;\n      case 'TK_STYLE':\n      case 'TK_SCRIPT':\n        if (multi_parser.token_text !== '') {\n          multi_parser.output.push('\\n');\n          var text = multi_parser.token_text;\n          if (multi_parser.token_type == 'TK_SCRIPT') {\n            var _beautifier = typeof js_beautify == 'function' && js_beautify;\n          } else if (multi_parser.token_type == 'TK_STYLE') {\n            var _beautifier = typeof css_beautify == 'function' && css_beautify;\n          }\n\n          if (options.indent_scripts == \"keep\") {\n            var script_indent_level = 0;\n          } else if (options.indent_scripts == \"separate\") {\n            var script_indent_level = -multi_parser.indent_level;\n          } else {\n            var script_indent_level = 1;\n          }\n\n          var indentation = multi_parser.get_full_indent(script_indent_level);\n          if (_beautifier) {\n            // call the Beautifier if avaliable\n            text = _beautifier(text.replace(/^\\s*/, indentation), options);\n          } else {\n            // simply indent the string otherwise\n            var white = text.match(/^\\s*/)[0];\n            var _level = white.match(/[^\\n\\r]*$/)[0].split(multi_parser.indent_string).length - 1;\n            var reindent = multi_parser.get_full_indent(script_indent_level -_level);\n            text = text.replace(/^\\s*/, indentation)\n                   .replace(/\\r\\n|\\r|\\n/g, '\\n' + reindent)\n                   .replace(/\\s*$/, '');\n          }\n          if (text) {\n            multi_parser.print_token(text);\n            multi_parser.print_newline(true, multi_parser.output);\n          }\n        }\n        multi_parser.current_mode = 'TAG';\n        break;\n    }\n    multi_parser.last_token = multi_parser.token_type;\n    multi_parser.last_text = multi_parser.token_text;\n  }\n  return multi_parser.output.join('');\n}\n\nmodule.exports = {\n  prettyPrint: style_html\n};\n},{}],23:[function(require,module,exports){\n\"use strict\"\n\nmodule.exports = require(\"./stream/stream\")\n\n},{\"./stream/stream\":24}],24:[function(require,module,exports){\n/* eslint-disable */\n;(function() {\n\"use strict\"\n/* eslint-enable */\n\nvar guid = 0, HALT = {}\nfunction createStream() {\n\tfunction stream() {\n\t\tif (arguments.length > 0 && arguments[0] !== HALT) updateStream(stream, arguments[0])\n\t\treturn stream._state.value\n\t}\n\tinitStream(stream)\n\n\tif (arguments.length > 0 && arguments[0] !== HALT) updateStream(stream, arguments[0])\n\n\treturn stream\n}\nfunction initStream(stream) {\n\tstream.constructor = createStream\n\tstream._state = {id: guid++, value: undefined, state: 0, derive: undefined, recover: undefined, deps: {}, parents: [], endStream: undefined, unregister: undefined}\n\tstream.map = stream[\"fantasy-land/map\"] = map, stream[\"fantasy-land/ap\"] = ap, stream[\"fantasy-land/of\"] = createStream\n\tstream.valueOf = valueOf, stream.toJSON = toJSON, stream.toString = valueOf\n\n\tObject.defineProperties(stream, {\n\t\tend: {get: function() {\n\t\t\tif (!stream._state.endStream) {\n\t\t\t\tvar endStream = createStream()\n\t\t\t\tendStream.map(function(value) {\n\t\t\t\t\tif (value === true) {\n\t\t\t\t\t\tunregisterStream(stream)\n\t\t\t\t\t\tendStream._state.unregister = function(){unregisterStream(endStream)}\n\t\t\t\t\t}\n\t\t\t\t\treturn value\n\t\t\t\t})\n\t\t\t\tstream._state.endStream = endStream\n\t\t\t}\n\t\t\treturn stream._state.endStream\n\t\t}}\n\t})\n}\nfunction updateStream(stream, value) {\n\tupdateState(stream, value)\n\tfor (var id in stream._state.deps) updateDependency(stream._state.deps[id], false)\n\tif (stream._state.unregister != null) stream._state.unregister()\n\tfinalize(stream)\n}\nfunction updateState(stream, value) {\n\tstream._state.value = value\n\tstream._state.changed = true\n\tif (stream._state.state !== 2) stream._state.state = 1\n}\nfunction updateDependency(stream, mustSync) {\n\tvar state = stream._state, parents = state.parents\n\tif (parents.length > 0 && parents.every(active) && (mustSync || parents.some(changed))) {\n\t\tvar value = stream._state.derive()\n\t\tif (value === HALT) return false\n\t\tupdateState(stream, value)\n\t}\n}\nfunction finalize(stream) {\n\tstream._state.changed = false\n\tfor (var id in stream._state.deps) stream._state.deps[id]._state.changed = false\n}\n\nfunction combine(fn, streams) {\n\tif (!streams.every(valid)) throw new Error(\"Ensure that each item passed to stream.combine/stream.merge is a stream\")\n\treturn initDependency(createStream(), streams, function() {\n\t\treturn fn.apply(this, streams.concat([streams.filter(changed)]))\n\t})\n}\n\nfunction initDependency(dep, streams, derive) {\n\tvar state = dep._state\n\tstate.derive = derive\n\tstate.parents = streams.filter(notEnded)\n\n\tregisterDependency(dep, state.parents)\n\tupdateDependency(dep, true)\n\n\treturn dep\n}\nfunction registerDependency(stream, parents) {\n\tfor (var i = 0; i < parents.length; i++) {\n\t\tparents[i]._state.deps[stream._state.id] = stream\n\t\tregisterDependency(stream, parents[i]._state.parents)\n\t}\n}\nfunction unregisterStream(stream) {\n\tfor (var i = 0; i < stream._state.parents.length; i++) {\n\t\tvar parent = stream._state.parents[i]\n\t\tdelete parent._state.deps[stream._state.id]\n\t}\n\tfor (var id in stream._state.deps) {\n\t\tvar dependent = stream._state.deps[id]\n\t\tvar index = dependent._state.parents.indexOf(stream)\n\t\tif (index > -1) dependent._state.parents.splice(index, 1)\n\t}\n\tstream._state.state = 2 //ended\n\tstream._state.deps = {}\n}\n\nfunction map(fn) {return combine(function(stream) {return fn(stream())}, [this])}\nfunction ap(stream) {return combine(function(s1, s2) {return s1()(s2())}, [stream, this])}\nfunction valueOf() {return this._state.value}\nfunction toJSON() {return this._state.value != null && typeof this._state.value.toJSON === \"function\" ? this._state.value.toJSON() : this._state.value}\n\nfunction valid(stream) {return stream._state }\nfunction active(stream) {return stream._state.state === 1}\nfunction changed(stream) {return stream._state.changed}\nfunction notEnded(stream) {return stream._state.state !== 2}\n\nfunction merge(streams) {\n\treturn combine(function() {\n\t\treturn streams.map(function(s) {return s()})\n\t}, streams)\n}\n\nfunction scan(reducer, seed, stream) {\n\tvar newStream = combine(function (s) {\n\t\treturn seed = reducer(seed, s._state.value)\n\t}, [stream])\n\n\tif (newStream._state.state === 0) newStream(seed)\n\n\treturn newStream\n}\n\nfunction scanMerge(tuples, seed) {\n\tvar streams = tuples.map(function(tuple) {\n\t\tvar stream = tuple[0]\n\t\tif (stream._state.state === 0) stream(undefined)\n\t\treturn stream\n\t})\n\n\tvar newStream = combine(function() {\n\t\tvar changed = arguments[arguments.length - 1]\n\n\t\tstreams.forEach(function(stream, idx) {\n\t\t\tif (changed.indexOf(stream) > -1) {\n\t\t\t\tseed = tuples[idx][1](seed, stream._state.value)\n\t\t\t}\n\t\t})\n\n\t\treturn seed\n\t}, streams)\n\n\treturn newStream\n}\n\ncreateStream[\"fantasy-land/of\"] = createStream\ncreateStream.merge = merge\ncreateStream.combine = combine\ncreateStream.scan = scan\ncreateStream.scanMerge = scanMerge\ncreateStream.HALT = HALT\n\nif (typeof module !== \"undefined\") module[\"exports\"] = createStream\nelse if (typeof window.m === \"function\" && !(\"stream\" in window.m)) window.m.stream = createStream\nelse window.m = {stream : createStream}\n\n}());\n\n},{}]},{},[11]);\n })();"]}
\ No newline at end of file
diff --git a/assets/js/forms-block.js b/assets/js/forms-block.js
new file mode 100644
index 0000000..4530df4
--- /dev/null
+++ b/assets/js/forms-block.js
@@ -0,0 +1,50 @@
+(function () { var require = undefined; var define = undefined; (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i\n

\n\n"; $content .= "

\n\t\n

"; -return $content; \ No newline at end of file +return $content; diff --git a/config/default-form-messages.php b/config/default-form-messages.php index 9dfeb54..62d8b4c 100755 --- a/config/default-form-messages.php +++ b/config/default-form-messages.php @@ -1,39 +1,39 @@ array( - 'type' => 'success', - 'text' => __( 'Thank you, your sign-up request was successful! Please check your email inbox to confirm.', 'newsletter-for-wp' ) - ), - 'updated' => array( - 'type' => 'success', - 'text' => __( 'Thank you, your records have been updated!', 'newsletter-for-wp' ), - ), - 'unsubscribed' => array( - 'type' => 'success', - 'text' => __( 'You were successfully unsubscribed.', 'newsletter-for-wp' ), - ), - 'not_subscribed' => array( - 'type' => 'notice', - 'text' => __( 'Given email address is not subscribed.', 'newsletter-for-wp' ), - ), - 'error' => array( - 'type' => 'error', - 'text' => __( 'Oops. Something went wrong. Please try again later.', 'newsletter-for-wp' ), - ), - 'invalid_email' => array( - 'type' => 'error', - 'text' => __( 'Please provide a valid email address.', 'newsletter-for-wp' ), - ), - 'already_subscribed' => array( - 'type' => 'notice', - 'text' => __( 'Given email address is already subscribed, thank you!', 'newsletter-for-wp' ), - ), - 'required_field_missing' => array( - 'type' => 'error', - 'text' => __( 'Please fill in the required fields.', 'newsletter-for-wp' ), - ), - 'no_lists_selected' => array( - 'type' => 'error', - 'text' => __( 'Please select at least one list.', 'newsletter-for-wp' ) - ), + 'subscribed' => array( + 'type' => 'success', + 'text' => __('Thank you, your sign-up request was successful! Please check your email inbox to confirm.', 'newsletter-for-wp') + ), + 'updated' => array( + 'type' => 'success', + 'text' => __('Thank you, your records have been updated!', 'newsletter-for-wp'), + ), + 'unsubscribed' => array( + 'type' => 'success', + 'text' => __('You were successfully unsubscribed.', 'newsletter-for-wp'), + ), + 'not_subscribed' => array( + 'type' => 'notice', + 'text' => __('Given email address is not subscribed.', 'newsletter-for-wp'), + ), + 'error' => array( + 'type' => 'error', + 'text' => __('Oops. Something went wrong. Please try again later.', 'newsletter-for-wp'), + ), + 'invalid_email' => array( + 'type' => 'error', + 'text' => __('Please provide a valid email address.', 'newsletter-for-wp'), + ), + 'already_subscribed' => array( + 'type' => 'notice', + 'text' => __('Given email address is already subscribed, thank you!', 'newsletter-for-wp'), + ), + 'required_field_missing' => array( + 'type' => 'error', + 'text' => __('Please fill in the required fields.', 'newsletter-for-wp'), + ), + 'no_lists_selected' => array( + 'type' => 'error', + 'text' => __('Please select at least one list.', 'newsletter-for-wp') + ), ); diff --git a/config/default-form-settings.php b/config/default-form-settings.php index 4753ca3..aa3b819 100755 --- a/config/default-form-settings.php +++ b/config/default-form-settings.php @@ -1,11 +1,12 @@ 0, - 'double_optin' => 1, - 'hide_after_success' => 0, - 'lists' => array(), - 'redirect' => '', - 'replace_interests' => 1, - 'required_fields' => '', - 'update_existing' => 0, + 'css' => 0, + 'double_optin' => 1, + 'hide_after_success' => 0, + 'lists' => array(), + 'redirect' => '', + 'replace_interests' => 1, + 'required_fields' => '', + 'update_existing' => 0, + 'subscriber_tags' => '', ); diff --git a/config/default-settings.php b/config/default-settings.php index 755e685..89dd16d 100755 --- a/config/default-settings.php +++ b/config/default-settings.php @@ -1,6 +1,6 @@ '', - 'allow_usage_tracking' => 0, + 'api_key' => '', + 'allow_usage_tracking' => 0, 'debug_log_level' => 'warning', -); \ No newline at end of file +); diff --git a/includes/admin/class-admin-ajax.php b/includes/admin/class-admin-ajax.php index 16bbe33..4696042 100755 --- a/includes/admin/class-admin-ajax.php +++ b/includes/admin/class-admin-ajax.php @@ -1,6 +1,7 @@ tools = $tools; } @@ -20,22 +21,22 @@ public function __construct( NL4WP_Admin_Tools $tools ) /** * Hook AJAX actions */ - public function add_hooks() { - add_action( 'wp_ajax_nl4wp_renew_newsletter_lists', array( $this, 'refresh_newsletter_lists' ) ); + public function add_hooks() + { + add_action('wp_ajax_nl4wp_renew_newsletter_lists', array( $this, 'refresh_newsletter_lists' )); } /** * Empty lists cache & fetch lists again. */ - public function refresh_newsletter_lists() { - if( ! $this->tools->is_user_authorized() ) { + public function refresh_newsletter_lists() + { + if (! $this->tools->is_user_authorized()) { wp_send_json(false); } $newsletter = new NL4WP_Newsletter(); $success = $newsletter->fetch_lists(); - wp_send_json( $success ); + wp_send_json($success); } - - -} \ No newline at end of file +} diff --git a/includes/admin/class-admin-messages.php b/includes/admin/class-admin-messages.php index e6d7927..b0bd953 100755 --- a/includes/admin/class-admin-messages.php +++ b/includes/admin/class-admin-messages.php @@ -6,76 +6,83 @@ * @ignore * @since 3.0 */ -class NL4WP_Admin_Messages { +class NL4WP_Admin_Messages +{ - /** - * @var array - */ - protected $bag; + /** + * @var array + */ + protected $bag; - /** - * @var bool - */ - protected $dirty = false; + /** + * @var bool + */ + protected $dirty = false; - /** - * Add hooks - */ - public function add_hooks() { - add_action( 'admin_notices', array( $this, 'show' ) ); - register_shutdown_function( array( $this, 'save' ) ); - } + /** + * Add hooks + */ + public function add_hooks() + { + add_action('admin_notices', array( $this, 'show' )); + register_shutdown_function(array( $this, 'save' )); + } - private function load() { - if( is_null( $this->bag ) ) { - $this->bag = get_option( 'nl4wp_flash_messages', array() ); - } - } + private function load() + { + if (is_null($this->bag)) { + $this->bag = get_option('nl4wp_flash_messages', array()); + } + } - // empty flash bag - private function reset() { - $this->bag = array(); - $this->dirty = true; - } + // empty flash bag + private function reset() + { + $this->bag = array(); + $this->dirty = true; + } - /** - * Flash a message (shows on next pageload) - * - * @param $message - * @param string $type - */ - public function flash( $message, $type = 'success' ) { - $this->load(); - $this->bag[] = array( - 'text' => $message, - 'type' => $type - ); - $this->dirty = true; - } + /** + * Flash a message (shows on next pageload) + * + * @param $message + * @param string $type + */ + public function flash($message, $type = 'success') + { + $this->load(); + $this->bag[] = array( + 'text' => $message, + 'type' => $type + ); + $this->dirty = true; + } - /** - * Show queued flash messages - */ - public function show() { - $this->load(); + /** + * Show queued flash messages + */ + public function show() + { + $this->load(); - foreach( $this->bag as $message ) { - echo sprintf( '

%s

', $message['type'], $message['text'] ); - } + foreach ($this->bag as $message) { + echo sprintf('

%s

', $message['type'], $message['text']); + } - $this->reset(); - } + $this->reset(); + } - /** - * Save queued messages - * - * @hooked `shutdown` - */ - public function save() { - if( $this->dirty ) { - update_option( 'nl4wp_flash_messages', $this->bag, false ); - } - } -} \ No newline at end of file + /** + * Save queued messages + * + * @hooked `shutdown` + */ + public function save() + { + if ($this->dirty) { + update_option('nl4wp_flash_messages', $this->bag, false); + } + } +} diff --git a/includes/admin/class-admin-texts.php b/includes/admin/class-admin-texts.php index f17be8b..6bda7d3 100755 --- a/includes/admin/class-admin-texts.php +++ b/includes/admin/class-admin-texts.php @@ -6,94 +6,95 @@ * @ignore * @since 3.0 */ -class NL4WP_Admin_Texts { +class NL4WP_Admin_Texts +{ - /** - * @param string $plugin_file - */ - public function __construct( $plugin_file ) { - $this->plugin_file = $plugin_file; - } + /** + * @param string $plugin_file + */ + public function __construct($plugin_file) + { + $this->plugin_file = $plugin_file; + } - /** - * Add hooks - */ - public function add_hooks() { - global $pagenow; + /** + * Add hooks + */ + public function add_hooks() + { + global $pagenow; - add_filter( 'admin_footer_text', array( $this, 'footer_text' ) ); + add_filter('admin_footer_text', array( $this, 'footer_text' )); - // Hooks for Plugins overview page - if( $pagenow === 'plugins.php' ) { - add_filter( 'plugin_action_links_' . $this->plugin_file, array( $this, 'add_plugin_settings_link' ), 10, 2 ); - add_filter( 'plugin_row_meta', array( $this, 'add_plugin_meta_links'), 10, 2 ); - } - } + // Hooks for Plugins overview page + if ($pagenow === 'plugins.php') { + add_filter('plugin_action_links_' . $this->plugin_file, array( $this, 'add_plugin_settings_link' ), 10, 2); + add_filter('plugin_row_meta', array( $this, 'add_plugin_meta_links'), 10, 2); + } + } - /** - * Ask for a plugin review in the WP Admin footer, if this is one of the plugin pages. - * - * @param $text - * - * @return string - */ - public function footer_text( $text ) { + /** + * Ask for a plugin review in the WP Admin footer, if this is one of the plugin pages. + * + * @param $text + * + * @return string + */ + public function footer_text($text) + { + if (! empty($_GET['page']) && strpos($_GET['page'], 'newsletter-for-wp') === 0) { + //$text = sprintf('If you enjoy using Newsletter for WordPress, please leave us a ★★★★★ rating. A huge thank you in advance!', 'https://wordpress.org/support/view/plugin-reviews/newsletter-for-wp?rate=5#postform'); /* NL_CHANGED */ + } - if(! empty( $_GET['page'] ) && strpos( $_GET['page'], 'newsletter-for-wp' ) === 0 ) { - /* NL_COMMENT - start -* Non mostra footer -*/ -//$text = sprintf( 'If you enjoy using Newsletter for WordPress, please leave us a ★★★★★ rating. A huge thank you in advance!', 'https://wordpress.org/support/view/plugin-reviews/newsletter-for-wp?rate=5#postform' ); -/* NL_COMMENT - end */ - } + return $text; + } - return $text; - } + /** + * Add the settings link to the Plugins overview + * + * @param array $links + * @param $file + * + * @return array + */ + public function add_plugin_settings_link($links, $file) + { + if ($file !== $this->plugin_file) { + return $links; + } - /** - * Add the settings link to the Plugins overview - * - * @param array $links - * @param $file - * - * @return array - */ - public function add_plugin_settings_link( $links, $file ) { - if( $file !== $this->plugin_file ) { - return $links; - } + $settings_link = ''. __('Settings', 'newsletter-for-wp') . ''; + array_unshift($links, $settings_link); + return $links; + } - $settings_link = ''. __( 'Settings', 'newsletter-for-wp' ) . ''; - array_unshift( $links, $settings_link ); - return $links; - } + /** + * Adds meta links to the plugin in the WP Admin > Plugins screen + * + * @param array $links + * @param string $file + * + * @return array + */ + public function add_plugin_meta_links($links, $file) + { + if ($file !== $this->plugin_file) { + return $links; + } - /** - * Adds meta links to the plugin in the WP Admin > Plugins screen - * - * @param array $links - * @param string $file - * - * @return array - */ - public function add_plugin_meta_links( $links, $file ) { - if( $file !== $this->plugin_file ) { - return $links; - } + // $links[] = ''. __('Documentation', 'newsletter-for-wp') . ''; - // $links[] = ''. __( 'Documentation', 'newsletter-for-wp' ) . ''; - - /** - * Filters meta links shown on the Plugins overview page - * - * This takes an array of strings - * - * @since 3.0 - * @param array $links + /** + * Filters meta links shown on the Plugins overview page + * + * This takes an array of strings + * + * @since 3.0 + * @param array $links * @ignore - */ - $links = (array) apply_filters( 'nl4wp_admin_plugin_meta_links', $links ); + */ + $links = (array) apply_filters('nl4wp_admin_plugin_meta_links', $links); - return $links; - } -} \ No newline at end of file + return $links; + } +} diff --git a/includes/admin/class-admin-tools.php b/includes/admin/class-admin-tools.php index 42471c2..0b376e0 100755 --- a/includes/admin/class-admin-tools.php +++ b/includes/admin/class-admin-tools.php @@ -1,17 +1,19 @@ get_required_capability() ); + public function is_user_authorized() + { + return current_user_can($this->get_required_capability()); } /** @@ -44,8 +48,8 @@ public function is_user_authorized() { * * @return string */ - public function get_required_capability() { - + public function get_required_capability() + { $capability = 'manage_options'; /** @@ -54,7 +58,7 @@ public function get_required_capability() { * @ignore * @deprecated 3.0 */ - $capability = apply_filters( 'nl4wp_settings_cap', $capability ); + $capability = apply_filters('nl4wp_settings_cap', $capability); /** * Filters the required user capability to access the Newsletter for WordPress' settings pages, view the dashboard widgets. @@ -65,9 +69,8 @@ public function get_required_capability() { * @param string $capability * @see https://codex.wordpress.org/Roles_and_Capabilities */ - $capability = (string) apply_filters( 'nl4wp_admin_required_capability', $capability ); + $capability = (string) apply_filters('nl4wp_admin_required_capability', $capability); return $capability; } - -} \ No newline at end of file +} diff --git a/includes/admin/class-admin.php b/includes/admin/class-admin.php index f723c22..8b1282a 100755 --- a/includes/admin/class-admin.php +++ b/includes/admin/class-admin.php @@ -6,525 +6,546 @@ * @ignore * @access private */ -class NL4WP_Admin { - - /** - * @var string The relative path to the main plugin file from the plugins dir - */ - protected $plugin_file; - - /** - * @var NL4WP_Newsletter - */ - protected $newsletter; - - /** - * @var NL4WP_Admin_Messages - */ - protected $messages; - - /** - * @var NL4WP_Admin_Ads - */ - protected $ads; - - /** - * @var NL4WP_Admin_Tools - */ - protected $tools; - - /** - * @var NL4WP_Admin_Review_Notice - */ - protected $review_notice; - - /** - * Constructor - * - * @param NL4WP_Admin_Tools $tools - * @param NL4WP_Admin_Messages $messages - * @param NL4WP_Newsletter $newsletter - */ - public function __construct( NL4WP_Admin_Tools $tools, NL4WP_Admin_Messages $messages, NL4WP_Newsletter $newsletter ) { - $this->tools = $tools; - $this->newsletter = $newsletter; - $this->messages = $messages; - $this->plugin_file = plugin_basename( NL4WP_PLUGIN_FILE ); - $this->ads = new NL4WP_Admin_Ads(); - $this->review_notice = new NL4WP_Admin_Review_Notice( $tools ); - $this->load_translations(); - } - - /** - * Registers all hooks - */ - public function add_hooks() { - - // Actions used globally throughout WP Admin - add_action( 'admin_menu', array( $this, 'build_menu' ) ); - add_action( 'admin_init', array( $this, 'initialize' ) ); - - add_action( 'current_screen', array( $this, 'customize_admin_texts' ) ); - add_action( 'wp_dashboard_setup', array( $this, 'register_dashboard_widgets' ) ); - add_action( 'nl4wp_admin_empty_lists_cache', array( $this, 'renew_lists_cache' ) ); - add_action( 'nl4wp_admin_empty_debug_log', array( $this, 'empty_debug_log' ) ); - - add_action( 'admin_notices', array( $this, 'show_api_key_notice' ) ); - add_action( 'nl4wp_admin_dismiss_api_key_notice', array( $this, 'dismiss_api_key_notice' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); - - $this->ads->add_hooks(); - $this->messages->add_hooks(); - $this->review_notice->add_hooks(); - } - - /** - * Initializes various stuff used in WP Admin - * - * - Registers settings - */ - public function initialize() { - - // register settings - register_setting( 'nl4wp_settings', 'nl4wp', array( $this, 'save_general_settings' ) ); - - // Load upgrader - $this->init_upgrade_routines(); - - // listen for custom actions - $this->listen_for_actions(); - } - - - /** - * Listen for `_nl4wp_action` requests - */ - public function listen_for_actions() { - - // listen for any action (if user is authorised) - if( ! $this->tools->is_user_authorized() || ! isset( $_REQUEST['_nl4wp_action'] ) ) { - return false; - } - - $action = (string) $_REQUEST['_nl4wp_action']; - - /** - * Allows you to hook into requests containing `_nl4wp_action` => action name. - * - * The dynamic portion of the hook name, `$action`, refers to the action name. - * - * By the time this hook is fired, the user is already authorized. After processing all the registered hooks, - * the request is redirected back to the referring URL. - * - * @since 3.0 - */ - do_action( 'nl4wp_admin_' . $action ); - - // redirect back to where we came from - $redirect_url = ! empty( $_POST['_redirect_to'] ) ? $_POST['_redirect_to'] : remove_query_arg( '_nl4wp_action' ); - wp_redirect( $redirect_url ); - exit; - } - - /** - * Register dashboard widgets - */ - public function register_dashboard_widgets() { - - if( ! $this->tools->is_user_authorized() ) { - return false; - } - - /** - * Setup dashboard widget, users are authorized by now. - * - * Use this hook to register your own dashboard widgets for users with the required capability. - * - * @since 3.0 - * @ignore - */ - do_action( 'nl4wp_dashboard_setup' ); - - return true; - } - - /** - * Upgrade routine - */ - private function init_upgrade_routines() { - - // upgrade routine for upgrade routine.... - $previous_version = get_option( 'nl4wp_lite_version', 0 ); - if( $previous_version ) { - delete_option( 'nl4wp_lite_version' ); - update_option( 'nl4wp_version', $previous_version ); - } - - $previous_version = get_option( 'nl4wp_version', 0 ); - - // allow setting migration version from URL, to easily re-run previous migrations. - if( isset( $_GET['nl4wp_run_migration'] ) ) { - $previous_version = $_GET['nl4wp_run_migration']; - } - - // Ran upgrade routines before? - if( empty( $previous_version ) ) { - update_option( 'nl4wp_version', NL4WP_VERSION ); - - // if we have at least one form, we're going to run upgrade routine for v3 => v4 anyway. - // TODO: Remove this once we hit 4.2.x - $posts = get_posts( array( 'post_type' => 'nl4wp-form', 'numberposts' => 1 ) ); - if( empty( $posts ) ) { - return false; - } - - $previous_version = '3.9'; - } - - // Rollback'ed? - if( version_compare( $previous_version, NL4WP_VERSION, '>' ) ) { - update_option( 'nl4wp_version', NL4WP_VERSION ); - return false; - } - - // This means we're good! - if( version_compare( $previous_version, NL4WP_VERSION ) > -1 ) { - return false; - } - - define( 'NL4WP_DOING_UPGRADE', true ); - $upgrade_routines = new NL4WP_Upgrade_Routines( $previous_version, NL4WP_VERSION, dirname( __FILE__ ) . '/migrations' ); - $upgrade_routines->run(); - update_option( 'nl4wp_version', NL4WP_VERSION ); - } - - /** - * Renew Newsletter lists cache - */ - public function renew_lists_cache() { - // try getting new lists to fill cache again - $lists = $this->newsletter->fetch_lists(); - - if( ! empty( $lists ) ) { - $this->messages->flash( __( 'Success! The cached configuration for your Newsletter lists has been renewed.', 'newsletter-for-wp' ) ); - } - } - - /** - * Load the plugin translations - */ - private function load_translations() { - // load the plugin text domain - load_plugin_textdomain( 'newsletter-for-wp', false, dirname( $this->plugin_file ) . '/languages' ); - } - - /** - * Customize texts throughout WP Admin - */ - public function customize_admin_texts() { - $texts = new NL4WP_Admin_Texts( $this->plugin_file ); - $texts->add_hooks(); - } - - /** - * Validates the General settings - * @param array $settings - * @return array - */ - public function save_general_settings( array $settings ) { - - $current = nl4wp_get_options(); - - // merge with current settings to allow passing partial arrays to this method - $settings = array_merge( $current, $settings ); - - // toggle usage tracking - if( $settings['allow_usage_tracking'] !== $current['allow_usage_tracking'] ) { - NL4WP_Usage_Tracking::instance()->toggle( $settings['allow_usage_tracking'] ); - } - - // Make sure not to use obfuscated key - if( strpos( $settings['api_key'], '*' ) !== false ) { - $settings['api_key'] = $current['api_key']; - } - - // Sanitize API key - $settings['api_key'] = sanitize_text_field( $settings['api_key'] ); - - // if API key changed, empty Newsletter cache - if ( $settings['api_key'] !== $current['api_key'] ) { - $this->newsletter->empty_cache(); - } - - - /** - * Runs right before general settings are saved. - * - * @param array $settings The updated settings array - * @param array $current The old settings array - */ - do_action( 'nl4wp_save_settings', $settings, $current ); - - return $settings; - } - - /** - * Load scripts and stylesheet on Newsletter for WP Admin pages - * - * @return bool - */ - public function enqueue_assets() { - - global $wp_scripts; - - - if( ! $this->tools->on_plugin_page() ) { - return false; - } - - $opts = nl4wp_get_options(); - $page = $this->tools->get_plugin_page(); - $suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min'; - - // css - wp_register_style( 'nl4wp-admin', NL4WP_PLUGIN_URL . 'assets/css/admin-styles' . $suffix . '.css', array(), NL4WP_VERSION ); - wp_enqueue_style( 'nl4wp-admin' ); - - // js - wp_register_script( 'es5-shim', NL4WP_PLUGIN_URL . 'assets/js/third-party/es5-shim.min.js', array(), NL4WP_VERSION ); - $wp_scripts->add_data( 'es5-shim', 'conditional', 'lt IE 9' ); - - // TODO: eventually get rid of jQuery here - wp_register_script( 'nl4wp-admin', NL4WP_PLUGIN_URL . 'assets/js/admin' . $suffix . '.js', array( 'jquery', 'es5-shim' ), NL4WP_VERSION, true ); - wp_enqueue_script( array( 'jquery', 'es5-shim', 'nl4wp-admin' ) ); - - wp_localize_script( 'nl4wp-admin', 'nl4wp_vars', - array( - 'newsletter' => array( - 'api_connected' => ! empty( $opts['api_key'] ), - 'lists' => $this->newsletter->get_cached_lists() - ), - 'countries' => NL4WP_Tools::get_countries(), - 'i18n' => array( - 'pro_only' => __( 'This is a pro-only feature. Please upgrade to the premium version to be able to use it.', 'newsletter-for-wp' ), - 'renew_newsletter_lists' => __( 'Renew Newsletter lists', 'newsletter-for-wp' ), - 'fetching_newsletter_lists' => __( 'Fetching Newsletter lists', 'newsletter-for-wp' ), - 'fetching_newsletter_lists_done' => __( 'Done! Newsletter lists renewed.', 'newsletter-for-wp' ), - 'fetching_newsletter_lists_can_take_a_while' => __( 'This can take a while if you have many Newsletter lists.', 'newsletter-for-wp' ), - 'fetching_newsletter_lists_error' => __( 'Failed to renew your lists. An error occured.', 'newsletter-for-wp' ), - ) - ) - ); - - /** - * Hook to enqueue your own custom assets on the Newsletter for WordPress setting pages. - * - * @since 3.0 - * - * @param string $suffix - * @param string $page - */ - do_action( 'nl4wp_admin_enqueue_assets', $suffix, $page ); - - return true; - } - - - - /** - * Register the setting pages and their menu items - */ - public function build_menu() { - $required_cap = $this->tools->get_required_capability(); - - $menu_items = array( - array( - 'title' => __( 'Newsletter API Settings', 'newsletter-for-wp' ), - 'text' => __( 'Newsletter', 'newsletter-for-wp' ), - 'slug' => '', - 'callback' => array( $this, 'show_generals_setting_page' ), - 'position' => 0 - ), - array( - 'title' => __( 'Other Settings', 'newsletter-for-wp' ), - 'text' => __( 'Other', 'newsletter-for-wp' ), - 'slug' => 'other', - 'callback' => array( $this, 'show_other_setting_page' ), - 'position' => 90 - ), - - ); - - /** - * Filters the menu items to appear under the main menu item. - * - * To add your own item, add an associative array in the following format. - * - * $menu_items[] = array( - * 'title' => 'Page title', - * 'text' => 'Menu text', - * 'slug' => 'Page slug', - * 'callback' => 'my_page_function', - * 'position' => 50 - * ); - * - * @param array $menu_items - * @since 3.0 - */ - $menu_items = (array) apply_filters( 'nl4wp_admin_menu_items', $menu_items ); - - // add top menu item - add_menu_page( 'Newsletter for WP', 'Newsletter for WP', $required_cap, 'newsletter-for-wp', array( $this, 'show_generals_setting_page' ), NL4WP_PLUGIN_URL . 'assets/img/icon.png', '99.68491' ); - - // sort submenu items by 'position' - usort( $menu_items, array( $this, 'sort_menu_items_by_position' ) ); - - // add sub-menu items - foreach( $menu_items as $item ) { - $this->add_menu_item( $item ); - } - } - - /** - * @param array $item - */ - public function add_menu_item( array $item ) { - - // generate menu slug - $slug = 'newsletter-for-wp'; - if( ! empty( $item['slug'] ) ) { - $slug .= '-' . $item['slug']; - } - - // provide some defaults - $parent_slug = ! empty( $item['parent_slug']) ? $item['parent_slug'] : 'newsletter-for-wp'; - $capability = ! empty( $item['capability'] ) ? $item['capability'] : $this->tools->get_required_capability(); - - // register page - $hook = add_submenu_page( $parent_slug, $item['title'] . ' - Newsletter for WordPress', $item['text'], $capability, $slug, $item['callback'] ); - - // register callback for loading this page, if given - if( array_key_exists( 'load_callback', $item ) ) { - add_action( 'load-' . $hook, $item['load_callback'] ); - } - } - - /** - * Show the API Settings page - */ - public function show_generals_setting_page() { - $opts = nl4wp_get_options(); - $api_key = nl4wp_get_api_key(); - - $connected = ! empty( $api_key ); - if( $connected ) { - try { - $connected = $this->get_api()->is_connected(); - } catch( NL4WP_API_Connection_Exception $e ) { - $message = sprintf( "%s %s %s ", __( "Error connecting to Newsletter:", 'newsletter-for-wp' ), $e->getCode(), $e->getMessage() ); - - if( is_object( $e->data ) && ! empty( $e->data->ref_no ) ) { - $message .= '
' . sprintf( __( 'Looks like your server is blocked by Newsletter\'s firewall. Please contact Newsletter support and include the following reference number: %s', 'newsletter-for-wp' ), $e->data->ref_no ); - } - - $message .= '

' . sprintf( '' . __( 'Here\'s some info on solving common connectivity issues.', 'newsletter-for-wp' ) . '', 'https://kb.mc4wp.com/solving-connectivity-issues/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=settings-notice' ); - - $this->messages->flash( $message, 'error' ); - $connected = false; - } catch( NL4WP_API_Exception $e ) { - $this->messages->flash( sprintf( "%s
%s", __( "Newsletter returned the following error:", 'newsletter-for-wp' ), $e ), 'error' ); - $connected = false; - } - } - - $lists = $this->newsletter->get_cached_lists(); - $obfuscated_api_key = nl4wp_obfuscate_string( $api_key ); - require NL4WP_PLUGIN_DIR . 'includes/views/general-settings.php'; - } - - /** - * Show the Other Settings page - */ - public function show_other_setting_page() { - $opts = nl4wp_get_options(); - $log = $this->get_log(); - $log_reader = new NL4WP_Debug_Log_Reader( $log->file ); - require NL4WP_PLUGIN_DIR . 'includes/views/other-settings.php'; - } - - /** - * @param $a - * @param $b - * - * @return int - */ - public function sort_menu_items_by_position( $a, $b ) { - $pos_a = isset( $a['position'] ) ? $a['position'] : 80; - $pos_b = isset( $b['position'] ) ? $b['position'] : 90; - return $pos_a < $pos_b ? -1 : 1; - } - - /** - * Empties the log file - */ - public function empty_debug_log() { - $log = $this->get_log(); - file_put_contents( $log->file, '' ); - - $this->messages->flash( __( 'Log successfully emptied.', 'newsletter-for-wp' ) ); - } - - /** - * Shows a notice when API key is not set. - */ - public function show_api_key_notice() { - - // don't show if on settings page already - if( $this->tools->on_plugin_page( '' ) ) { - return; - } - - // only show to user with proper permissions - if( ! $this->tools->is_user_authorized() ) { - return; - } - - // don't show if dismissed - if( get_transient( 'nl4wp_api_key_notice_dismissed' ) ) { - return; - } - - // don't show if api key is set already - $api_key = nl4wp_get_api_key(); - if( ! empty( $api_key ) ) { - return; - } - - echo '
'; - echo '

' . sprintf( __( 'To get started with Newsletter for WordPress, please enter your Newsletter API key on the settings page of the plugin.', 'newsletter-for-wp' ), admin_url( 'admin.php?page=newsletter-for-wp' ) ) . '

'; - echo '
'; - echo '
'; - } - - /** - * Dismisses the API key notice for 1 week - */ - public function dismiss_api_key_notice() { - set_transient( 'nl4wp_api_key_notice_dismissed', 1, 3600 * 24 * 7 ); - } - - /** - * @return NL4WP_Debug_Log - */ - protected function get_log() { - return nl4wp('log'); - } - - /** - * @return NL4WP_API_v3 - */ - protected function get_api() { - return nl4wp('api'); - } - +class NL4WP_Admin +{ + + /** + * @var string The relative path to the main plugin file from the plugins dir + */ + protected $plugin_file; + + /** + * @var NL4WP_Newsletter + */ + protected $newsletter; + + /** + * @var NL4WP_Admin_Messages + */ + protected $messages; + + /** + * @var NL4WP_Admin_Ads + */ + protected $ads; + + /** + * @var NL4WP_Admin_Tools + */ + protected $tools; + + /** + * @var NL4WP_Admin_Review_Notice + */ + protected $review_notice; + + /** + * Constructor + * + * @param NL4WP_Admin_Tools $tools + * @param NL4WP_Admin_Messages $messages + * @param NL4WP_Newsletter $newsletter + */ + public function __construct(NL4WP_Admin_Tools $tools, NL4WP_Admin_Messages $messages, NL4WP_Newsletter $newsletter) + { + $this->tools = $tools; + $this->newsletter = $newsletter; + $this->messages = $messages; + $this->plugin_file = plugin_basename(NL4WP_PLUGIN_FILE); + $this->ads = new NL4WP_Admin_Ads(); + $this->review_notice = new NL4WP_Admin_Review_Notice($tools); + $this->load_translations(); + } + + /** + * Registers all hooks + */ + public function add_hooks() + { + + // Actions used globally throughout WP Admin + add_action('admin_menu', array( $this, 'build_menu' )); + add_action('admin_init', array( $this, 'initialize' )); + + add_action('current_screen', array( $this, 'customize_admin_texts' )); + add_action('wp_dashboard_setup', array( $this, 'register_dashboard_widgets' )); + add_action('nl4wp_admin_empty_lists_cache', array( $this, 'renew_lists_cache' )); + add_action('nl4wp_admin_empty_debug_log', array( $this, 'empty_debug_log' )); + + add_action('admin_notices', array( $this, 'show_api_key_notice' )); + add_action('nl4wp_admin_dismiss_api_key_notice', array( $this, 'dismiss_api_key_notice' )); + add_action('admin_enqueue_scripts', array( $this, 'enqueue_assets' )); + + $this->ads->add_hooks(); + $this->messages->add_hooks(); + $this->review_notice->add_hooks(); + } + + /** + * Initializes various stuff used in WP Admin + * + * - Registers settings + */ + public function initialize() + { + + // register settings + register_setting('nl4wp_settings', 'nl4wp', array( $this, 'save_general_settings' )); + + // Load upgrader + $this->init_upgrade_routines(); + + // listen for custom actions + $this->listen_for_actions(); + } + + + /** + * Listen for `_nl4wp_action` requests + */ + public function listen_for_actions() + { + + // listen for any action (if user is authorised) + if (! $this->tools->is_user_authorized() || ! isset($_REQUEST['_nl4wp_action'])) { + return false; + } + + $action = (string) $_REQUEST['_nl4wp_action']; + + /** + * Allows you to hook into requests containing `_nl4wp_action` => action name. + * + * The dynamic portion of the hook name, `$action`, refers to the action name. + * + * By the time this hook is fired, the user is already authorized. After processing all the registered hooks, + * the request is redirected back to the referring URL. + * + * @since 3.0 + */ + do_action('nl4wp_admin_' . $action); + + // redirect back to where we came from + $redirect_url = ! empty($_POST['_redirect_to']) ? $_POST['_redirect_to'] : remove_query_arg('_nl4wp_action'); + wp_redirect($redirect_url); + exit; + } + + /** + * Register dashboard widgets + */ + public function register_dashboard_widgets() + { + if (! $this->tools->is_user_authorized()) { + return false; + } + + /** + * Setup dashboard widget, users are authorized by now. + * + * Use this hook to register your own dashboard widgets for users with the required capability. + * + * @since 3.0 + * @ignore + */ + do_action('nl4wp_dashboard_setup'); + + return true; + } + + /** + * Upgrade routine + */ + private function init_upgrade_routines() + { + + // upgrade routine for upgrade routine.... + $previous_version = get_option('nl4wp_lite_version', 0); + if ($previous_version) { + delete_option('nl4wp_lite_version'); + update_option('nl4wp_version', $previous_version); + } + + $previous_version = get_option('nl4wp_version', 0); + + // allow setting migration version from URL, to easily re-run previous migrations. + if (isset($_GET['nl4wp_run_migration'])) { + $previous_version = $_GET['nl4wp_run_migration']; + } + + // Ran upgrade routines before? + if (empty($previous_version)) { + update_option('nl4wp_version', NL4WP_VERSION); + + // if we have at least one form, we're going to run upgrade routine for v3 => v4 anyway. + // TODO: Remove this once we hit 4.2.x + $posts = get_posts(array( 'post_type' => 'nl4wp-form', 'numberposts' => 1 )); + if (empty($posts)) { + return false; + } + + $previous_version = '3.9'; + } + + // Rollback'ed? + if (version_compare($previous_version, NL4WP_VERSION, '>')) { + update_option('nl4wp_version', NL4WP_VERSION); + return false; + } + + // This means we're good! + if (version_compare($previous_version, NL4WP_VERSION) > -1) { + return false; + } + + define('NL4WP_DOING_UPGRADE', true); + $upgrade_routines = new NL4WP_Upgrade_Routines($previous_version, NL4WP_VERSION, dirname(__FILE__) . '/migrations'); + $upgrade_routines->run(); + update_option('nl4wp_version', NL4WP_VERSION); + } + + /** + * Renew Newsletter lists cache + */ + public function renew_lists_cache() + { + // try getting new lists to fill cache again + $lists = $this->newsletter->fetch_lists(); + + if (! empty($lists)) { + $this->messages->flash(__('Success! The cached configuration for your Newsletter lists has been renewed.', 'newsletter-for-wp')); + } + } + + /** + * Load the plugin translations + */ + private function load_translations() + { + // load the plugin text domain + load_plugin_textdomain('newsletter-for-wp', false, dirname($this->plugin_file) . '/languages'); + } + + /** + * Customize texts throughout WP Admin + */ + public function customize_admin_texts() + { + $texts = new NL4WP_Admin_Texts($this->plugin_file); + $texts->add_hooks(); + } + + /** + * Validates the General settings + * @param array $settings + * @return array + */ + public function save_general_settings(array $settings) + { + $current = nl4wp_get_options(); + + // merge with current settings to allow passing partial arrays to this method + $settings = array_merge($current, $settings); + + // toggle usage tracking + if ($settings['allow_usage_tracking'] !== $current['allow_usage_tracking']) { + NL4WP_Usage_Tracking::instance()->toggle($settings['allow_usage_tracking']); + } + + // Make sure not to use obfuscated key + if (strpos($settings['api_key'], '*') !== false) { + $settings['api_key'] = $current['api_key']; + } + + // Sanitize API key + $settings['api_key'] = sanitize_text_field($settings['api_key']); + + // if API key changed, empty Newsletter cache + if ($settings['api_key'] !== $current['api_key']) { + $this->newsletter->empty_cache(); + } + + + /** + * Runs right before general settings are saved. + * + * @param array $settings The updated settings array + * @param array $current The old settings array + */ + do_action('nl4wp_save_settings', $settings, $current); + + return $settings; + } + + /** + * Load scripts and stylesheet on Newsletter for WP Admin pages + * + * @return bool + */ + public function enqueue_assets() + { + global $wp_scripts; + + + if (! $this->tools->on_plugin_page()) { + return false; + } + + $opts = nl4wp_get_options(); + $page = $this->tools->get_plugin_page(); + $suffix = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? '' : '.min'; + + // css + wp_register_style('nl4wp-admin', NL4WP_PLUGIN_URL . 'assets/css/admin-styles' . $suffix . '.css', array(), NL4WP_VERSION); + wp_enqueue_style('nl4wp-admin'); + + // js + wp_register_script('es5-shim', NL4WP_PLUGIN_URL . 'assets/js/third-party/es5-shim.min.js', array(), NL4WP_VERSION); + $wp_scripts->add_data('es5-shim', 'conditional', 'lt IE 9'); + + // TODO: eventually get rid of jQuery here + wp_register_script('nl4wp-admin', NL4WP_PLUGIN_URL . 'assets/js/admin' . $suffix . '.js', array( 'jquery', 'es5-shim' ), NL4WP_VERSION, true); + wp_enqueue_script(array( 'jquery', 'es5-shim', 'nl4wp-admin' )); + + wp_localize_script( + 'nl4wp-admin', + 'nl4wp_vars', + array( + 'newsletter' => array( + 'api_connected' => ! empty($opts['api_key']), + 'lists' => $this->newsletter->get_cached_lists() + ), + 'countries' => NL4WP_Tools::get_countries(), + 'i18n' => array( + 'invalid_api_key' => __('The given value does not look like a valid Newsletter API key.', 'newsletter-for-wp'), + 'pro_only' => __('This is a premium feature. Please upgrade to Newsletter for WordPress Premium to be able to use it.', 'newsletter-for-wp'), + 'renew_newsletter_lists' => __('Renew Newsletter lists', 'newsletter-for-wp'), + 'fetching_newsletter_lists' => __('Fetching Newsletter lists', 'newsletter-for-wp'), + 'fetching_newsletter_lists_done' => __('Done! Newsletter lists renewed.', 'newsletter-for-wp'), + 'fetching_newsletter_lists_can_take_a_while' => __('This can take a while if you have many Newsletter lists.', 'newsletter-for-wp'), + 'fetching_newsletter_lists_error' => __('Failed to renew your lists. An error occured.', 'newsletter-for-wp'), + ) + ) + ); + + /** + * Hook to enqueue your own custom assets on the Newsletter for WordPress setting pages. + * + * @since 3.0 + * + * @param string $suffix + * @param string $page + */ + do_action('nl4wp_admin_enqueue_assets', $suffix, $page); + + return true; + } + + + + /** + * Register the setting pages and their menu items + */ + public function build_menu() + { + $required_cap = $this->tools->get_required_capability(); + + $menu_items = array( + array( + 'title' => __('Newsletter API Settings', 'newsletter-for-wp'), + 'text' => __('Newsletter', 'newsletter-for-wp'), + 'slug' => '', + 'callback' => array( $this, 'show_generals_setting_page' ), + 'position' => 0 + ), + array( + 'title' => __('Other Settings', 'newsletter-for-wp'), + 'text' => __('Other', 'newsletter-for-wp'), + 'slug' => 'other', + 'callback' => array( $this, 'show_other_setting_page' ), + 'position' => 90 + ), + + ); + + /** + * Filters the menu items to appear under the main menu item. + * + * To add your own item, add an associative array in the following format. + * + * $menu_items[] = array( + * 'title' => 'Page title', + * 'text' => 'Menu text', + * 'slug' => 'Page slug', + * 'callback' => 'my_page_function', + * 'position' => 50 + * ); + * + * @param array $menu_items + * @since 3.0 + */ + $menu_items = (array) apply_filters('nl4wp_admin_menu_items', $menu_items); + + // add top menu item + add_menu_page('Newsletter for WP', 'Newsletter for WP', $required_cap, 'newsletter-for-wp', array( $this, 'show_generals_setting_page' ), NL4WP_PLUGIN_URL . 'assets/img/icon.png', '99.68491'); + + // sort submenu items by 'position' + usort($menu_items, array( $this, 'sort_menu_items_by_position' )); + + // add sub-menu items + foreach ($menu_items as $item) { + $this->add_menu_item($item); + } + } + + /** + * @param array $item + */ + public function add_menu_item(array $item) + { + + // generate menu slug + $slug = 'newsletter-for-wp'; + if (! empty($item['slug'])) { + $slug .= '-' . $item['slug']; + } + + // provide some defaults + $parent_slug = ! empty($item['parent_slug']) ? $item['parent_slug'] : 'newsletter-for-wp'; + $capability = ! empty($item['capability']) ? $item['capability'] : $this->tools->get_required_capability(); + + // register page + $hook = add_submenu_page($parent_slug, $item['title'] . ' - Newsletter for WordPress', $item['text'], $capability, $slug, $item['callback']); + + // register callback for loading this page, if given + if (array_key_exists('load_callback', $item)) { + add_action('load-' . $hook, $item['load_callback']); + } + } + + /** + * Show the API Settings page + */ + public function show_generals_setting_page() + { + $opts = nl4wp_get_options(); + $api_key = nl4wp_get_api_key(); + + $connected = ! empty($api_key); + if ($connected) { + try { + $connected = $this->get_api()->is_connected(); + } catch (NL4WP_API_Connection_Exception $e) { + $message = sprintf("%s %s %s ", __("Error connecting to Newsletter:", 'newsletter-for-wp'), $e->getCode(), $e->getMessage()); + + if (is_object($e->data) && ! empty($e->data->ref_no)) { + $message .= '
' . sprintf(__('Looks like your server is blocked by Newsletter\'s firewall. Please contact Newsletter support and include the following reference number: %s', 'newsletter-for-wp'), $e->data->ref_no); + } + + $message .= '

' . sprintf('' . __('Here\'s some info on solving common connectivity issues.', 'newsletter-for-wp') . '', 'https://kb.mc4wp.com/solving-connectivity-issues/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=settings-notice'); + + $this->messages->flash($message, 'error'); + $connected = false; + } catch (NL4WP_API_Exception $e) { + $this->messages->flash(sprintf("%s
%s", __("Newsletter returned the following error:", 'newsletter-for-wp'), $e), 'error'); + $connected = false; + } + } + + $lists = $this->newsletter->get_cached_lists(); + $obfuscated_api_key = nl4wp_obfuscate_string($api_key); + require NL4WP_PLUGIN_DIR . 'includes/views/general-settings.php'; + } + + /** + * Show the Other Settings page + */ + public function show_other_setting_page() + { + $opts = nl4wp_get_options(); + $log = $this->get_log(); + $log_reader = new NL4WP_Debug_Log_Reader($log->file); + require NL4WP_PLUGIN_DIR . 'includes/views/other-settings.php'; + } + + /** + * @param $a + * @param $b + * + * @return int + */ + public function sort_menu_items_by_position($a, $b) + { + $pos_a = isset($a['position']) ? $a['position'] : 80; + $pos_b = isset($b['position']) ? $b['position'] : 90; + return $pos_a < $pos_b ? -1 : 1; + } + + /** + * Empties the log file + */ + public function empty_debug_log() + { + $log = $this->get_log(); + file_put_contents($log->file, ''); + + $this->messages->flash(__('Log successfully emptied.', 'newsletter-for-wp')); + } + + /** + * Shows a notice when API key is not set. + */ + public function show_api_key_notice() + { + + // don't show if on settings page already + if ($this->tools->on_plugin_page('')) { + return; + } + + // only show to user with proper permissions + if (! $this->tools->is_user_authorized()) { + return; + } + + // don't show if dismissed + if (get_transient('nl4wp_api_key_notice_dismissed')) { + return; + } + + // don't show if api key is set already + $api_key = nl4wp_get_api_key(); + if (! empty($api_key)) { + return; + } + + echo '
'; + echo '

' . sprintf(__('To get started with Newsletter for WordPress, please enter your Newsletter API key on the settings page of the plugin.', 'newsletter-for-wp'), admin_url('admin.php?page=newsletter-for-wp')) . '

'; + echo '
'; + echo '
'; + } + + /** + * Dismisses the API key notice for 1 week + */ + public function dismiss_api_key_notice() + { + set_transient('nl4wp_api_key_notice_dismissed', 1, 3600 * 24 * 7); + } + + /** + * @return NL4WP_Debug_Log + */ + protected function get_log() + { + return nl4wp('log'); + } + + /** + * @return NL4WP_API_v3 + */ + protected function get_api() + { + return nl4wp('api'); + } } diff --git a/includes/admin/class-ads.php b/includes/admin/class-ads.php index 6ed6ad3..27a52f1 100755 --- a/includes/admin/class-ads.php +++ b/includes/admin/class-ads.php @@ -6,141 +6,145 @@ * @ignore * @access private */ -class NL4WP_Admin_Ads { - - /** - * @return bool Adds hooks - */ - public function add_hooks() { - - // don't hook if Premium is activated - if( defined( 'NL4WP_PREMIUM_VERSION' ) ) { - return false; - } - - add_filter( 'nl4wp_admin_plugin_meta_links', array( $this, 'plugin_meta_links' ) ); - add_action( 'nl4wp_admin_form_after_behaviour_settings_rows', array( $this, 'after_form_settings_rows' ) ); - add_action( 'nl4wp_admin_form_after_appearance_settings_rows', array( $this, 'after_form_appearance_settings_rows' ) ); - add_action( 'nl4wp_admin_sidebar', array( $this, 'admin_sidebar' ) ); - add_action( 'nl4wp_admin_footer', array( $this, 'admin_footer' ) ); - add_action( 'nl4wp_admin_other_settings', array( $this, 'ecommerce' ), 90 ); - - add_filter( 'nl4wp_admin_menu_items', array( $this, 'add_menu_item' ) ); - - add_action( 'nl4wp_admin_after_woocommerce_integration_settings', array( $this, 'ecommerce' ) ); - return true; - } - - public function add_menu_item( $items ) { - $items['extensions'] = array( - 'title' => __( 'Add-ons', 'newsletter-for-wp' ), - 'text' => '' . __( 'Add-ons', 'newsletter-for-wp' ) . '', - 'slug' => 'extensions', - 'callback' => array( $this, 'show_extensions_page' ), - 'position' => 100 - ); - - return $items; - } - - /** - * Add text row to "Form > Appearance" tab. - */ - public function after_form_appearance_settings_rows() { - echo ''; - echo ''; - echo '

'; - echo sprintf( __( 'Want to customize the style of your form? Try our Styles Builder & edit the look of your forms with just a few clicks.', 'newsletter-for-wp' ), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=form-settings-link' ); - echo '

'; - echo ''; - echo ''; - } - - /** - * Add text row to "Form > Settings" tab. - */ - public function after_form_settings_rows() { - echo ''; - echo ''; - echo '

'; - - if( rand( 1, 2 ) === 1 ) { - echo sprintf( __( 'Be notified whenever someone subscribes? Newsletter for WordPress Premium allows you to set up email notifications for your forms.', 'newsletter-for-wp' ), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=footer-link' ); - } else { - echo sprintf( __( 'Increased conversions? Newsletter for WordPress Premium submits forms without reloading the entire page, resulting in a much better experience for your visitors.', 'newsletter-for-wp' ), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=form-settings-link' ); - } - - echo '

'; - echo ''; - echo ''; - } - - /** - * @param array $links - * - * @return array - */ - public function plugin_meta_links( $links ) { - $links[] = '' . __( 'Upgrade to Premium', 'newsletter-for-wp' ) . ''; - return $links; - } - - /** - * Add several texts to admin footer. - */ - public function admin_footer() { - - if( isset( $_GET['view'] ) && $_GET['view'] === 'edit-form' ) { - - // WPML & Polylang specific message - if( defined( 'ICL_LANGUAGE_CODE' ) ) { - echo '

' . sprintf( __( 'Do you want translated forms for all of your languages? Try Newsletter for WordPress Premium, which does just that plus more.', 'newsletter-for-wp' ), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=footer-link' ) . '

'; - return; - } - - // General "edit form" message - echo '

' . sprintf( __( 'Do you want to create more than one form? Our Premium add-on does just that! Have a look at all Premium benefits.', 'newsletter-for-wp' ), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=footer-link' ) . '

'; - return; - } - - // General message - echo '

' . sprintf( __( 'Are you enjoying this plugin? The Premium add-on unlocks several powerful features. Find out about all benefits now.', 'newsletter-for-wp' ), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=footer-link' ) . '

'; - } - - /** - * Add email opt-in form to sidebar - */ - public function admin_sidebar() { - - echo '
'; - echo '
'; - echo '

Newsletter for WordPress Premium

'; - echo '

This plugin has a Premium add-on, unlocking several powerful features. Have a look at its benefits!

'; - echo '
'; - echo '
'; - - ?> +class NL4WP_Admin_Ads +{ + + /** + * @return bool Adds hooks + */ + public function add_hooks() + { + + // don't hook if Premium is activated + if (defined('NL4WP_PREMIUM_VERSION')) { + return false; + } + + add_filter('nl4wp_admin_plugin_meta_links', array( $this, 'plugin_meta_links' )); + add_action('nl4wp_admin_form_after_behaviour_settings_rows', array( $this, 'after_form_settings_rows' )); + add_action('nl4wp_admin_form_after_appearance_settings_rows', array( $this, 'after_form_appearance_settings_rows' )); + add_action('nl4wp_admin_sidebar', array( $this, 'admin_sidebar' )); + add_action('nl4wp_admin_footer', array( $this, 'admin_footer' )); + add_action('nl4wp_admin_other_settings', array( $this, 'ecommerce' ), 90); + + add_filter('nl4wp_admin_menu_items', array( $this, 'add_menu_item' )); + + add_action('nl4wp_admin_after_woocommerce_integration_settings', array( $this, 'ecommerce' )); + return true; + } + + public function add_menu_item($items) + { + $items['extensions'] = array( + 'title' => __('Add-ons', 'newsletter-for-wp'), + 'text' => '' . __('Add-ons', 'newsletter-for-wp') . '', + 'slug' => 'extensions', + 'callback' => array( $this, 'show_extensions_page' ), + 'position' => 100 + ); + + return $items; + } + + /** + * Add text row to "Form > Appearance" tab. + */ + public function after_form_appearance_settings_rows() + { + echo ''; + echo ''; + echo '

'; + echo sprintf(__('Want to customize the style of your form? Try our Styles Builder & edit the look of your forms with just a few clicks.', 'newsletter-for-wp'), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=form-settings-link'); + echo '

'; + echo ''; + echo ''; + } + + /** + * Add text row to "Form > Settings" tab. + */ + public function after_form_settings_rows() + { + echo ''; + echo ''; + echo '

'; + + if (rand(1, 2) === 1) { + echo sprintf(__('Be notified whenever someone subscribes? Newsletter for WordPress Premium allows you to set up email notifications for your forms.', 'newsletter-for-wp'), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=footer-link'); + } else { + echo sprintf(__('Increased conversions? Newsletter for WordPress Premium submits forms without reloading the entire page, resulting in a much better experience for your visitors.', 'newsletter-for-wp'), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=form-settings-link'); + } + + echo '

'; + echo ''; + echo ''; + } + + /** + * @param array $links + * + * @return array + */ + public function plugin_meta_links($links) + { + $links[] = '' . __('Upgrade to Premium', 'newsletter-for-wp') . ''; + return $links; + } + + /** + * Add several texts to admin footer. + */ + public function admin_footer() + { + if (isset($_GET['view']) && $_GET['view'] === 'edit-form') { + + // WPML & Polylang specific message + if (defined('ICL_LANGUAGE_CODE')) { + echo '

' . sprintf(__('Do you want translated forms for all of your languages? Try Newsletter for WordPress Premium, which does just that plus more.', 'newsletter-for-wp'), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=footer-link') . '

'; + return; + } + + // General "edit form" message + echo '

' . sprintf(__('Do you want to create more than one form? Our Premium add-on does just that! Have a look at all Premium benefits.', 'newsletter-for-wp'), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=footer-link') . '

'; + return; + } + + // General message + echo '

' . sprintf(__('Are you enjoying this plugin? The Premium add-on unlocks several powerful features. Find out about all benefits now.', 'newsletter-for-wp'), 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=footer-link') . '

'; + } + + /** + * Add email opt-in form to sidebar + */ + public function admin_sidebar() + { + echo '
'; + echo '
'; + echo '

Newsletter for WordPress Premium

'; + echo '

This plugin has a Premium add-on, unlocking several powerful features. Have a look at its benefits!

'; + echo '
'; + echo '
'; ?>
-

-

+

+

- - + +

- - + +

- +

@@ -148,31 +152,32 @@ public function admin_sidebar() {
'; - echo '

Advanced WooCommerce integration for Newsletter

'; - echo '

'; - echo __( 'Do you want to track all WooCommerce orders in Newsletter so you can send emails based on the purchase activity of your subscribers?', 'newsletter-for-wp' ); - echo '

'; - echo '

'; - echo sprintf( __( 'Upgrade to Newsletter for WordPress Premium or read more about Newsletter\'s E-Commerce features.', 'newsletter-for-wp' ) . '

', 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=other-settings-link', 'https://kb.mc4wp.com/what-is-ecommerce360/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=other-settings-link' ); - echo '

'; - echo ''; - } - - public function show_extensions_page() { - require NL4WP_PLUGIN_DIR . 'includes/views/extensions.php'; - } - + } + + /** + * Show notice about E-Commerce integration in Premium. + */ + public function ecommerce() + { + + // detect whether WooCommerce is installed & activated. + if (! class_exists('WooCommerce')) { + return; + } + + echo '
'; + echo '

Advanced WooCommerce integration for Newsletter

'; + echo '

'; + echo __('Do you want to track all WooCommerce orders in Newsletter so you can send emails based on the purchase activity of your subscribers?', 'newsletter-for-wp'); + echo '

'; + echo '

'; + echo sprintf(__('Upgrade to Newsletter for WordPress Premium or read more about Newsletter\'s E-Commerce features.', 'newsletter-for-wp') . '

', 'https://mc4wp.com/premium-features/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=other-settings-link', 'https://kb.mc4wp.com/what-is-ecommerce360/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=other-settings-link'); + echo '

'; + echo '
'; + } + + public function show_extensions_page() + { + require NL4WP_PLUGIN_DIR . 'includes/views/extensions.php'; + } } diff --git a/includes/admin/class-review-notice.php b/includes/admin/class-review-notice.php index ad8c19b..d8d7d9b 100755 --- a/includes/admin/class-review-notice.php +++ b/includes/admin/class-review-notice.php @@ -5,7 +5,8 @@ * * @ignore */ -class NL4WP_Admin_Review_Notice { +class NL4WP_Admin_Review_Notice +{ /** * @var NL4WP_Admin_Tools @@ -22,58 +23,58 @@ class NL4WP_Admin_Review_Notice { * * @param NL4WP_Admin_Tools $tools */ - public function __construct( NL4WP_Admin_Tools $tools ) { + public function __construct(NL4WP_Admin_Tools $tools) + { $this->tools = $tools; } /** * Add action & filter hooks. */ - public function add_hooks() { - add_action( 'admin_notices', array( $this, 'show' ) ); - add_action( 'nl4wp_admin_dismiss_review_notice', array( $this, 'dismiss' ) ); + public function add_hooks() + { + add_action('admin_notices', array( $this, 'show' )); + add_action('nl4wp_admin_dismiss_review_notice', array( $this, 'dismiss' )); } /** * Set flag in user meta so notice won't be shown. */ - public function dismiss() { + public function dismiss() + { $user = wp_get_current_user(); - update_user_meta( $user->ID, $this->meta_key_dismissed, 1 ); + update_user_meta($user->ID, $this->meta_key_dismissed, 1); } /** * @return bool */ - public function show() { -/* NL_CHANGED - start -* non mostra nulla -*/ -return false; -/* NL_CHANGED - end */ + public function show() { return false; } /* NL_CHANGED */ + public function _disabled_show() + { // only show on Newsletter for WordPress' pages. - if( ! $this->tools->on_plugin_page() ) { + if (! $this->tools->on_plugin_page()) { return false; } // only show if 2 weeks have passed since first use. - $two_weeks_in_seconds = ( 60 * 60 * 24 * 14 ); - if( $this->time_since_first_use() <= $two_weeks_in_seconds ) { + $two_weeks_in_seconds = (60 * 60 * 24 * 14); + if ($this->time_since_first_use() <= $two_weeks_in_seconds) { return false; } // only show if user did not dismiss before $user = wp_get_current_user(); - if( get_user_meta( $user->ID, $this->meta_key_dismissed, true ) ) { + if (get_user_meta($user->ID, $this->meta_key_dismissed, true)) { return false; } echo '
'; echo '

'; - echo __( 'You\'ve been using Newsletter for WordPress for some time now; we hope you love it!', 'newsletter-for-wp' ) . '
'; - echo sprintf( __( 'If you do, please leave us a 5★ rating on WordPress.org. It would be of great help to us.', 'newsletter-for-wp' ), 'https://wordpress.org/support/view/plugin-reviews/newsletter-for-wp?rate=5#new-post' ); + echo __('You\'ve been using Newsletter for WordPress for some time now; we hope you love it!', 'newsletter-for-wp') . '
'; + echo sprintf(__('If you do, please leave us a 5★ rating on WordPress.org. It would be of great help to us.', 'newsletter-for-wp'), 'https://wordpress.org/support/view/plugin-reviews/newsletter-for-wp?rate=5#new-post'); echo '

'; - echo ''; + echo '
'; echo '
'; return true; } @@ -81,13 +82,14 @@ public function show() { /** * @return int */ - private function time_since_first_use() { - $options = get_option( 'nl4wp' ); + private function time_since_first_use() + { + $options = get_option('nl4wp'); // option was never added before, do it now. - if( empty( $options['first_activated_on'] ) ) { + if (empty($options['first_activated_on'])) { $options['first_activated_on'] = time(); - update_option( 'nl4wp', $options ); + update_option('nl4wp', $options); } return time() - $options['first_activated_on']; diff --git a/includes/admin/class-update-optin.php b/includes/admin/class-update-optin.php index a5874af..947ce45 100755 --- a/includes/admin/class-update-optin.php +++ b/includes/admin/class-update-optin.php @@ -1,6 +1,7 @@ to_version = $to_version; $this->plugin_file = $plugin_file; $this->view_file = $view_file; - $this->option_enable = 'nl4wp_enable_' . sanitize_key( $this->to_version ); - $this->option_notice = 'nl4wp_notice_' . sanitize_key( $this->to_version ); + $this->option_enable = 'nl4wp_enable_' . sanitize_key($this->to_version); + $this->option_notice = 'nl4wp_notice_' . sanitize_key($this->to_version); } /** * Add hooks */ - public function add_hooks() { - add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'maybe_hide_update' ) ); - add_action( 'init', array( $this, 'listen' ) ); + public function add_hooks() + { + add_filter('pre_set_site_transient_update_plugins', array( $this, 'maybe_hide_update' )); + add_action('init', array( $this, 'listen' )); global $pagenow; - $on_settings_page = isset( $_GET['page'] ) && stristr( $_GET['page'], dirname( $this->plugin_file ) ) !== false; - if( $pagenow === 'plugins.php' || $pagenow === 'update-core.php' || $on_settings_page ) { - add_action( 'admin_notices', array( $this, 'show_update_optin' ) ); + $on_settings_page = isset($_GET['page']) && stristr($_GET['page'], dirname($this->plugin_file)) !== false; + if ($pagenow === 'plugins.php' || $pagenow === 'update-core.php' || $on_settings_page) { + add_action('admin_notices', array( $this, 'show_update_optin' )); } } /** * Listen for actions */ - public function listen() { + public function listen() + { // only show to users with required capability - if( ! current_user_can( self::CAPABILITY ) ) { + if (! current_user_can(self::CAPABILITY)) { return; } - if( isset( $_GET[ $this->option_enable ] ) ) { + if (isset($_GET[ $this->option_enable ])) { $this->enable_major_updates(); } } @@ -84,36 +88,36 @@ public function listen() { * @param array $data * @return array */ - public function maybe_hide_update( $data ) { - - if( empty( $data->response ) ) { + public function maybe_hide_update($data) + { + if (empty($data->response)) { return $data; } // do nothing if the specified version is not out there yet.. - if( empty( $data->response[ $this->plugin_file ]->new_version ) - || version_compare( $data->response[ $this->plugin_file ]->new_version, $this->to_version, '<' ) ) { + if (empty($data->response[ $this->plugin_file ]->new_version) + || version_compare($data->response[ $this->plugin_file ]->new_version, $this->to_version, '<')) { // reset flags here in case we revert the update - if( ! $this->active ) { - delete_option( $this->option_notice ); - delete_option( $this->option_enable ); + if (! $this->active) { + delete_option($this->option_notice); + delete_option($this->option_enable); } return $data; } // return unmodified data if already opted-in - $opted_in = get_option( $this->option_enable, false ); - if( $opted_in ) { + $opted_in = get_option($this->option_enable, false); + if ($opted_in) { return $data; } // set a flag to start showing "update to x.x" notice - update_option( $this->option_notice, 1 ); + update_option($this->option_notice, 1); // unset update data - unset( $data->response[ $this->plugin_file ] ); + unset($data->response[ $this->plugin_file ]); // set flag because this filter runs multiple times.. $this->active = true; @@ -124,55 +128,57 @@ public function maybe_hide_update( $data ) { /** * Enables major updates (opts-in to 3.x update) */ - public function enable_major_updates() { + public function enable_major_updates() + { // update option - update_option( $this->option_enable, 1 ); + update_option($this->option_enable, 1); // delete site transient so wp core will fetch latest version - delete_site_transient( 'update_plugins' ); + delete_site_transient('update_plugins'); // redirect to updates page - wp_safe_redirect( admin_url( 'update-core.php' ) ); + wp_safe_redirect(admin_url('update-core.php')); exit; } /** * Shows update opt-in */ - public function show_update_optin() { - - if( ! $this->should_show_update_optin() ) { + public function show_update_optin() + { + if (! $this->should_show_update_optin()) { return; } // prepare link URL - $update_link = add_query_arg( array( $this->option_enable => 1 ) ); + $update_link = add_query_arg(array( $this->option_enable => 1 )); // show! - include $this->view_file; + include $this->view_file; } /** * @return bool */ - public function should_show_update_optin() { + public function should_show_update_optin() + { // don't show if flag is not set - if( ! get_option( $this->option_notice, false ) ) { + if (! get_option($this->option_notice, false)) { return false; } // stop showing if opted-in already - if( get_option( $this->option_enable, false ) ) { + if (get_option($this->option_enable, false)) { return false; } // only show to users with required capability - if( ! current_user_can( self::CAPABILITY ) ) { + if (! current_user_can(self::CAPABILITY)) { return false; } return true; } -} \ No newline at end of file +} diff --git a/includes/admin/class-upgrade-routines.php b/includes/admin/class-upgrade-routines.php index 21b0612..ecd5f98 100755 --- a/includes/admin/class-upgrade-routines.php +++ b/includes/admin/class-upgrade-routines.php @@ -8,82 +8,79 @@ * * @ignore */ -class NL4WP_Upgrade_Routines { - - /** - * @var float - */ - protected $version_from = 0; - - /** - * @var float - */ - protected $version_to = 0; - - /** - * @var string - */ - protected $migrations_dir = ''; - - /** - * @param float $from - * @param float $to - */ - public function __construct( $from, $to, $migrations_dir ) { - $this->version_from = $from; - $this->version_to = $to; - $this->migrations_dir = $migrations_dir; - } - - /** - * Run the various upgrade routines, all the way up to the latest version - */ - public function run() { - $migrations = $this->find_migrations(); - - // run in sub-function for scope - array_map( array( $this, 'run_migration' ), $migrations ); - } - - /** - * @return array - */ - public function find_migrations() { - - $files = glob( rtrim( $this->migrations_dir, '/' ) . '/*.php' ); - $migrations = array(); - - // return empty array when glob returns non-array value. - if( ! is_array( $files ) ) { - return $migrations; - } - - foreach( $files as $file ) { - $migration = basename( $file ); - $parts = explode( '-', $migration ); - $version = $parts[0]; - - if( version_compare( $this->version_from, $version, '<' ) ) { - $migrations[] = $file; - } - } - - return $migrations; - } - - /** - * Include a migration file and runs it. - * - * @param string $file - */ - protected function run_migration( $file ) { - include $file; - } - - - - - - - -} \ No newline at end of file +class NL4WP_Upgrade_Routines +{ + + /** + * @var float + */ + protected $version_from = 0; + + /** + * @var float + */ + protected $version_to = 0; + + /** + * @var string + */ + protected $migrations_dir = ''; + + /** + * @param float $from + * @param float $to + */ + public function __construct($from, $to, $migrations_dir) + { + $this->version_from = $from; + $this->version_to = $to; + $this->migrations_dir = $migrations_dir; + } + + /** + * Run the various upgrade routines, all the way up to the latest version + */ + public function run() + { + $migrations = $this->find_migrations(); + + // run in sub-function for scope + array_map(array( $this, 'run_migration' ), $migrations); + } + + /** + * @return array + */ + public function find_migrations() + { + $files = glob(rtrim($this->migrations_dir, '/') . '/*.php'); + $migrations = array(); + + // return empty array when glob returns non-array value. + if (! is_array($files)) { + return $migrations; + } + + foreach ($files as $file) { + $migration = basename($file); + $parts = explode('-', $migration); + $version = $parts[0]; + + if (version_compare($this->version_from, $version, '<')) { + $migrations[] = $file; + } + } + + return $migrations; + } + + /** + * Include a migration file and runs it. + * + * @param string $file + */ + protected function run_migration($file) + { + include $file; + } +} diff --git a/includes/admin/class-usage-tracking.php b/includes/admin/class-usage-tracking.php index 8fe449c..e982846 100755 --- a/includes/admin/class-usage-tracking.php +++ b/includes/admin/class-usage-tracking.php @@ -7,195 +7,213 @@ * @since 2.3 * @ignore */ -class NL4WP_Usage_Tracking { - - /** - * @var string - */ - protected $tracking_url = 'https://mc4wp.com/api/usage-tracking'; - - /** - * @var NL4WP_Usage_Tracking The One True Instance - */ - protected static $instance; - - /** - * @return NL4WP_Usage_Tracking - */ - public static function instance() { - - if( ! self::$instance instanceof NL4WP_Usage_Tracking ) { - self::$instance = new NL4WP_Usage_Tracking(); - } - - return self::$instance; - } - - /** - * Constructor - */ - public function __construct() {} - - /** - * Add hooks - */ - public function add_hooks() { - add_action( 'nl4wp_usage_tracking', array( $this, 'track' ) ); - add_filter( 'cron_schedules', array( $this, 'cron_schedules' ) ); - } - - /** - * Registers a new schedule with WP Cron - * - * @param array $schedules - * - * @return array - */ - public function cron_schedules( $schedules ) { - $schedules['monthly'] = array( - 'interval' => 30 * DAY_IN_SECONDS, - 'display' => __( 'Once a month' ) - ); - return $schedules; - } - - /** - * Enable usage tracking - * - * @return bool - */ - public function enable() { - // only schedule if not yet scheduled - if( ! wp_next_scheduled( 'nl4wp_usage_tracking' ) ) { - return wp_schedule_event( time(), 'monthly', 'nl4wp_usage_tracking' ); - } - - return true; - } - - /** - * Disable usage tracking - */ - public function disable() { - wp_clear_scheduled_hook( 'nl4wp_usage_tracking' ); - } - - /** - * Toggle tracking (clears & sets the scheduled tracking event) - * - * @param bool $enable - */ - public function toggle( $enable ) { - $enable ? $this->enable() : $this->disable(); - } - - /** - * Sends the tracking request. Non-blocking. - * - * @return bool - */ - public function track() { - $data = $this->get_tracking_data(); - - // send non-blocking request and be done with it - wp_remote_post( $this->tracking_url, array( - 'body' => json_encode( $data ), - 'headers' => array( - 'Content-Type' => 'application/json', - 'Accept' => 'application/json' - ), - 'blocking' => false, - ) - ); - - return true; - } - - /** - * @return array - */ - protected function get_tracking_data() { - - $data = array( - // use md5 hash of home_url, we don't need/want to know the actual site url - 'site' => md5( home_url() ), - 'number_of_newsletter_lists' => $this->get_newsletter_lists_count(), - 'nl4wp_version' => $this->get_nl4wp_version(), - 'nl4wp_premium_version' => $this->get_nl4wp_premium_version(), - 'plugins' => (array) get_option( 'active_plugins', array() ), - 'php_version' => $this->get_php_version(), - 'curl_version' => $this->get_curl_version(), - 'wp_version' => $GLOBALS['wp_version'], - 'wp_language' => get_locale(), - 'server_software' => $this->get_server_software(), - 'using_https' => $this->is_site_using_https() - ); - - return $data; - } - - public function get_php_version() { - if( ! defined('PHP_MAJOR_VERSION' ) ) { // defined since PHP 5.2.7 - return null; - } - - return PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION; - } - - /** - * @return string - */ - public function get_nl4wp_premium_version() { - return defined( 'NL4WP_PREMIUM_VERSION' ) ? NL4WP_PREMIUM_VERSION : null; - } - - /** - * Returns the Newsletter for WordPress version - * - * @return string - */ - protected function get_nl4wp_version() { - return NL4WP_VERSION; - } - - /** - * @return int - */ - protected function get_newsletter_lists_count() { - $newsletter = new NL4WP_Newsletter(); - $list_ids = $newsletter->get_list_ids( false ); - return count( $list_ids ); - } - - - /** - * @return string - */ - protected function get_curl_version() { - if( ! function_exists( 'curl_version' ) ) { - return null; - } - - $curl_version_info = curl_version(); - return $curl_version_info['version']; - } - - /** - * @return bool - */ - protected function is_site_using_https() { - $site_url = site_url(); - return stripos( $site_url, 'https' ) === 0; - } - - /** - * @return string - */ - protected function get_server_software() { - if( ! isset( $_SERVER['SERVER_SOFTWARE'] ) ) { - return null; - } - - return $_SERVER['SERVER_SOFTWARE']; - } +class NL4WP_Usage_Tracking +{ + + /** + * @var string + */ + protected $tracking_url = 'https://mc4wp.com/api/usage-tracking'; + + /** + * @var NL4WP_Usage_Tracking The One True Instance + */ + protected static $instance; + + /** + * @return NL4WP_Usage_Tracking + */ + public static function instance() + { + if (! self::$instance instanceof NL4WP_Usage_Tracking) { + self::$instance = new NL4WP_Usage_Tracking(); + } + + return self::$instance; + } + + /** + * Constructor + */ + public function __construct() + { + } + + /** + * Add hooks + */ + public function add_hooks() + { + add_action('nl4wp_usage_tracking', array( $this, 'track' )); + add_filter('cron_schedules', array( $this, 'cron_schedules' )); + } + + /** + * Registers a new schedule with WP Cron + * + * @param array $schedules + * + * @return array + */ + public function cron_schedules($schedules) + { + $schedules['monthly'] = array( + 'interval' => 30 * DAY_IN_SECONDS, + 'display' => __('Once a month') + ); + return $schedules; + } + + /** + * Enable usage tracking + * + * @return bool + */ + public function enable() + { + // only schedule if not yet scheduled + if (! wp_next_scheduled('nl4wp_usage_tracking')) { + return wp_schedule_event(time(), 'monthly', 'nl4wp_usage_tracking'); + } + + return true; + } + + /** + * Disable usage tracking + */ + public function disable() + { + wp_clear_scheduled_hook('nl4wp_usage_tracking'); + } + + /** + * Toggle tracking (clears & sets the scheduled tracking event) + * + * @param bool $enable + */ + public function toggle($enable) + { + $enable ? $this->enable() : $this->disable(); + } + + /** + * Sends the tracking request. Non-blocking. + * + * @return bool + */ + public function track() + { + $data = $this->get_tracking_data(); + + // send non-blocking request and be done with it + wp_remote_post( + $this->tracking_url, + array( + 'body' => json_encode($data), + 'headers' => array( + 'Content-Type' => 'application/json', + 'Accept' => 'application/json' + ), + 'blocking' => false, + ) + ); + + return true; + } + + /** + * @return array + */ + protected function get_tracking_data() + { + $data = array( + // use md5 hash of home_url, we don't need/want to know the actual site url + 'site' => md5(home_url()), + 'number_of_newsletter_lists' => $this->get_newsletter_lists_count(), + 'nl4wp_version' => $this->get_nl4wp_version(), + 'nl4wp_premium_version' => $this->get_nl4wp_premium_version(), + 'plugins' => (array) get_option('active_plugins', array()), + 'php_version' => $this->get_php_version(), + 'curl_version' => $this->get_curl_version(), + 'wp_version' => $GLOBALS['wp_version'], + 'wp_language' => get_locale(), + 'server_software' => $this->get_server_software(), + 'using_https' => $this->is_site_using_https() + ); + + return $data; + } + + public function get_php_version() + { + if (! defined('PHP_MAJOR_VERSION')) { // defined since PHP 5.2.7 + return null; + } + + return PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION; + } + + /** + * @return string + */ + public function get_nl4wp_premium_version() + { + return defined('NL4WP_PREMIUM_VERSION') ? NL4WP_PREMIUM_VERSION : null; + } + + /** + * Returns the Newsletter for WordPress version + * + * @return string + */ + protected function get_nl4wp_version() + { + return NL4WP_VERSION; + } + + /** + * @return int + */ + protected function get_newsletter_lists_count() + { + $newsletter = new NL4WP_Newsletter(); + $list_ids = $newsletter->get_list_ids(false); + return count($list_ids); + } + + + /** + * @return string + */ + protected function get_curl_version() + { + if (! function_exists('curl_version')) { + return null; + } + + $curl_version_info = curl_version(); + return $curl_version_info['version']; + } + + /** + * @return bool + */ + protected function is_site_using_https() + { + $site_url = site_url(); + return stripos($site_url, 'https') === 0; + } + + /** + * @return string + */ + protected function get_server_software() + { + if (! isset($_SERVER['SERVER_SOFTWARE'])) { + return null; + } + + return $_SERVER['SERVER_SOFTWARE']; + } } diff --git a/includes/admin/migrations/3.0.0-form-1-post-type.php b/includes/admin/migrations/3.0.0-form-1-post-type.php index 54db5f1..71d2b8d 100755 --- a/includes/admin/migrations/3.0.0-form-1-post-type.php +++ b/includes/admin/migrations/3.0.0-form-1-post-type.php @@ -1,91 +1,89 @@ 'nl4wp-form', - 'post_status' => 'publish', - 'numberposts' => 1 - ) + array( + 'post_type' => 'nl4wp-form', + 'post_status' => 'publish', + 'numberposts' => 1 + ) ); // There are forms already, don't continue. -if( ! empty( $has_forms ) ) { +if (! empty($has_forms)) { - // delete option as it apparently exists. - delete_option( 'nl4wp_lite_form' ); - return; + // delete option as it apparently exists. + delete_option('nl4wp_lite_form'); + return; } // create post type for form $id = wp_insert_post( - array( - 'post_type' => 'nl4wp-form', - 'post_status' => 'publish', - 'post_title' => __( 'Default sign-up form', 'newsletter-for-wp' ), - 'post_content' => ( empty( $form_options['markup'] ) ) ? '' : $form_options['markup'], - ) + array( + 'post_type' => 'nl4wp-form', + 'post_status' => 'publish', + 'post_title' => __('Default sign-up form', 'newsletter-for-wp'), + 'post_content' => (empty($form_options['markup'])) ? '' : $form_options['markup'], + ) ); // set default_form_id -update_option( 'nl4wp_default_form_id', $id ); +update_option('nl4wp_default_form_id', $id); // set form settings $setting_keys = array( - 'css', - 'custom_theme_color', - 'double_optin', - 'update_existing', - 'replace_interests', - 'send_welcome', - 'redirect', - 'hide_after_success' + 'css', + 'custom_theme_color', + 'double_optin', + 'update_existing', + 'replace_interests', + 'send_welcome', + 'redirect', + 'hide_after_success' ); $settings = array(); -foreach( $setting_keys as $setting_key ) { - // use isset to account for "0" settings - if( isset( $form_options[ $setting_key ] ) ) { - $settings[ $setting_key ] = $form_options[ $setting_key ]; - } +foreach ($setting_keys as $setting_key) { + // use isset to account for "0" settings + if (isset($form_options[ $setting_key ])) { + $settings[ $setting_key ] = $form_options[ $setting_key ]; + } } // get only keys of lists setting -if( isset( $form_options['lists'] ) ) { - $settings['lists'] = array_keys( $form_options['lists'] ); +if (isset($form_options['lists'])) { + $settings['lists'] = array_keys($form_options['lists']); } -update_post_meta( $id, '_nl4wp_settings', $settings ); +update_post_meta($id, '_nl4wp_settings', $settings); // set form message texts $message_keys = array( - 'text_subscribed', - 'text_error', - 'text_invalid_email', - 'text_already_subscribed', - 'text_required_field_missing', - 'text_unsubscribed', - 'text_not_subscribed' + 'text_subscribed', + 'text_error', + 'text_invalid_email', + 'text_already_subscribed', + 'text_required_field_missing', + 'text_unsubscribed', + 'text_not_subscribed' ); -foreach( $message_keys as $message_key ) { - - if( ! empty( $form_options[ $message_key ] ) ) { - update_post_meta( $id, $message_key, $form_options[ $message_key ] ); - } - +foreach ($message_keys as $message_key) { + if (! empty($form_options[ $message_key ])) { + update_post_meta($id, $message_key, $form_options[ $message_key ]); + } } // delete old option -delete_option( 'nl4wp_lite_form' ); \ No newline at end of file +delete_option('nl4wp_lite_form'); diff --git a/includes/admin/migrations/3.0.0-form-2-options.php b/includes/admin/migrations/3.0.0-form-2-options.php index 379ceec..4e64bf0 100755 --- a/includes/admin/migrations/3.0.0-form-2-options.php +++ b/includes/admin/migrations/3.0.0-form-2-options.php @@ -1,65 +1,65 @@ 'nl4wp-form', - 'post_status' => 'publish', - 'numberposts' => -1 - ) + array( + 'post_type' => 'nl4wp-form', + 'post_status' => 'publish', + 'numberposts' => -1 + ) ); $css_map = array( - 'default' => 'basic', - 'custom' => 'styles-builder', - 'light' => 'theme-light', - 'dark' => 'theme-dark', - 'red' => 'theme-red', - 'green' => 'theme-green', - 'blue' => 'theme-blue', - 'custom-color' => 'theme-custom-color' + 'default' => 'basic', + 'custom' => 'styles-builder', + 'light' => 'theme-light', + 'dark' => 'theme-dark', + 'red' => 'theme-red', + 'green' => 'theme-green', + 'blue' => 'theme-blue', + 'custom-color' => 'theme-custom-color' ); $stylesheets = array(); -foreach( $posts as $post ) { +foreach ($posts as $post) { - // get form options from post meta directly - $options = (array) get_post_meta( $post->ID, '_nl4wp_settings', true ); + // get form options from post meta directly + $options = (array) get_post_meta($post->ID, '_nl4wp_settings', true); - // store all global options in scoped form settings - // do this BEFORE changing css key, so we take that as well. - foreach( $global_options as $key => $value ) { - if( strlen( $value ) > 0 && ( ! isset( $options[ $key ] ) || strlen( $options[ $key ] ) == 0 ) ) { - $options[ $key ] = $value; - } - } + // store all global options in scoped form settings + // do this BEFORE changing css key, so we take that as well. + foreach ($global_options as $key => $value) { + if (strlen($value) > 0 && (! isset($options[ $key ]) || strlen($options[ $key ]) == 0)) { + $options[ $key ] = $value; + } + } - // update "css" option value - if( isset( $options['css'] ) && isset( $css_map[ $options['css'] ] ) ) { - $options['css'] = $css_map[ $options['css'] ]; - } + // update "css" option value + if (isset($options['css']) && isset($css_map[ $options['css'] ])) { + $options['css'] = $css_map[ $options['css'] ]; + } - // create stylesheets option - if( ! empty( $options['css'] ) ) { - $stylesheet = $options['css']; - if( strpos( $stylesheet, 'theme-' ) === 0 ) { - $stylesheet = 'themes'; - } + // create stylesheets option + if (! empty($options['css'])) { + $stylesheet = $options['css']; + if (strpos($stylesheet, 'theme-') === 0) { + $stylesheet = 'themes'; + } - if( ! in_array( $stylesheet, $stylesheets ) ) { - $stylesheets[] = $stylesheet; - } - } + if (! in_array($stylesheet, $stylesheets)) { + $stylesheets[] = $stylesheet; + } + } - update_post_meta( $post->ID, '_nl4wp_settings', $options ); + update_post_meta($post->ID, '_nl4wp_settings', $options); } // update stylesheets option -update_option( 'nl4wp_form_stylesheets', $stylesheets ); +update_option('nl4wp_form_stylesheets', $stylesheets); // delete old options -delete_option( 'nl4wp_form' ); \ No newline at end of file +delete_option('nl4wp_form'); diff --git a/includes/admin/migrations/3.0.0-form-3-messages.php b/includes/admin/migrations/3.0.0-form-3-messages.php index 3286178..a076de9 100755 --- a/includes/admin/migrations/3.0.0-form-3-messages.php +++ b/includes/admin/migrations/3.0.0-form-3-messages.php @@ -1,42 +1,41 @@ 'nl4wp-form', - 'post_status' => 'publish', - 'numberposts' => -1 - ) + array( + 'post_type' => 'nl4wp-form', + 'post_status' => 'publish', + 'numberposts' => -1 + ) ); // set form message texts $message_keys = array( - 'text_subscribed', - 'text_error', - 'text_invalid_email', - 'text_already_subscribed', - 'text_required_field_missing', - 'text_unsubscribed', - 'text_not_subscribed' + 'text_subscribed', + 'text_error', + 'text_invalid_email', + 'text_already_subscribed', + 'text_required_field_missing', + 'text_unsubscribed', + 'text_not_subscribed' ); -foreach( $posts as $post ) { +foreach ($posts as $post) { + $settings = get_post_meta($post->ID, '_nl4wp_settings', true); - $settings = get_post_meta( $post->ID, '_nl4wp_settings', true ); + foreach ($message_keys as $key) { + if (empty($settings[ $key ])) { + continue; + } - foreach( $message_keys as $key ) { - if( empty( $settings[ $key ] ) ) { - continue; - } + $message = $settings[ $key ]; - $message = $settings[ $key ]; + // move message setting over to post meta + update_post_meta($post->ID, $key, $message); + unset($settings[ $key ]); + } - // move message setting over to post meta - update_post_meta( $post->ID, $key, $message ); - unset( $settings[ $key ] ); - } - - // update post meta with unset message keys - update_post_meta( $post->ID, '_nl4wp_settings', $settings ); -} \ No newline at end of file + // update post meta with unset message keys + update_post_meta($post->ID, '_nl4wp_settings', $settings); +} diff --git a/includes/admin/migrations/3.0.0-general-options.php b/includes/admin/migrations/3.0.0-general-options.php index 10b4ef4..3e57b98 100755 --- a/includes/admin/migrations/3.0.0-general-options.php +++ b/includes/admin/migrations/3.0.0-general-options.php @@ -1,17 +1,16 @@ 'wp-comment-form', - 'registration_form' => 'wp-registration-form', - 'buddypress_form' => 'buddypress', - 'bbpres_forms' => 'bbpress', - 'woocommerce_checkout' => 'woocommerce', - 'edd_checkout' => 'easy-digital-downloads' + 'comment_form' => 'wp-comment-form', + 'registration_form' => 'wp-registration-form', + 'buddypress_form' => 'buddypress', + 'bbpres_forms' => 'bbpress', + 'woocommerce_checkout' => 'woocommerce', + 'edd_checkout' => 'easy-digital-downloads' ); $option_keys = array( - 'label', - 'precheck', - 'css', - 'lists', - 'double_optin', - 'update_existing', - 'replace_interests', - 'send_welcome', + 'label', + 'precheck', + 'css', + 'lists', + 'double_optin', + 'update_existing', + 'replace_interests', + 'send_welcome', ); -foreach( $map as $old_integration_slug => $new_integration_slug ) { +foreach ($map as $old_integration_slug => $new_integration_slug) { - // check if integration is enabled using its old slug - $show_key = sprintf( 'show_at_%s', $old_integration_slug ); - if( empty( $old_options[ $show_key ] ) ) { - continue; - } + // check if integration is enabled using its old slug + $show_key = sprintf('show_at_%s', $old_integration_slug); + if (empty($old_options[ $show_key ])) { + continue; + } - $options = array( - 'enabled' => 1 - ); + $options = array( + 'enabled' => 1 + ); - foreach( $option_keys as $option_key ) { - if( isset( $old_options[ $option_key ] ) ) { - $options[ $option_key ] = $old_options[ $option_key ]; - } - } + foreach ($option_keys as $option_key) { + if (isset($old_options[ $option_key ])) { + $options[ $option_key ] = $old_options[ $option_key ]; + } + } - // add to new options - $new_options[ $new_integration_slug ] = $options; + // add to new options + $new_options[ $new_integration_slug ] = $options; } // save new settings -update_option( 'nl4wp_integrations', $new_options ); +update_option('nl4wp_integrations', $new_options); // delete old options -delete_option( 'nl4wp_lite_checkbox' ); -delete_option( 'nl4wp_checkbox' ); - +delete_option('nl4wp_lite_checkbox'); +delete_option('nl4wp_checkbox'); diff --git a/includes/admin/migrations/3.0.0-styles-builder.php b/includes/admin/migrations/3.0.0-styles-builder.php index 4cf1888..1d1fd27 100755 --- a/includes/admin/migrations/3.0.0-styles-builder.php +++ b/includes/admin/migrations/3.0.0-styles-builder.php @@ -1,42 +1,42 @@ $widgets ) { +foreach ($section_widgets as $section => $widgets) { - // WP has an "array_version" key that is not an array... - if( ! is_array( $widgets ) ) { - continue; - } + // WP has an "array_version" key that is not an array... + if (! is_array($widgets)) { + continue; + } - // loop through widget ID's - foreach( $widgets as $key => $widget_id ) { + // loop through widget ID's + foreach ($widgets as $key => $widget_id) { - // does this widget ID start with "nl4wp_widget"? - if( strpos( $widget_id, 'nl4wp_widget' ) === 0 ) { + // does this widget ID start with "nl4wp_widget"? + if (strpos($widget_id, 'nl4wp_widget') === 0) { - // replace "nl4wp_widget" with "nl4wp_form_widget" - $new_widget_id = str_replace( 'nl4wp_widget', 'nl4wp_form_widget', $widget_id ); - $section_widgets[ $section ][ $key ] = $new_widget_id; - $replaced = true; - } - } + // replace "nl4wp_widget" with "nl4wp_form_widget" + $new_widget_id = str_replace('nl4wp_widget', 'nl4wp_form_widget', $widget_id); + $section_widgets[ $section ][ $key ] = $new_widget_id; + $replaced = true; + } + } } // update option if we made changes -if( $replaced ) { - update_option( 'sidebars_widgets', $section_widgets ); +if ($replaced) { + update_option('sidebars_widgets', $section_widgets); } // update widget options -$options = get_option( 'widget_nl4wp_widget', false ); -if( $options ) { - update_option( 'widget_nl4wp_form_widget', $options ); +$options = get_option('widget_nl4wp_widget', false); +if ($options) { + update_option('widget_nl4wp_form_widget', $options); - // delete old option - delete_option( 'widget_nl4wp_widget' ); + // delete old option + delete_option('widget_nl4wp_widget'); } - diff --git a/includes/admin/migrations/3.0.3-usage-tracking-schedule.php b/includes/admin/migrations/3.0.3-usage-tracking-schedule.php index ed1d683..88581a2 100755 --- a/includes/admin/migrations/3.0.3-usage-tracking-schedule.php +++ b/includes/admin/migrations/3.0.3-usage-tracking-schedule.php @@ -1,9 +1,9 @@ 30 * DAY_IN_SECONDS, - 'display' => 'Once a month' - ); +function _nl4wp_303_add_monthly_cron_schedule($schedules) +{ + $schedules['monthly'] = array( + 'interval' => 30 * DAY_IN_SECONDS, + 'display' => 'Once a month' + ); - return $schedules; + return $schedules; } -add_filter( 'cron_schedules', '_nl4wp_303_add_monthly_cron_schedule', 1 ); +add_filter('cron_schedules', '_nl4wp_303_add_monthly_cron_schedule', 1); // reschedule usage tracking event -wp_clear_scheduled_hook( 'nl4wp_usage_tracking' ); -wp_schedule_event( time(), 'monthly', 'nl4wp_usage_tracking' ); \ No newline at end of file +wp_clear_scheduled_hook('nl4wp_usage_tracking'); +wp_schedule_event(time(), 'monthly', 'nl4wp_usage_tracking'); diff --git a/includes/admin/migrations/3.1.6-woocommerce-position-prefix.php b/includes/admin/migrations/3.1.6-woocommerce-position-prefix.php index 98fd2eb..08b35c8 100755 --- a/includes/admin/migrations/3.1.6-woocommerce-position-prefix.php +++ b/includes/admin/migrations/3.1.6-woocommerce-position-prefix.php @@ -1,11 +1,11 @@ name === $interest_category->title ) { + if ($grouping->name === $interest_category->title) { return $grouping; } } @@ -23,9 +24,10 @@ function _nl4wp_400_find_grouping_for_interest_category( $groupings, $interest_c * @ignore * @return object */ -function _nl4wp_400_find_group_for_interest( $groups, $interest ) { - foreach( $groups as $group_id => $group_name ) { - if( $group_name === $interest->name ) { +function _nl4wp_400_find_group_for_interest($groups, $interest) +{ + foreach ($groups as $group_id => $group_name) { + if ($group_name === $interest->name) { return (object) array( 'name' => $group_name, 'id' => $group_id @@ -37,63 +39,63 @@ function _nl4wp_400_find_group_for_interest( $groups, $interest ) { } // in case the migration is _very_ late to the party -if( ! class_exists( 'NL4WP_API_v3' ) ) { +if (! class_exists('NL4WP_API_v3')) { return; } -$options = get_option( 'nl4wp', array() ); -if( empty( $options['api_key'] ) ) { +$options = get_option('nl4wp', array()); +if (empty($options['api_key'])) { return; } // get current state from transient -$lists = get_transient( 'nl4wp_newsletter_lists_fallback' ); -if( empty( $lists ) ) { +$lists = get_transient('nl4wp_newsletter_lists_fallback'); +if (empty($lists)) { return; } @set_time_limit(600); -$api_v3 = new NL4WP_API_v3( $options['api_key'] ); +$api_v3 = new NL4WP_API_v3($options['api_key']); $map = array(); -foreach( $lists as $list ) { +foreach ($lists as $list) { // cast to stdClass because of missing classes $list = (object) (array) $list; // no groupings? easy! - if( empty( $list->groupings ) ) { + if (empty($list->groupings)) { continue; } // fetch (new) interest categories for this list try { - $interest_categories = $api_v3->get_list_interest_categories( $list->id ); - } catch( NL4WP_API_Exception $e ) { + $interest_categories = $api_v3->get_list_interest_categories($list->id); + } catch (NL4WP_API_Exception $e) { continue; } - foreach( $interest_categories as $interest_category ) { + foreach ($interest_categories as $interest_category) { // compare interest title with grouping name, if it matches, get new id. - $grouping = _nl4wp_400_find_grouping_for_interest_category( $list->groupings, $interest_category ); - if( ! $grouping ) { + $grouping = _nl4wp_400_find_grouping_for_interest_category($list->groupings, $interest_category); + if (! $grouping) { continue; } $groups = array(); try { - $interests = $api_v3->get_list_interest_category_interests( $list->id, $interest_category->id ); - } catch( NL4WP_API_Exception $e ) { + $interests = $api_v3->get_list_interest_category_interests($list->id, $interest_category->id); + } catch (NL4WP_API_Exception $e) { continue; } - foreach( $interests as $interest ) { - $group = _nl4wp_400_find_group_for_interest( $grouping->groups, $interest ); + foreach ($interests as $interest) { + $group = _nl4wp_400_find_group_for_interest($grouping->groups, $interest); - if( $group ) { + if ($group) { $groups[ $group->id ] = $interest->id; $groups[ $group->name ] = $interest->id; } @@ -107,6 +109,6 @@ function _nl4wp_400_find_group_for_interest( $groups, $interest ) { } -if( ! empty( $map ) ) { - update_option( 'nl4wp_groupings_map', $map ); +if (! empty($map)) { + update_option('nl4wp_groupings_map', $map); } diff --git a/includes/admin/migrations/4.0.0-hidden-fields-value-delimiter.php b/includes/admin/migrations/4.0.0-hidden-fields-value-delimiter.php index 8071a60..b29ea4e 100755 --- a/includes/admin/migrations/4.0.0-hidden-fields-value-delimiter.php +++ b/includes/admin/migrations/4.0.0-hidden-fields-value-delimiter.php @@ -1,26 +1,27 @@ 'nl4wp-form', 'numberposts' => -1 ) ); +$posts = get_posts(array( 'post_type' => 'nl4wp-form', 'numberposts' => -1 )); -foreach( $posts as $post ) { +foreach ($posts as $post) { // find hidden field values in form and pass through replace function $old = $post->post_content; - $new = preg_replace_callback( '/type="hidden" .* value="(.*)"/i', '_nl4wp_400_replace_comma_with_pipe', $old ); + $new = preg_replace_callback('/type="hidden" .* value="(.*)"/i', '_nl4wp_400_replace_comma_with_pipe', $old); // update post if we replaced something - if( $new != $old ) { + if ($new != $old) { $post->post_content = $new; - wp_update_post( $post ); + wp_update_post($post); } -} \ No newline at end of file +} diff --git a/includes/admin/migrations/4.0.7-rename-debug-log-file.php b/includes/admin/migrations/4.0.7-rename-debug-log-file.php index 861eb64..91dd41d 100755 --- a/includes/admin/migrations/4.0.7-rename-debug-log-file.php +++ b/includes/admin/migrations/4.0.7-rename-debug-log-file.php @@ -1,36 +1,33 @@ '; - if( strpos( $line, $php_exit_string ) !== 0 ) { - rewind( $handle); - fwrite( $handle, $php_exit_string . PHP_EOL . $line ); + if (strpos($line, $php_exit_string) !== 0) { + rewind($handle); + fwrite($handle, $php_exit_string . PHP_EOL . $line); } - fclose( $handle ); + fclose($handle); } } - - - diff --git a/includes/admin/migrations/4.1.2-flush-list-cache.php b/includes/admin/migrations/4.1.2-flush-list-cache.php index 5d4f10d..ef24110 100755 --- a/includes/admin/migrations/4.1.2-flush-list-cache.php +++ b/includes/admin/migrations/4.1.2-flush-list-cache.php @@ -1,13 +1,12 @@ -client = new NL4WP_API_v3_Client( $api_key ); - } - - /** - * Gets the API client to perform raw API calls. - * - * @return NL4WP_API_v3_Client - */ - public function get_client() { - return $this->client; - } - - /** - * Pings the Newsletter API to see if we're connected - * - * @return boolean - * @throws NL4WP_API_Exception - */ - public function is_connected() { - $data = $this->client->get( '/', array( 'fields' => 'account_id' ) ); - $connected = is_object( $data ) && isset( $data->account_id ); - return $connected; - } - - /** - * @param $email_address - * - * @return string - */ - public function get_subscriber_hash( $email_address ) { - return base64_encode( strtolower( trim( $email_address ) ) ); - } - - /** - * Get recent daily, aggregated activity stats for a list. - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/activity/#read-get_lists_list_id_activity - * - * @param string $list_id - * @param array $args - * - * @return array - * @throws NL4WP_API_Exception - */ - public function get_list_activity( $list_id, array $args = array() ) { - $resource = sprintf( '/lists/%s/activity', $list_id ); - $data = $this->client->get( $resource, $args ); - - if( is_object( $data ) && isset( $data->activity ) ) { - return $data->activity; - } - - return array(); - } - - /** - * Gets the interest categories for a given List - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/interest-categories/#read-get_lists_list_id_interest_categories - * - * @param string $list_id - * @param array $args - * - * @return array - * @throws NL4WP_API_Exception - */ - public function get_list_interest_categories( $list_id, array $args = array() ) { - $resource = sprintf( '/lists/%s/interest-categories', $list_id ); - $data = $this->client->get( $resource, $args ); - - if( is_object( $data ) && isset( $data->categories ) ) { - return $data->categories; - } - - return array(); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/interest-categories/interests/#read-get_lists_list_id_interest_categories_interest_category_id_interests - * - * @param string $list_id - * @param string $interest_category_id - * @param array $args - * - * @return array - * @throws NL4WP_API_Exception - */ - public function get_list_interest_category_interests( $list_id, $interest_category_id, array $args = array() ) { - $resource = sprintf( '/lists/%s/interest-categories/%s/interests', $list_id, $interest_category_id ); - $data = $this->client->get( $resource, $args ); - - if( is_object( $data ) && isset( $data->interests ) ) { - return $data->interests; - } - - return array(); - } - - /** - * Get merge vars for a given list - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/merge-fields/#read-get_lists_list_id_merge_fields - * - * @param string $list_id - * @param array $args - * - * @return array - * @throws NL4WP_API_Exception - */ - public function get_list_merge_fields( $list_id, array $args = array() ) { - $resource = sprintf( '/lists/%s/merge-fields', $list_id ); - $data = $this->client->get( $resource, $args ); - - if( is_object( $data ) && isset( $data->merge_fields ) ) { - return $data->merge_fields; - } - - return array(); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/#read-get_lists_list_id - * - * @param string $list_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_list( $list_id, array $args = array() ) { - $resource = sprintf( '/lists/%s', $list_id ); - $data = $this->client->get( $resource, $args ); - return $data; - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/#read-get_lists - * - * @param array $args - * - * @return array - * @throws NL4WP_API_Exception - */ - public function get_lists( $args = array() ) { - $resource = '/lists'; - $data = $this->client->get( $resource, $args ); - - if( is_object( $data ) && isset( $data->lists ) ) { - return $data->lists; - } - - return array(); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/ - * - * @param string $list_id - * @param string $email_address - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_list_member( $list_id, $email_address, array $args = array() ) { - $subscriber_hash = $this->get_subscriber_hash( $email_address ); - $resource = sprintf( '/lists/%s/members/%s', $list_id, $subscriber_hash ); - $data = $this->client->get( $resource, $args ); - return $data; - } - - /** - * Batch subscribe / unsubscribe list members. - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/#create-post_lists_list_id - * - * @param string $list_id - * @param array $args - * @return object - * @throws NL4WP_API_Exception - */ - public function add_list_members( $list_id, array $args ) { - $resource = sprintf( '/lists/%s', $list_id ); - return $this->client->post( $resource, $args ); - } - - /** - * Add or update (!) a member to a Newsletter list. - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/#create-post_lists_list_id_members - * - * @param string $list_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_list_member( $list_id, array $args ) { - $subscriber_hash = $this->get_subscriber_hash( $args['email_address'] ); - $resource = sprintf( '/lists/%s/members/%s', $list_id, $subscriber_hash ); - - // make sure we're sending an object as the Newsletter schema requires this - if( isset( $args['merge_fields'] ) ) { - $args['merge_fields'] = (object) $args['merge_fields']; - } - - if( isset( $args['interests'] ) ) { - $args['interests'] = (object) $args['interests']; - } - - // "put" updates the member if it's already on the list... take notice - $data = $this->client->put( $resource, $args ); - return $data; - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/#edit-patch_lists_list_id_members_subscriber_hash - * - * @param $list_id - * @param $email_address - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_list_member( $list_id, $email_address, array $args ) { - $subscriber_hash = $this->get_subscriber_hash( $email_address ); - $resource = sprintf( '/lists/%s/members/%s', $list_id, $subscriber_hash ); - - // make sure we're sending an object as the Newsletter schema requires this - if( isset( $args['merge_fields'] ) ) { - $args['merge_fields'] = (object) $args['merge_fields']; - } - - if( isset( $args['interests'] ) ) { - $args['interests'] = (object) $args['interests']; - } - - $data = $this->client->patch( $resource, $args ); - return $data; - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/ - * - * @param string $list_id - * @param string $email_address - * - * @return bool - * @throws NL4WP_API_Exception - */ - public function delete_list_member( $list_id, $email_address ) { - $subscriber_hash = $this->get_subscriber_hash( $email_address ); - $resource = sprintf( '/lists/%s/members/%s', $list_id, $subscriber_hash ); - $data = $this->client->delete( $resource ); - return !!$data; - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#read-get_ecommerce_stores - * - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_stores( array $args = array() ) { - $resource = '/ecommerce/stores'; - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#read-get_ecommerce_stores_store_id - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store( $store_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s', $store_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#create-post_ecommerce_stores - * - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store( array $args ) { - $resource = '/ecommerce/stores'; - return $this->client->post( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#edit-patch_ecommerce_stores_store_id - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store( $store_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s', $store_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#delete-delete_ecommerce_stores_store_id - * - * @param string $store_id - * - * @return boolean - * @throws NL4WP_API_Exception - */ - public function delete_ecommerce_store( $store_id ) { - $resource = sprintf( '/ecommerce/stores/%s', $store_id ); - return !!$this->client->delete( $resource ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#read-get_ecommerce_stores_store_id_customers - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_customers( $store_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/customers', $store_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#read-get_ecommerce_stores_store_id_customers_customer_id - * - * @param string $store_id - * @param string $customer_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_customer( $store_id, $customer_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/customers/%s', $store_id, $customer_id ); - return $this->client->get( $resource, $args ); - } - - /** - * Add OR update a store customer - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#edit-put_ecommerce_stores_store_id_customers_customer_id - * - * @param $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store_customer( $store_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/customers/%s', $store_id, $args['id'] ); - return $this->client->put( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#edit-patch_ecommerce_stores_store_id_customers_customer_id - * - * @param string $store_id - * @param string $customer_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store_customer( $store_id, $customer_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/customers/%s', $store_id, $customer_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#delete-delete_ecommerce_stores_store_id_customers_customer_id - * - * @param string $store_id - * @param string $customer_id - * - * @return bool - * @throws NL4WP_API_Exception - */ - public function delete_ecommerce_store_customer( $store_id, $customer_id ) { - $resource = sprintf( '/ecommerce/stores/%s/customers/%s', $store_id, $customer_id ); - return !!$this->client->delete( $resource ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#read-get_ecommerce_stores_store_id_products - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_products( $store_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/products', $store_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#read-get_ecommerce_stores_store_id_products_product_id - * - * @param string $store_id - * @param string $product_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_product( $store_id, $product_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/products/%s', $store_id, $product_id ); - return $this->client->get( $resource, $args ); - } - - /** - * Add a product to a store - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#create-post_ecommerce_stores_store_id_products - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store_product( $store_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/products', $store_id ); - return $this->client->post( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#edit-patch_ecommerce_stores_store_id_products_product_id - * - * @param string $store_id - * @param string $product_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store_product( $store_id, $product_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/products/%s', $store_id, $product_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#delete-delete_ecommerce_stores_store_id_products_product_id - * - * @param string $store_id - * @param string $product_id - * - * @return boolean - * @throws NL4WP_API_Exception - */ - public function delete_ecommerce_store_product( $store_id, $product_id ) { - $resource = sprintf( '/ecommerce/stores/%s/products/%s', $store_id, $product_id ); - return !!$this->client->delete( $resource ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#read-get_ecommerce_stores_store_id_products_product_id_variants - * - * @param string $store_id - * @param string $product_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_product_variants( $store_id, $product_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/products/%s/variants', $store_id, $product_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#read-get_ecommerce_stores_store_id_products_product_id_variants_variant_id - * - * @param string $store_id - * @param string $product_id - * @param string $variant_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_product_variant( $store_id, $product_id, $variant_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/products/%s/variants/%s', $store_id, $product_id, $variant_id ); - return $this->client->get( $resource, $args ); - } - - /** - * Add OR update a product variant. - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#edit-put_ecommerce_stores_store_id_products_product_id_variants_variant_id - * - * @param string $store_id - * @param string $product_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store_product_variant( $store_id, $product_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/products/%s/variants/%s', $store_id, $product_id, $args['id'] ); - return $this->client->put( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#edit-patch_ecommerce_stores_store_id_products_product_id_variants_variant_id - * - * @param string $store_id - * @param string $product_id - * @param string $variant_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store_product_variant( $store_id, $product_id, $variant_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/products/%s/variants/%s', $store_id, $product_id, $variant_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#delete-delete_ecommerce_stores_store_id_products_product_id_variants_variant_id - * - * @param string $store_id - * @param string $product_id - * @param string $variant_id - * - * @return boolean - * @throws NL4WP_API_Exception - */ - public function delete_ecommerce_store_product_variant( $store_id, $product_id, $variant_id ) { - $resource = sprintf( '/ecommerce/stores/%s/products/%s/variants/%s', $store_id, $product_id, $variant_id ); - return !!$this->client->delete( $resource ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#read-get_ecommerce_stores_store_id_orders - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_orders( $store_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/orders', $store_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#read-get_ecommerce_stores_store_id_orders_order_id - * - * @param string $store_id - * @param string $order_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_order( $store_id, $order_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/orders/%s', $store_id, $order_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#create-post_ecommerce_stores_store_id_orders - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store_order( $store_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/orders', $store_id ); - return $this->client->post( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#edit-patch_ecommerce_stores_store_id_orders_order_id - * - * @param string $store_id - * @param string $order_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store_order( $store_id, $order_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/orders/%s', $store_id, $order_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#delete-delete_ecommerce_stores_store_id_orders_order_id - * - * @param string $store_id - * @param string $order_id - * - * @return bool - * @throws NL4WP_API_Exception - */ - public function delete_ecommerce_store_order( $store_id, $order_id ) { - return !! $this->client->delete( sprintf( '/ecommerce/stores/%s/orders/%s', $store_id, $order_id ) ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#create-post_ecommerce_stores_store_id_orders_order_id_lines - * - * @param string $store_id - * @param string $order_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store_order_line( $store_id, $order_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/orders/%s/lines', $store_id, $order_id ); - return $this->client->post( $resource, $args ); - } - - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#read-get_ecommerce_stores_store_id_orders_order_id_lines - * - * @param string $store_id - * @param string $order_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_order_lines( $store_id, $order_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/orders/%s/lines', $store_id, $order_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#read-get_ecommerce_stores_store_id_orders_order_id_lines_line_id - * - * @param string $store_id - * @param string $order_id - * @param string $line_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_order_line( $store_id, $order_id, $line_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/orders/%s/lines/%s', $store_id, $order_id, $line_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#edit-patch_ecommerce_stores_store_id_orders_order_id_lines_line_id - * - * @param string $store_id - * @param string $order_id - * @param string $line_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store_order_line( $store_id, $order_id, $line_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/orders/%s/lines/%s', $store_id, $order_id, $line_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#delete-delete_ecommerce_stores_store_id_orders_order_id_lines_line_id - * - * @param string $store_id - * @param string $order_id - * @param string $line_id - * - * @return bool - * @throws NL4WP_API_Exception - */ - public function delete_ecommerce_store_order_line( $store_id, $order_id, $line_id ) { - $resource = sprintf( '/ecommerce/stores/%s/orders/%s/lines/%s', $store_id, $order_id, $line_id ); - return !! $this->client->delete( $resource ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#read-get_ecommerce_stores_store_id_carts - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_carts( $store_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/carts', $store_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#read-get_ecommerce_stores_store_id_carts_cart_id - * - * @param string $store_id - * @param string $cart_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_cart( $store_id, $cart_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/carts/%s', $store_id, $cart_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#create-post_ecommerce_stores_store_id_carts - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store_cart( $store_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/carts', $store_id ); - return $this->client->post( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#edit-patch_ecommerce_stores_store_id_carts_cart_id - * - * @param string $store_id - * @param string $cart_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store_cart( $store_id, $cart_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/carts/%s', $store_id, $cart_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#delete-delete_ecommerce_stores_store_id_carts_cart_id - * - * @param string $store_id - * @param string $cart_id - * - * @return bool - */ - public function delete_ecommerce_store_cart( $store_id, $cart_id ) { - return !! $this->client->delete( sprintf( '/ecommerce/stores/%s/carts/%s', $store_id, $cart_id ) ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#read-get_ecommerce_stores_store_id_carts_cart_id_lines - * - * @param string $store_id - * @param string $cart_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_cart_lines( $store_id, $cart_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/carts/%/lines', $store_id, $cart_id); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#read-get_ecommerce_stores_store_id_carts_cart_id_lines_line_id - * - * @param string $store_id - * @param string $cart_id - * @param string $line_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_cart_line( $store_id, $cart_id, $line_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/carts/%s/lines/%s', $store_id, $cart_id, $line_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#create-post_ecommerce_stores_store_id_carts_cart_id_lines - * - * @param string $store_id - * @param string $cart_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store_cart_line( $store_id, $cart_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/carts/%s/lines', $store_id, $cart_id ); - return $this->client->post( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#edit-patch_ecommerce_stores_store_id_carts_cart_id_lines_line_id - * - * @param string $store_id - * @param string $cart_id - * @param string $line_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store_cart_line( $store_id, $cart_id, $line_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/carts/%s/lines/%s', $store_id, $cart_id, $line_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#delete-delete_ecommerce_stores_store_id_carts_cart_id_lines_line_id - * - * @param string $store_id - * @param string $cart_id - * @param string $line_id - * - * @return bool - * @throws NL4WP_API_Exception - */ - public function delete_ecommerce_store_cart_line( $store_id, $cart_id, $line_id ) { - $resource = sprintf( '/ecommerce/stores/%s/carts/%s/lines/%s', $store_id, $cart_id, $line_id ); - return !! $this->client->delete( $resource ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#create-post_ecommerce_stores_store_id_promo_rules - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store_promo_rule( $store_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules', $store_id ); - return $this->client->post( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#read-get_ecommerce_stores_store_id_promo_rules - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_promo_rules( $store_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules', $store_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#read-get_ecommerce_stores_store_id_promo_rules_promo_rule_id - * - * @param string $store_id - * @param string $promo_rule_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_promo_rule( $store_id, $promo_rule_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules/%s', $store_id, $promo_rule_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#edit-patch_ecommerce_stores_store_id_promo_rules_promo_rule_id - * - * @param string $store_id - * @param string $promo_rule_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store_promo_rule( $store_id, $promo_rule_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules/%s', $store_id, $promo_rule_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#delete-delete_ecommerce_stores_store_id_promo_rules_promo_rule_id - * - * @param string $store_id - * @param string $promo_rule_id - * - * @return boolean - * @throws NL4WP_API_Exception - */ - public function delete_ecommerce_store_promo_rule( $store_id, $promo_rule_id ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules/%s', $store_id, $promo_rule_id ); - return !! $this->client->delete( $resource ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#create-post_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function add_ecommerce_store_promo_rule_promo_code( $store_id, $promo_rule_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules/%s/promo-codes', $store_id, $promo_rule_id ); - return $this->client->post( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#read-get_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes - * - * @param string $store_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_promo_rule_promo_codes( $store_id, $promo_rule_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules/%s/promo-codes', $store_id, $promo_rule_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#read-get_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes_promo_code_id - * - * @param string $store_id - * @param string $promo_rule_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function get_ecommerce_store_promo_rule_promo_code( $store_id, $promo_rule_id, $promo_code_id, array $args = array() ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules/%s/promo-codes/%s', $store_id, $promo_rule_id, $promo_code_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#edit-patch_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes_promo_code_id - * - * @param string $store_id - * @param string $promo_rule_id - * @param array $args - * - * @return object - * @throws NL4WP_API_Exception - */ - public function update_ecommerce_store_promo_rule_promo_code( $store_id, $promo_rule_id, $promo_code_id, array $args ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules/%s/promo-codes/%s', $store_id, $promo_rule_id, $promo_code_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#delete-delete_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes_promo_code_id - * - * @param string $store_id - * @param string $promo_rule_id - * - * @return boolean - * @throws NL4WP_API_Exception - */ - public function delete_ecommerce_store_promo_rule_promo_code( $store_id, $promo_rule_id, $promo_code_id ) { - $resource = sprintf( '/ecommerce/stores/%s/promo-rules/%s/promo-codes/%s', $store_id, $promo_rule_id, $promo_code_id ); - return !! $this->client->delete( $resource ); - } - - - /** - * Get a list of an account's available templates - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/templates/#read-get_templates - * @param array $args - * @return object - * @throws NL4WP_API_Exception - */ - public function get_templates( array $args = array() ) { - $resource = '/templates'; - return $this->client->get( $resource, $args ); - } - - /** - * Get information about a specific template. - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/templates/#read-get_templates_template_id - * @param string $template_id - * @return object - * @throws NL4WP_API_Exception - */ - public function get_template( $template_id, array $args = array() ) { - $resource = sprintf( '/templates/%s', $template_id ); - return $this->client->get( $resource, $args ); - } - - /** - * @link https://developer.newsletter.com/documentation/newsletter/reference/templates/default-content/ - * @param string $template_id - * @return object - * @throws NL4WP_API_Exception - */ - public function get_template_default_content( $template_id, array $args = array() ) { - $resource = sprintf( '/templates/%s/default-content', $template_id ); - return $this->client->get( $resource, $args ); - } - - /** - * Create a new campaign - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#create-post_campaigns - * @param array $args - * @return object - * @throws NL4WP_API_Exception - */ - public function add_campaign( array $args ) { - $resource = '/campaigns'; - return $this->client->post( $resource, $args ); - } - - /** - * Get all campaigns in an account - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#read-get_campaigns - * @param array $args - * @return object - * @throws NL4WP_API_Exception - */ - public function get_campaigns( array $args = array() ) { - $resource = '/campaigns'; - return $this->client->get( $resource, $args ); - } - - /** - * Get information about a specific campaign. - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#read-get_campaigns_campaign_id - * @param string $campaign_id - * @param array $args - * @return object - * @throws NL4WP_API_Exception - */ - public function get_campaign( $campaign_id, array $args = array() ) { - $resource = sprintf( '/campaigns/%s', $campaign_id ); - return $this->client->get( $resource, $args ); - } - - /** - * Update some or all of the settings for a specific campaign. - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#edit-patch_campaigns_campaign_id - * @param string $campaign_id - * @param array $args - * @return object - * @throws NL4WP_API_Exception - */ - public function update_campaign( $campaign_id, array $args ) { - $resource = sprintf( '/campaigns/%s', $campaign_id ); - return $this->client->patch( $resource, $args ); - } - - /** - * Remove a campaign from the Newsletter account - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#delete-delete_campaigns_campaign_id - * @param string $campaign_id - * @return bool - * @throws NL4WP_API_Exception - */ - public function delete_campaign( $campaign_id ) { - $resource = sprintf( '/campaigns/%s', $campaign_id ); - return !! $this->client->delete( $resource ); - } - - /** - * Perform an action on a Newsletter campaign - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#action-post_campaigns - * - * @param string $campaign_id - * @param string $action - * @param array $args - * @return object - * @throws NL4WP_API_Exception - */ - public function campaign_action( $campaign_id, $action, array $args = array() ) { - $resource = sprintf( '/campaigns/%s/actions/%s', $campaign_id, $action ); - return $this->client->post( $resource, $args ); - } - - /** - * Get the HTML and plain-text content for a campaign - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/content/#read-get_campaigns_campaign_id_content - * @param string $campaign_id - * @param array $args - * @return object - * @throws NL4WP_API_Exception - */ - public function get_campaign_content( $campaign_id, array $args = array() ) { - $resource = sprintf( '/campaigns/%s/content', $campaign_id ); - return $this->client->get( $resource, $args ); - } - - /** - * Set the content for a campaign - * - * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/content/#edit-put_campaigns_campaign_id_content - * @param string $campaign_id - * @param array $args - * @return object - * @throws NL4WP_API_Exception - */ - public function update_campaign_content( $campaign_id, array $args ) { - $resource = sprintf( '/campaigns/%s/content', $campaign_id ); - return $this->client->put( $resource, $args ); - } - - /** - * @return string - */ - public function get_last_response_body() { - return $this->client->get_last_response_body(); - } - - /** - * @return array - */ - public function get_last_response_headers() { - return $this->client->get_last_response_headers(); - } - - +class NL4WP_API_v3 +{ + + /** + * @var NL4WP_API_v3_Client + */ + protected $client; + + + /** + * Constructor + * + * @param string $api_key + */ + public function __construct($api_key) + { + $this->client = new NL4WP_API_v3_Client($api_key); + } + + /** + * Gets the API client to perform raw API calls. + * + * @return NL4WP_API_v3_Client + */ + public function get_client() + { + return $this->client; + } + + /** + * Pings the Newsletter API to see if we're connected + * + * @return boolean + * @throws NL4WP_API_Exception + */ + public function is_connected() + { + $data = $this->client->get('/', array( 'fields' => 'account_id' )); + $connected = is_object($data) && isset($data->account_id); + return $connected; + } + + /** + * @param $email_address + * + * @return string + */ + public function get_subscriber_hash($email_address) + { + return base64_encode( strtolower( trim( $email_address ) ) ); /* NL_CHANGED */ + } + + /** + * Get recent daily, aggregated activity stats for a list. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/activity/#read-get_lists_list_id_activity + * + * @param string $list_id + * @param array $args + * + * @return array + * @throws NL4WP_API_Exception + */ + public function get_list_activity($list_id, array $args = array()) + { + $resource = sprintf('/lists/%s/activity', $list_id); + $data = $this->client->get($resource, $args); + + if (is_object($data) && isset($data->activity)) { + return $data->activity; + } + + return array(); + } + + /** + * Gets the interest categories for a given List + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/interest-categories/#read-get_lists_list_id_interest_categories + * + * @param string $list_id + * @param array $args + * + * @return array + * @throws NL4WP_API_Exception + */ + public function get_list_interest_categories($list_id, array $args = array()) + { + $resource = sprintf('/lists/%s/interest-categories', $list_id); + $data = $this->client->get($resource, $args); + + if (is_object($data) && isset($data->categories)) { + return $data->categories; + } + + return array(); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/interest-categories/interests/#read-get_lists_list_id_interest_categories_interest_category_id_interests + * + * @param string $list_id + * @param string $interest_category_id + * @param array $args + * + * @return array + * @throws NL4WP_API_Exception + */ + public function get_list_interest_category_interests($list_id, $interest_category_id, array $args = array()) + { + $resource = sprintf('/lists/%s/interest-categories/%s/interests', $list_id, $interest_category_id); + $data = $this->client->get($resource, $args); + + if (is_object($data) && isset($data->interests)) { + return $data->interests; + } + + return array(); + } + + /** + * Get merge vars for a given list + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/merge-fields/#read-get_lists_list_id_merge_fields + * + * @param string $list_id + * @param array $args + * + * @return array + * @throws NL4WP_API_Exception + */ + public function get_list_merge_fields($list_id, array $args = array()) + { + $resource = sprintf('/lists/%s/merge-fields', $list_id); + $data = $this->client->get($resource, $args); + + if (is_object($data) && isset($data->merge_fields)) { + return $data->merge_fields; + } + + return array(); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/#read-get_lists_list_id + * + * @param string $list_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_list($list_id, array $args = array()) + { + $resource = sprintf('/lists/%s', $list_id); + $data = $this->client->get($resource, $args); + return $data; + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/#read-get_lists + * + * @param array $args + * + * @return array + * @throws NL4WP_API_Exception + */ + public function get_lists($args = array()) + { + $resource = '/lists'; + $data = $this->client->get($resource, $args); + + if (is_object($data) && isset($data->lists)) { + return $data->lists; + } + + return array(); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/ + * + * @param string $list_id + * @param string $email_address + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_list_member($list_id, $email_address, array $args = array()) + { + $subscriber_hash = $this->get_subscriber_hash($email_address); + $resource = sprintf('/lists/%s/members/%s', $list_id, $subscriber_hash); + $data = $this->client->get($resource, $args); + return $data; + } + + /** + * Batch subscribe / unsubscribe list members. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/#create-post_lists_list_id + * + * @param string $list_id + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function add_list_members($list_id, array $args) + { + $resource = sprintf('/lists/%s', $list_id); + return $this->client->post($resource, $args); + } + + /** + * Add or update (!) a member to a Newsletter list. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/#create-post_lists_list_id_members + * + * @param string $list_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_list_member($list_id, array $args) + { + $subscriber_hash = $this->get_subscriber_hash($args['email_address']); + $resource = sprintf('/lists/%s/members/%s', $list_id, $subscriber_hash); + + // make sure we're sending an object as the Newsletter schema requires this + if (isset($args['merge_fields'])) { + $args['merge_fields'] = (object) $args['merge_fields']; + } + + if (isset($args['interests'])) { + $args['interests'] = (object) $args['interests']; + } + + // "put" updates the member if it's already on the list... take notice + $data = $this->client->put($resource, $args); + return $data; + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/#edit-patch_lists_list_id_members_subscriber_hash + * + * @param $list_id + * @param $email_address + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_list_member($list_id, $email_address, array $args) + { + $subscriber_hash = $this->get_subscriber_hash($email_address); + $resource = sprintf('/lists/%s/members/%s', $list_id, $subscriber_hash); + + // make sure we're sending an object as the Newsletter schema requires this + if (isset($args['merge_fields'])) { + $args['merge_fields'] = (object) $args['merge_fields']; + } + + if (isset($args['interests'])) { + $args['interests'] = (object) $args['interests']; + } + + $data = $this->client->patch($resource, $args); + return $data; + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/ + * + * @param string $list_id + * @param string $email_address + * + * @return bool + * @throws NL4WP_API_Exception + */ + public function delete_list_member($list_id, $email_address) + { + $subscriber_hash = $this->get_subscriber_hash($email_address); + $resource = sprintf('/lists/%s/members/%s', $list_id, $subscriber_hash); + $data = $this->client->delete($resource); + return !!$data; + } + + /** + * Get the tags on a list member. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/tags/#create-post_lists_list_id_members_subscriber_hash_tags + * @param string $list_id + * @param string $email_address + * @return object + * @throws NL4WP_API_Exception + */ + public function get_list_member_tags($list_id, $email_address) + { + $subscriber_hash = $this->get_subscriber_hash($email_address); + $resource = sprintf('/lists/%s/members/%s/tags', $list_id, $subscriber_hash); + return $this->client->get($resource); + } + + /** + * Add or remove tags from a list member. If a tag that does not exist is passed in and set as ‘active’, a new tag will be created. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/members/tags/#read-get_lists_list_id_members_subscriber_hash_tags + * @param string $list_id + * @param string $email_address + * @param array $data + * @return object + * @throws NL4WP_API_Exception + */ + public function update_list_member_tags($list_id, $email_address, array $data) + { + $subscriber_hash = $this->get_subscriber_hash($email_address); + $resource = sprintf('/lists/%s/members/%s/tags', $list_id, $subscriber_hash); + return $this->client->post($resource, $data); + } + + /** + * Get information about all available segments for a specific list. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/lists/segments/#read-get_lists_list_id_segments + * @param string $list_id + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function get_list_segments($list_id, array $args = array()) + { + $resource = sprintf('/lists/%s/segments', $list_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#read-get_ecommerce_stores + * + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_stores(array $args = array()) + { + $resource = '/ecommerce/stores'; + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#read-get_ecommerce_stores_store_id + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store($store_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s', $store_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#create-post_ecommerce_stores + * + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store(array $args) + { + $resource = '/ecommerce/stores'; + return $this->client->post($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#edit-patch_ecommerce_stores_store_id + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store($store_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s', $store_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/#delete-delete_ecommerce_stores_store_id + * + * @param string $store_id + * + * @return boolean + * @throws NL4WP_API_Exception + */ + public function delete_ecommerce_store($store_id) + { + $resource = sprintf('/ecommerce/stores/%s', $store_id); + return !!$this->client->delete($resource); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#read-get_ecommerce_stores_store_id_customers + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_customers($store_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/customers', $store_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#read-get_ecommerce_stores_store_id_customers_customer_id + * + * @param string $store_id + * @param string $customer_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_customer($store_id, $customer_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/customers/%s', $store_id, $customer_id); + return $this->client->get($resource, $args); + } + + /** + * Add OR update a store customer + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#edit-put_ecommerce_stores_store_id_customers_customer_id + * + * @param $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store_customer($store_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/customers/%s', $store_id, $args['id']); + return $this->client->put($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#edit-patch_ecommerce_stores_store_id_customers_customer_id + * + * @param string $store_id + * @param string $customer_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store_customer($store_id, $customer_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/customers/%s', $store_id, $customer_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/customers/#delete-delete_ecommerce_stores_store_id_customers_customer_id + * + * @param string $store_id + * @param string $customer_id + * + * @return bool + * @throws NL4WP_API_Exception + */ + public function delete_ecommerce_store_customer($store_id, $customer_id) + { + $resource = sprintf('/ecommerce/stores/%s/customers/%s', $store_id, $customer_id); + return !!$this->client->delete($resource); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#read-get_ecommerce_stores_store_id_products + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_products($store_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/products', $store_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#read-get_ecommerce_stores_store_id_products_product_id + * + * @param string $store_id + * @param string $product_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_product($store_id, $product_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/products/%s', $store_id, $product_id); + return $this->client->get($resource, $args); + } + + /** + * Add a product to a store + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#create-post_ecommerce_stores_store_id_products + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store_product($store_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/products', $store_id); + return $this->client->post($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#edit-patch_ecommerce_stores_store_id_products_product_id + * + * @param string $store_id + * @param string $product_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store_product($store_id, $product_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/products/%s', $store_id, $product_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/#delete-delete_ecommerce_stores_store_id_products_product_id + * + * @param string $store_id + * @param string $product_id + * + * @return boolean + * @throws NL4WP_API_Exception + */ + public function delete_ecommerce_store_product($store_id, $product_id) + { + $resource = sprintf('/ecommerce/stores/%s/products/%s', $store_id, $product_id); + return !!$this->client->delete($resource); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#read-get_ecommerce_stores_store_id_products_product_id_variants + * + * @param string $store_id + * @param string $product_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_product_variants($store_id, $product_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/products/%s/variants', $store_id, $product_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#read-get_ecommerce_stores_store_id_products_product_id_variants_variant_id + * + * @param string $store_id + * @param string $product_id + * @param string $variant_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_product_variant($store_id, $product_id, $variant_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/products/%s/variants/%s', $store_id, $product_id, $variant_id); + return $this->client->get($resource, $args); + } + + /** + * Add OR update a product variant. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#edit-put_ecommerce_stores_store_id_products_product_id_variants_variant_id + * + * @param string $store_id + * @param string $product_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store_product_variant($store_id, $product_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/products/%s/variants/%s', $store_id, $product_id, $args['id']); + return $this->client->put($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#edit-patch_ecommerce_stores_store_id_products_product_id_variants_variant_id + * + * @param string $store_id + * @param string $product_id + * @param string $variant_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store_product_variant($store_id, $product_id, $variant_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/products/%s/variants/%s', $store_id, $product_id, $variant_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/products/variants/#delete-delete_ecommerce_stores_store_id_products_product_id_variants_variant_id + * + * @param string $store_id + * @param string $product_id + * @param string $variant_id + * + * @return boolean + * @throws NL4WP_API_Exception + */ + public function delete_ecommerce_store_product_variant($store_id, $product_id, $variant_id) + { + $resource = sprintf('/ecommerce/stores/%s/products/%s/variants/%s', $store_id, $product_id, $variant_id); + return !!$this->client->delete($resource); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#read-get_ecommerce_stores_store_id_orders + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_orders($store_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/orders', $store_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#read-get_ecommerce_stores_store_id_orders_order_id + * + * @param string $store_id + * @param string $order_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_order($store_id, $order_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/orders/%s', $store_id, $order_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#create-post_ecommerce_stores_store_id_orders + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store_order($store_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/orders', $store_id); + return $this->client->post($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#edit-patch_ecommerce_stores_store_id_orders_order_id + * + * @param string $store_id + * @param string $order_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store_order($store_id, $order_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/orders/%s', $store_id, $order_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/#delete-delete_ecommerce_stores_store_id_orders_order_id + * + * @param string $store_id + * @param string $order_id + * + * @return bool + * @throws NL4WP_API_Exception + */ + public function delete_ecommerce_store_order($store_id, $order_id) + { + return !! $this->client->delete(sprintf('/ecommerce/stores/%s/orders/%s', $store_id, $order_id)); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#create-post_ecommerce_stores_store_id_orders_order_id_lines + * + * @param string $store_id + * @param string $order_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store_order_line($store_id, $order_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/orders/%s/lines', $store_id, $order_id); + return $this->client->post($resource, $args); + } + + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#read-get_ecommerce_stores_store_id_orders_order_id_lines + * + * @param string $store_id + * @param string $order_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_order_lines($store_id, $order_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/orders/%s/lines', $store_id, $order_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#read-get_ecommerce_stores_store_id_orders_order_id_lines_line_id + * + * @param string $store_id + * @param string $order_id + * @param string $line_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_order_line($store_id, $order_id, $line_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/orders/%s/lines/%s', $store_id, $order_id, $line_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#edit-patch_ecommerce_stores_store_id_orders_order_id_lines_line_id + * + * @param string $store_id + * @param string $order_id + * @param string $line_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store_order_line($store_id, $order_id, $line_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/orders/%s/lines/%s', $store_id, $order_id, $line_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/orders/lines/#delete-delete_ecommerce_stores_store_id_orders_order_id_lines_line_id + * + * @param string $store_id + * @param string $order_id + * @param string $line_id + * + * @return bool + * @throws NL4WP_API_Exception + */ + public function delete_ecommerce_store_order_line($store_id, $order_id, $line_id) + { + $resource = sprintf('/ecommerce/stores/%s/orders/%s/lines/%s', $store_id, $order_id, $line_id); + return !! $this->client->delete($resource); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#read-get_ecommerce_stores_store_id_carts + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_carts($store_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/carts', $store_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#read-get_ecommerce_stores_store_id_carts_cart_id + * + * @param string $store_id + * @param string $cart_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_cart($store_id, $cart_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/carts/%s', $store_id, $cart_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#create-post_ecommerce_stores_store_id_carts + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store_cart($store_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/carts', $store_id); + return $this->client->post($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#edit-patch_ecommerce_stores_store_id_carts_cart_id + * + * @param string $store_id + * @param string $cart_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store_cart($store_id, $cart_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/carts/%s', $store_id, $cart_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/#delete-delete_ecommerce_stores_store_id_carts_cart_id + * + * @param string $store_id + * @param string $cart_id + * + * @return bool + */ + public function delete_ecommerce_store_cart($store_id, $cart_id) + { + return !! $this->client->delete(sprintf('/ecommerce/stores/%s/carts/%s', $store_id, $cart_id)); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#read-get_ecommerce_stores_store_id_carts_cart_id_lines + * + * @param string $store_id + * @param string $cart_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_cart_lines($store_id, $cart_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/carts/%/lines', $store_id, $cart_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#read-get_ecommerce_stores_store_id_carts_cart_id_lines_line_id + * + * @param string $store_id + * @param string $cart_id + * @param string $line_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_cart_line($store_id, $cart_id, $line_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/carts/%s/lines/%s', $store_id, $cart_id, $line_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#create-post_ecommerce_stores_store_id_carts_cart_id_lines + * + * @param string $store_id + * @param string $cart_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store_cart_line($store_id, $cart_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/carts/%s/lines', $store_id, $cart_id); + return $this->client->post($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#edit-patch_ecommerce_stores_store_id_carts_cart_id_lines_line_id + * + * @param string $store_id + * @param string $cart_id + * @param string $line_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store_cart_line($store_id, $cart_id, $line_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/carts/%s/lines/%s', $store_id, $cart_id, $line_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/carts/lines/#delete-delete_ecommerce_stores_store_id_carts_cart_id_lines_line_id + * + * @param string $store_id + * @param string $cart_id + * @param string $line_id + * + * @return bool + * @throws NL4WP_API_Exception + */ + public function delete_ecommerce_store_cart_line($store_id, $cart_id, $line_id) + { + $resource = sprintf('/ecommerce/stores/%s/carts/%s/lines/%s', $store_id, $cart_id, $line_id); + return !! $this->client->delete($resource); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#create-post_ecommerce_stores_store_id_promo_rules + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store_promo_rule($store_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules', $store_id); + return $this->client->post($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#read-get_ecommerce_stores_store_id_promo_rules + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_promo_rules($store_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules', $store_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#read-get_ecommerce_stores_store_id_promo_rules_promo_rule_id + * + * @param string $store_id + * @param string $promo_rule_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_promo_rule($store_id, $promo_rule_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules/%s', $store_id, $promo_rule_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#edit-patch_ecommerce_stores_store_id_promo_rules_promo_rule_id + * + * @param string $store_id + * @param string $promo_rule_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store_promo_rule($store_id, $promo_rule_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules/%s', $store_id, $promo_rule_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/#delete-delete_ecommerce_stores_store_id_promo_rules_promo_rule_id + * + * @param string $store_id + * @param string $promo_rule_id + * + * @return boolean + * @throws NL4WP_API_Exception + */ + public function delete_ecommerce_store_promo_rule($store_id, $promo_rule_id) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules/%s', $store_id, $promo_rule_id); + return !! $this->client->delete($resource); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#create-post_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function add_ecommerce_store_promo_rule_promo_code($store_id, $promo_rule_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules/%s/promo-codes', $store_id, $promo_rule_id); + return $this->client->post($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#read-get_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes + * + * @param string $store_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_promo_rule_promo_codes($store_id, $promo_rule_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules/%s/promo-codes', $store_id, $promo_rule_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#read-get_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes_promo_code_id + * + * @param string $store_id + * @param string $promo_rule_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function get_ecommerce_store_promo_rule_promo_code($store_id, $promo_rule_id, $promo_code_id, array $args = array()) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules/%s/promo-codes/%s', $store_id, $promo_rule_id, $promo_code_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#edit-patch_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes_promo_code_id + * + * @param string $store_id + * @param string $promo_rule_id + * @param array $args + * + * @return object + * @throws NL4WP_API_Exception + */ + public function update_ecommerce_store_promo_rule_promo_code($store_id, $promo_rule_id, $promo_code_id, array $args) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules/%s/promo-codes/%s', $store_id, $promo_rule_id, $promo_code_id); + return $this->client->patch($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/ecommerce/stores/promo-rules/promo-codes/#delete-delete_ecommerce_stores_store_id_promo_rules_promo_rule_id_promo_codes_promo_code_id + * + * @param string $store_id + * @param string $promo_rule_id + * + * @return boolean + * @throws NL4WP_API_Exception + */ + public function delete_ecommerce_store_promo_rule_promo_code($store_id, $promo_rule_id, $promo_code_id) + { + $resource = sprintf('/ecommerce/stores/%s/promo-rules/%s/promo-codes/%s', $store_id, $promo_rule_id, $promo_code_id); + return !! $this->client->delete($resource); + } + + + /** + * Get a list of an account's available templates + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/templates/#read-get_templates + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function get_templates(array $args = array()) + { + $resource = '/templates'; + return $this->client->get($resource, $args); + } + + /** + * Get information about a specific template. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/templates/#read-get_templates_template_id + * @param string $template_id + * @return object + * @throws NL4WP_API_Exception + */ + public function get_template($template_id, array $args = array()) + { + $resource = sprintf('/templates/%s', $template_id); + return $this->client->get($resource, $args); + } + + /** + * @link https://developer.newsletter.com/documentation/newsletter/reference/templates/default-content/ + * @param string $template_id + * @return object + * @throws NL4WP_API_Exception + */ + public function get_template_default_content($template_id, array $args = array()) + { + $resource = sprintf('/templates/%s/default-content', $template_id); + return $this->client->get($resource, $args); + } + + /** + * Create a new campaign + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#create-post_campaigns + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function add_campaign(array $args) + { + $resource = '/campaigns'; + return $this->client->post($resource, $args); + } + + /** + * Get all campaigns in an account + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#read-get_campaigns + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function get_campaigns(array $args = array()) + { + $resource = '/campaigns'; + return $this->client->get($resource, $args); + } + + /** + * Get information about a specific campaign. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#read-get_campaigns_campaign_id + * @param string $campaign_id + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function get_campaign($campaign_id, array $args = array()) + { + $resource = sprintf('/campaigns/%s', $campaign_id); + return $this->client->get($resource, $args); + } + + /** + * Update some or all of the settings for a specific campaign. + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#edit-patch_campaigns_campaign_id + * @param string $campaign_id + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function update_campaign($campaign_id, array $args) + { + $resource = sprintf('/campaigns/%s', $campaign_id); + return $this->client->patch($resource, $args); + } + + /** + * Remove a campaign from the Newsletter account + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#delete-delete_campaigns_campaign_id + * @param string $campaign_id + * @return bool + * @throws NL4WP_API_Exception + */ + public function delete_campaign($campaign_id) + { + $resource = sprintf('/campaigns/%s', $campaign_id); + return !! $this->client->delete($resource); + } + + /** + * Perform an action on a Newsletter campaign + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/#action-post_campaigns + * + * @param string $campaign_id + * @param string $action + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function campaign_action($campaign_id, $action, array $args = array()) + { + $resource = sprintf('/campaigns/%s/actions/%s', $campaign_id, $action); + return $this->client->post($resource, $args); + } + + /** + * Get the HTML and plain-text content for a campaign + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/content/#read-get_campaigns_campaign_id_content + * @param string $campaign_id + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function get_campaign_content($campaign_id, array $args = array()) + { + $resource = sprintf('/campaigns/%s/content', $campaign_id); + return $this->client->get($resource, $args); + } + + /** + * Set the content for a campaign + * + * @link https://developer.newsletter.com/documentation/newsletter/reference/campaigns/content/#edit-put_campaigns_campaign_id_content + * @param string $campaign_id + * @param array $args + * @return object + * @throws NL4WP_API_Exception + */ + public function update_campaign_content($campaign_id, array $args) + { + $resource = sprintf('/campaigns/%s/content', $campaign_id); + return $this->client->put($resource, $args); + } + + /** + * @return string + */ + public function get_last_response_body() + { + return $this->client->get_last_response_body(); + } + + /** + * @return array + */ + public function get_last_response_headers() + { + return $this->client->get_last_response_headers(); + } } diff --git a/includes/api/class-api.php b/includes/api/class-api.php index 48ae074..7cbc929 100755 --- a/includes/api/class-api.php +++ b/includes/api/class-api.php @@ -8,577 +8,594 @@ * @since 1.0 * @deprecated 4.0 */ -class NL4WP_API { - - /** - * @var string The URL to the Newsletter API - */ - protected $api_url = 'https://api.newsletter.com/2.0/'; - - /** - * @var string The API key to use - */ - protected $api_key = ''; - - /** - * @var string The error message of the latest API request (if any) - */ - protected $error_message = ''; - - /** - * @var int The error code of the last API request (if any) - */ - protected $error_code = 0; - - /** - * @var boolean Boolean indicating whether the user is connected with Newsletter - */ - protected $connected; - - /** - * @var object The full response object of the latest API call - */ - protected $last_response; - - /** - * Constructor - * - * @param string $api_key - */ - public function __construct( $api_key ) { - $this->api_key = $api_key; - - $dash_position = strpos( $api_key, '-' ); - if( $dash_position !== false ) { - $this->api_url = 'https://' . substr( $api_key, $dash_position + 1 ) . '.api.newsletter.com/2.0/'; - } - } - - /** - * Show an error message to administrators - * - * @param string $message - * - * @return bool - */ - private function show_error( $message ) { - - if( ! is_admin() || ! current_user_can( 'manage_options' ) ) { - return false; - } - - if( ! function_exists( 'add_settings_error' ) ) { - return false; - } - - add_settings_error( 'nl4wp-api', 'nl4wp-api-error', $message, 'error' ); - return true; - } - - /** - * @param $message - * - * @return bool - */ - private function show_connection_error( $message ) { - $message .= '

' . sprintf( '' . __( 'Read more about common connectivity issues.', 'newsletter-for-wp' ) . '', 'https://kb.mc4wp.com/solving-connectivity-issues/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=settings-notice' ); - return $this->show_error( $message ); - } - - /** - * Pings the Newsletter API to see if we're connected - * - * The result is cached to ensure a maximum of 1 API call per page load - * - * @return boolean - */ - public function is_connected() { - - if( is_bool( $this->connected ) ) { - return $this->connected; - } - - $result = $this->call( 'helper/ping' ); - $this->connected = false; - - if( is_object( $result ) ) { - - // Msg key set? All good then! - if( ! empty( $result->msg ) ) { - $this->connected = true; - return true; - } - - // Uh oh. We got an error back. - if( isset( $result->error ) ) { - $this->show_error( 'Newsletter Error: ' . $result->error ); - } - } - - return $this->connected; - } - - /** - * Sends a subscription request to the Newsletter API - * - * @param string $list_id The list id to subscribe to - * @param string $email The email address to subscribe - * @param array $merge_vars Array of extra merge variables - * @param string $email_type The email type to send to this email address. Possible values are `html` and `text`. - * @param boolean $double_optin Should this email be confirmed via double opt-in? - * @param boolean $update_existing Update information if this email is already on list? - * @param boolean $replace_interests Replace interest groupings, only if update_existing is true. - * @param boolean $send_welcome Send a welcome e-mail, only if double_optin is false. - * - * @return boolean|string True if success, 'error' if error - */ - public function subscribe($list_id, $email, array $merge_vars = array(), $email_type = 'html', $double_optin = true, $update_existing = false, $replace_interests = true, $send_welcome = false ) { - $data = array( - 'id' => $list_id, - 'email' => array( 'email' => $email ), - 'merge_vars' => $merge_vars, - 'email_type' => $email_type, - 'double_optin' => $double_optin, - 'update_existing' => $update_existing, - 'replace_interests' => $replace_interests, - 'send_welcome' => $send_welcome - ); - - $response = $this->call( 'lists/subscribe', $data ); - - if( is_object( $response ) && isset( $response->email ) ) { - return true; - } - - return false; - } - - /** - * Gets the Groupings for a given List - * @param int $list_id - * @return array|boolean - */ - public function get_list_groupings( $list_id ) { - $result = $this->call( 'lists/interest-groupings', array( 'id' => $list_id ) ); - if( is_array( $result ) ) { - return $result; - } - - return false; - } - - /** - * @param array $list_ids Array of ID's of the lists to fetch. (optional) - * - * @return bool - */ - public function get_lists( $list_ids = array() ) { - $args = array( - 'limit' => 100, - 'sort_field' => 'web', - 'sort_dir' => 'ASC', - ); - - // set filter if the $list_ids parameter was set - if( count( $list_ids ) > 0 ) { - $args['filters'] = array( - 'list_id' => implode( ',', $list_ids ) - ); - } - - $result = $this->call( 'lists/list', $args ); - - if( is_object( $result ) && isset( $result->data ) ) { - return $result->data; - } - - return false; - } - - /** - * Get the lists an email address is subscribed to - * - * @param array|string $email - * - * @return array - */ - public function get_lists_for_email( $email ) { - - if( is_string( $email ) ) { - $email = array( - 'email' => $email, - ); - } - - $result = $this->call( 'helper/lists-for-email', array( 'email' => $email ) ); - - if( ! is_array( $result ) ) { - return false; - } - - return $result; - } - - /** - * Get lists with their merge_vars for a given array of list id's - * @param array $list_ids - * @return array|boolean - */ - public function get_lists_with_merge_vars( $list_ids ) { - $result = $this->call( 'lists/merge-vars', array('id' => $list_ids ) ); - - if( is_object( $result ) && isset( $result->data ) ) { - return $result->data; - } - - return false; - } - - /** - * Gets the member info for one or multiple emails on a list - * - * @param string $list_id - * @param array $emails - * @return array - */ - public function get_subscriber_info( $list_id, $emails ) { - - if( is_string( $emails ) ) { - $emails = array( $emails ); - } - - $result = $this->call( 'lists/member-info', array( - 'id' => $list_id, - 'emails' => $emails - ) - ); - - if( is_object( $result ) && isset( $result->data ) ) { - return $result->data; - } - - return false; - } - - /** - * Checks if an email address is on a given list - * - * @param string $list_id - * @param string $email - * @return boolean - */ - public function list_has_subscriber( $list_id, $email ) { - $member_info = $this->get_subscriber_info( $list_id, array( array( 'email' => $email ) ) ); - - if( is_array( $member_info ) && isset( $member_info[0] ) ) { - return ( $member_info[0]->status === 'subscribed' ); - } - - return false; - } - - /** - * @param string $list_id - * @param array|string $email - * @param array $merge_vars - * @param string $email_type - * @param bool $replace_interests - * - * @return bool - */ - public function update_subscriber( $list_id, $email, $merge_vars = array(), $email_type = 'html', $replace_interests = false ) { - - // default to using email for updating - if( is_string( $email ) ) { - $email = array( - 'email' => $email - ); - } - - $result = $this->call( 'lists/update-member', array( - 'id' => $list_id, - 'email' => $email, - 'merge_vars' => $merge_vars, - 'email_type' => $email_type, - 'replace_interests' => $replace_interests - ) - ); - - if( is_object( $result ) ) { - - if( isset( $result->error ) ) { - return false; - } else { - return true; - } - - } - - return false; - } - - /** - * Unsubscribes the given email or luid from the given Newsletter list - * - * @param string $list_id - * @param array|string $struct - * @param bool $delete_member - * @param bool $send_goodbye - * @param bool $send_notification - * - * @return bool - */ - public function unsubscribe( $list_id, $struct, $send_goodbye = true, $send_notification = false, $delete_member = false ) { - - if( ! is_array( $struct ) ) { - // assume $struct is an email - $struct = array( - 'email' => $struct - ); - } - - $response = $this->call( 'lists/unsubscribe', array( - 'id' => $list_id, - 'email' => $struct, - 'delete_member' => $delete_member, - 'send_goodbye' => $send_goodbye, - 'send_notify' => $send_notification - ) - ); - - if( is_object( $response ) ) { - - if ( isset( $response->complete ) && $response->complete ) { - return true; - } - } - - return false; - } - - /** - * @see https://apidocs.newsletter.com/api/2.0/ecomm/order-add.php - * - * @param array $order_data - * - * @return boolean - */ - public function add_ecommerce_order( array $order_data ) { - - $response = $this->call( 'ecomm/order-add', array( 'order' => $order_data ) ); - - if( is_object( $response ) ) { - - // complete means success - if ( isset( $response->complete ) && $response->complete ) { - return true; - } - - // if order was already added: great - if( isset( $response->code, $response->error ) && $response->code == 330 && strpos( $response->error, 'already been recorded' ) !== false ) { - return true; - } - } - - return false; - } - - /** - * @see https://apidocs.newsletter.com/api/2.0/ecomm/order-del.php - * - * @param string $store_id - * @param string $order_id - * - * @return bool - */ - public function delete_ecommerce_order( $store_id, $order_id ) { - - $data = array( - 'store_id' => $store_id, - 'order_id' => $order_id - ); - - $response = $this->call( 'ecomm/order-del', $data ); - - if( is_object( $response ) ) { - if ( isset( $response->complete ) && $response->complete ) { - return true; - } - - // Invalid order (order not existing). Good! - if( isset( $response->code ) && $response->code == 330 ) { - return true; - } - } - - return false; - } - - - - /** - * Calls the Newsletter API - * - * @uses WP_HTTP - * - * @param string $method - * @param array $data - * - * @return object - */ - public function call( $method, array $data = array() ) { - - $this->empty_last_response(); - - // do not make request when no api key was provided. - if( empty( $this->api_key ) ) { - $this->error_message = "Missing Newsletter API key."; - $this->error_code = 001; - return false; - } - - // do not make request if helper/ping failed already - if( $this->connected === false ) { - return false; - } - - $data['apikey'] = $this->api_key; - - $url = $this->api_url . $method . '.json'; - $request_args = array( - 'body' => $data, - 'timeout' => 10, - 'headers' => $this->get_headers(), - 'sslverify' => apply_filters( 'nl4wp_use_sslverify', true ), - ); - - $response = wp_remote_post( $url, $request_args ); - - try { - $response = $this->parse_response( $response ); - } catch( Exception $e ) { - $this->error_code = $e->getCode(); - $this->error_message = $e->getMessage(); - $this->show_connection_error( $e->getMessage() ); - return false; - } - - // store response - $this->last_response = $response; - - // store error (if any) - if( is_object( $response ) ) { - if( ! empty( $response->error ) ) { - $this->error_message = $response->error; - } - - // store error code (if any) - if( ! empty( $response->code ) ) { - $this->error_code = (int) $response->code; - } - } - - return $response; - } - - /** - * Checks if an error occured in the most recent request - * @return boolean - */ - public function has_error() { - return ( ! empty( $this->error_message ) ); - } - - /** - * Gets the most recent error message - * @return string - */ - public function get_error_message() { - return $this->error_message; - } - - /** - * Gets the most recent error code - * - * @return int - */ - public function get_error_code() { - return $this->error_code; - } - - /** - * Get the most recent response object - * - * @return object - */ - public function get_last_response() { - return $this->last_response; - } - - /** - * Empties all data from previous response - */ - private function empty_last_response() { - $this->last_response = null; - $this->error_code = 0; - $this->error_message = ''; - } - - /** - * Get the request headers to send to the Newsletter API - * - * @return array - */ - private function get_headers() { +class NL4WP_API +{ + + /** + * @var string The URL to the Newsletter API + */ + protected $api_url = 'https://api.newsletter.com/2.0/'; + + /** + * @var string The API key to use + */ + protected $api_key = ''; + + /** + * @var string The error message of the latest API request (if any) + */ + protected $error_message = ''; + + /** + * @var int The error code of the last API request (if any) + */ + protected $error_code = 0; + + /** + * @var boolean Boolean indicating whether the user is connected with Newsletter + */ + protected $connected; + + /** + * @var object The full response object of the latest API call + */ + protected $last_response; + + /** + * Constructor + * + * @param string $api_key + */ + public function __construct($api_key) + { + $this->api_key = $api_key; + + $dash_position = strpos($api_key, '-'); + if ($dash_position !== false) { + $this->api_url = 'https://' . substr($api_key, $dash_position + 1) . '.api.newsletter.com/2.0/'; + } + } + + /** + * Show an error message to administrators + * + * @param string $message + * + * @return bool + */ + private function show_error($message) + { + if (! is_admin() || ! current_user_can('manage_options')) { + return false; + } + + if (! function_exists('add_settings_error')) { + return false; + } + + add_settings_error('nl4wp-api', 'nl4wp-api-error', $message, 'error'); + return true; + } + + /** + * @param $message + * + * @return bool + */ + private function show_connection_error($message) + { + $message .= '

' . sprintf('' . __('Read more about common connectivity issues.', 'newsletter-for-wp') . '', 'https://kb.mc4wp.com/solving-connectivity-issues/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=settings-notice'); + return $this->show_error($message); + } + + /** + * Pings the Newsletter API to see if we're connected + * + * The result is cached to ensure a maximum of 1 API call per page load + * + * @return boolean + */ + public function is_connected() + { + if (is_bool($this->connected)) { + return $this->connected; + } + + $result = $this->call('helper/ping'); + $this->connected = false; + + if (is_object($result)) { + + // Msg key set? All good then! + if (! empty($result->msg)) { + $this->connected = true; + return true; + } + + // Uh oh. We got an error back. + if (isset($result->error)) { + $this->show_error('Newsletter Error: ' . $result->error); + } + } + + return $this->connected; + } + + /** + * Sends a subscription request to the Newsletter API + * + * @param string $list_id The list id to subscribe to + * @param string $email The email address to subscribe + * @param array $merge_vars Array of extra merge variables + * @param string $email_type The email type to send to this email address. Possible values are `html` and `text`. + * @param boolean $double_optin Should this email be confirmed via double opt-in? + * @param boolean $update_existing Update information if this email is already on list? + * @param boolean $replace_interests Replace interest groupings, only if update_existing is true. + * @param boolean $send_welcome Send a welcome e-mail, only if double_optin is false. + * + * @return boolean|string True if success, 'error' if error + */ + public function subscribe($list_id, $email, array $merge_vars = array(), $email_type = 'html', $double_optin = true, $update_existing = false, $replace_interests = true, $send_welcome = false) + { + $data = array( + 'id' => $list_id, + 'email' => array( 'email' => $email ), + 'merge_vars' => $merge_vars, + 'email_type' => $email_type, + 'double_optin' => $double_optin, + 'update_existing' => $update_existing, + 'replace_interests' => $replace_interests, + 'send_welcome' => $send_welcome + ); + + $response = $this->call('lists/subscribe', $data); + + if (is_object($response) && isset($response->email)) { + return true; + } + + return false; + } + + /** + * Gets the Groupings for a given List + * @param int $list_id + * @return array|boolean + */ + public function get_list_groupings($list_id) + { + $result = $this->call('lists/interest-groupings', array( 'id' => $list_id )); + if (is_array($result)) { + return $result; + } + + return false; + } + + /** + * @param array $list_ids Array of ID's of the lists to fetch. (optional) + * + * @return bool + */ + public function get_lists($list_ids = array()) + { + $args = array( + 'limit' => 100, + 'sort_field' => 'web', + 'sort_dir' => 'ASC', + ); + + // set filter if the $list_ids parameter was set + if (count($list_ids) > 0) { + $args['filters'] = array( + 'list_id' => implode(',', $list_ids) + ); + } + + $result = $this->call('lists/list', $args); + + if (is_object($result) && isset($result->data)) { + return $result->data; + } + + return false; + } + + /** + * Get the lists an email address is subscribed to + * + * @param array|string $email + * + * @return array + */ + public function get_lists_for_email($email) + { + if (is_string($email)) { + $email = array( + 'email' => $email, + ); + } + + $result = $this->call('helper/lists-for-email', array( 'email' => $email )); + if (! is_array($result)) { + return array(); + } + + return $result; + } + + /** + * Get lists with their merge_vars for a given array of list id's + * @param array $list_ids + * @return array|bool + */ + public function get_lists_with_merge_vars($list_ids) + { + $result = $this->call('lists/merge-vars', array('id' => $list_ids )); + + if (is_object($result) && isset($result->data)) { + return $result->data; + } + + return false; + } + + /** + * Gets the member info for one or multiple emails on a list + * + * @param string $list_id + * @param array $emails + * @return array|bool + */ + public function get_subscriber_info($list_id, $emails) + { + if (is_string($emails)) { + $emails = array( $emails ); + } + + $result = $this->call( + 'lists/member-info', + array( + 'id' => $list_id, + 'emails' => $emails + ) + ); + + if (is_object($result) && isset($result->data)) { + return $result->data; + } + + return false; + } + + /** + * Checks if an email address is on a given list + * + * @param string $list_id + * @param string $email + * @return bool + */ + public function list_has_subscriber($list_id, $email) + { + $member_info = $this->get_subscriber_info($list_id, array( array( 'email' => $email ) )); + + if (is_array($member_info) && isset($member_info[0])) { + return ($member_info[0]->status === 'subscribed'); + } + + return false; + } + + /** + * @param string $list_id + * @param array|string $email + * @param array $merge_vars + * @param string $email_type + * @param bool $replace_interests + * + * @return bool + */ + public function update_subscriber($list_id, $email, $merge_vars = array(), $email_type = 'html', $replace_interests = false) + { + + // default to using email for updating + if (is_string($email)) { + $email = array( + 'email' => $email + ); + } + + $result = $this->call( + 'lists/update-member', + array( + 'id' => $list_id, + 'email' => $email, + 'merge_vars' => $merge_vars, + 'email_type' => $email_type, + 'replace_interests' => $replace_interests + ) + ); + + if (is_object($result)) { + if (isset($result->error)) { + return false; + } else { + return true; + } + } + + return false; + } + + /** + * Unsubscribes the given email or luid from the given Newsletter list + * + * @param string $list_id + * @param array|string $struct + * @param bool $delete_member + * @param bool $send_goodbye + * @param bool $send_notification + * + * @return bool + */ + public function unsubscribe($list_id, $struct, $send_goodbye = true, $send_notification = false, $delete_member = false) + { + if (! is_array($struct)) { + // assume $struct is an email + $struct = array( + 'email' => $struct + ); + } + + $response = $this->call( + 'lists/unsubscribe', + array( + 'id' => $list_id, + 'email' => $struct, + 'delete_member' => $delete_member, + 'send_goodbye' => $send_goodbye, + 'send_notify' => $send_notification + ) + ); + + if (is_object($response)) { + if (isset($response->complete) && $response->complete) { + return true; + } + } + + return false; + } + + /** + * @see https://apidocs.newsletter.com/api/2.0/ecomm/order-add.php + * + * @param array $order_data + * + * @return boolean + */ + public function add_ecommerce_order(array $order_data) + { + $response = $this->call('ecomm/order-add', array( 'order' => $order_data )); + + if (is_object($response)) { + + // complete means success + if (isset($response->complete) && $response->complete) { + return true; + } + + // if order was already added: great + if (isset($response->code, $response->error) && $response->code == 330 && strpos($response->error, 'already been recorded') !== false) { + return true; + } + } + + return false; + } + + /** + * @see https://apidocs.newsletter.com/api/2.0/ecomm/order-del.php + * + * @param string $store_id + * @param string $order_id + * + * @return bool + */ + public function delete_ecommerce_order($store_id, $order_id) + { + $data = array( + 'store_id' => $store_id, + 'order_id' => $order_id + ); + + $response = $this->call('ecomm/order-del', $data); + + if (is_object($response)) { + if (isset($response->complete) && $response->complete) { + return true; + } + + // Invalid order (order not existing). Good! + if (isset($response->code) && $response->code == 330) { + return true; + } + } + + return false; + } + + + + /** + * Calls the Newsletter API + * + * @uses WP_HTTP + * + * @param string $method + * @param array $data + * + * @return object|bool + */ + public function call($method, array $data = array()) + { + $this->empty_last_response(); + + // do not make request when no api key was provided. + if (empty($this->api_key)) { + $this->error_message = "Missing Newsletter API key."; + $this->error_code = 001; + return false; + } + + // do not make request if helper/ping failed already + if ($this->connected === false) { + return false; + } + + $data['apikey'] = $this->api_key; + + $url = $this->api_url . $method . '.json'; + $request_args = array( + 'body' => $data, + 'timeout' => 10, + 'headers' => $this->get_headers(), + 'sslverify' => apply_filters('nl4wp_use_sslverify', true), + ); + + $response = wp_remote_post($url, $request_args); + + try { + $response = $this->parse_response($response); + } catch (Exception $e) { + $this->error_code = $e->getCode(); + $this->error_message = $e->getMessage(); + $this->show_connection_error($e->getMessage()); + return false; + } + + // store response + $this->last_response = $response; + + // store error (if any) + if (is_object($response)) { + if (! empty($response->error)) { + $this->error_message = $response->error; + } + + // store error code (if any) + if (! empty($response->code)) { + $this->error_code = (int) $response->code; + } + } + + return $response; + } + + /** + * Checks if an error occured in the most recent request + * @return boolean + */ + public function has_error() + { + return (! empty($this->error_message)); + } + + /** + * Gets the most recent error message + * @return string + */ + public function get_error_message() + { + return $this->error_message; + } + + /** + * Gets the most recent error code + * + * @return int + */ + public function get_error_code() + { + return $this->error_code; + } + + /** + * Get the most recent response object + * + * @return object + */ + public function get_last_response() + { + return $this->last_response; + } + + /** + * Empties all data from previous response + */ + private function empty_last_response() + { + $this->last_response = null; + $this->error_code = 0; + $this->error_message = ''; + } + + /** + * Get the request headers to send to the Newsletter API + * + * @return array + */ + private function get_headers() + { global $wp_version; - $headers = array( - 'Accept' => 'application/json', - 'User-Agent' => 'nl4wp/' . NL4WP_VERSION . '; WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) + $headers = array( + 'Accept' => 'application/json', + 'User-Agent' => 'nl4wp/' . NL4WP_VERSION . '; WordPress/' . $wp_version . '; ' . get_bloginfo('url') ); - // Copy Accept-Language from browser headers - if( ! empty( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) { - $headers['Accept-Language'] = $_SERVER['HTTP_ACCEPT_LANGUAGE']; - } - - return $headers; - } - - /** - * @param array|WP_Error $response - * @return object - * @throws Exception - */ - private function parse_response( $response ) { - - if( is_wp_error( $response ) ) { - throw new Exception( 'Error connecting to Newsletter. ' . $response->get_error_message(), (int) $response->get_error_code() ); - } - - // decode response body - $body = wp_remote_retrieve_body( $response ); - $data = json_decode( $body ); - if( ! is_null( $data ) ) { - return $data; - } - - $code = (int) wp_remote_retrieve_response_code( $response ); - $message = wp_remote_retrieve_response_message( $response ); - - if( $code !== 200 ) { - $message = sprintf( 'The Newsletter API server returned the following response: %s %s.', $code, $message ); - - // check for Akamai firewall response - if( $code === 403 ) { - preg_match('/Reference (.*)/i', $body, $matches ); - - if( ! empty( $matches[1] ) ) { - $message .= '

' . sprintf( 'This usually means that your server is blacklisted by Newsletter\'s firewall. Please contact Newsletter support with the following reference number: %s ', $matches[1] ); - } - } - } - - throw new Exception( $message, $code ); - } + // Copy Accept-Language from browser headers + if (! empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { + $headers['Accept-Language'] = $_SERVER['HTTP_ACCEPT_LANGUAGE']; + } + + return $headers; + } + + /** + * @param array|WP_Error $response + * @return object + * @throws Exception + */ + private function parse_response($response) + { + if (is_wp_error($response)) { + throw new Exception('Error connecting to Newsletter. ' . $response->get_error_message(), (int) $response->get_error_code()); + } + + // decode response body + $body = wp_remote_retrieve_body($response); + $data = json_decode($body); + if (! is_null($data)) { + return $data; + } + + $code = (int) wp_remote_retrieve_response_code($response); + $message = wp_remote_retrieve_response_message($response); + + if ($code !== 200) { + $message = sprintf('The Newsletter API server returned the following response: %s %s.', $code, $message); + + // check for Akamai firewall response + if ($code === 403) { + preg_match('/Reference (.*)/i', $body, $matches); + + if (! empty($matches[1])) { + $message .= '

' . sprintf('This usually means that your server is blacklisted by Newsletter\'s firewall. Please contact Newsletter support with the following reference number: %s ', $matches[1]); + } + } + } + + throw new Exception($message, $code); + } } diff --git a/includes/api/class-connection-exception.php b/includes/api/class-connection-exception.php index a439588..9746858 100755 --- a/includes/api/class-connection-exception.php +++ b/includes/api/class-connection-exception.php @@ -1,3 +1,5 @@ request = $request; $this->response = $response; @@ -38,10 +47,13 @@ public function __construct( $message, $code, $request = null, $response = null, /** * Backwards compatibility for direct property access. + * @param string $property + * @return mixed */ - public function __get( $property ) { - if( in_array( $property, array( 'title', 'detail', 'errors' ) ) ) { - if( ! empty( $this->response_data ) && isset( $this->response_data->{$property} ) ) { + public function __get($property) + { + if (in_array($property, array( 'title', 'detail', 'errors' ))) { + if (! empty($this->response_data) && isset($this->response_data->{$property})) { return $this->response_data->{$property}; } @@ -52,55 +64,56 @@ public function __get( $property ) { /** * @return string */ - public function __toString() { + public function __toString() + { $string = $this->message . '.'; // add errors from response data returned by Newsletter - if( ! empty( $this->response_data ) ) { - if( ! empty( $this->response_data->title ) && $this->response_data->title !== $this->getMessage() ) { + if (! empty($this->response_data)) { + if (! empty($this->response_data->title) && $this->response_data->title !== $this->getMessage()) { $string .= ' ' . $this->response_data->title . '.'; } // add detail message - if( ! empty( $this->response_data->detail ) ) { + if (! empty($this->response_data->detail)) { $string .= ' ' . $this->response_data->detail; } // add field specific errors - if( ! empty( $this->response_data->errors ) && isset( $this->response_data->errors[0]->field ) ) { + if (! empty($this->response_data->errors) && isset($this->response_data->errors[0]->field)) { // strip off obsolete msg - $string = str_replace( 'For field-specific details, see the \'errors\' array.', '', $string ); + $string = str_replace('For field-specific details, see the \'errors\' array.', '', $string); // generate list of field errors $field_errors = array(); - foreach( $this->response_data->errors as $error ) { - if( ! empty( $error->field ) ) { - $field_errors[] = sprintf( '- %s : %s', $error->field, $error->message ); + foreach ($this->response_data->errors as $error) { + if (! empty($error->field)) { + $field_errors[] = sprintf('- %s : %s', $error->field, $error->message); } else { - $field_errors[] = sprintf( '- %s', $error->message ); + $field_errors[] = sprintf('- %s', $error->message); } } - $string .= " \n" . join( "\n", $field_errors ); + $string .= " \n" . join("\n", $field_errors); } } // Add request data - if( ! empty( $this->request ) && is_array( $this->request ) ) { - $string .= "\n" . sprintf( 'Request: %s %s', $this->request['method'], $this->request['url'] ); + if (! empty($this->request) && is_array($this->request)) { + $string .= "\n" . sprintf('Request: %s %s', $this->request['method'], $this->request['url']); - if( ! empty( $this->request['body'] ) ) { - $string .= sprintf( ' - %s', $this->request['body'] ); + if (! empty($this->request['body'])) { + $string .= sprintf(' - %s', $this->request['body']); } } // Add response data - if( ! empty( $this->response ) && is_array( $this->response ) ) { - $response_code = wp_remote_retrieve_response_code( $this->response ); - $response_message = wp_remote_retrieve_response_message( $this->response ); - $response_body = wp_remote_retrieve_body( $this->response ); - $string .= "\n" . sprintf( 'Response: %d %s - %s', $response_code, $response_message, $response_body ); + if (! empty($this->response) && is_array($this->response)) { + $response_code = wp_remote_retrieve_response_code($this->response); + $response_message = wp_remote_retrieve_response_message($this->response); + $response_body = wp_remote_retrieve_body($this->response); + $string .= "\n" . sprintf('Response: %d %s - %s', $response_code, $response_message, $response_body); } return $string; diff --git a/includes/api/class-resource-not-found-exception.php b/includes/api/class-resource-not-found-exception.php index 6175dd8..9da2cdd 100755 --- a/includes/api/class-resource-not-found-exception.php +++ b/includes/api/class-resource-not-found-exception.php @@ -1,3 +1,6 @@ array = $array; - } - - /** - * @return array - */ - public function keys() { - return array_keys( $this->array ); - } - - /** - * @param string $name - * @param mixed $value - */ - public function set( $name, $value ) { - $this->array[ $name ] = $value; - } - - /** - * @param string $name - * @param mixed $default - * - * @return mixed - */ - public function get( $name, $default = null ) { - if( isset( $this->array[ $name ] ) ) { +class NL4WP_Array_Bag +{ + + /** + * @var array + */ + protected $array; + + /** + * @param array $array + */ + public function __construct(array $array) + { + $this->array = $array; + } + + /** + * @return array + */ + public function keys() + { + return array_keys($this->array); + } + + /** + * @param string $name + * @param mixed $value + */ + public function set($name, $value) + { + $this->array[ $name ] = $value; + } + + /** + * @param string $name + * @param mixed $default + * + * @return mixed + */ + public function get($name, $default = null) + { + if (isset($this->array[ $name ])) { return $this->array[ $name ]; } // allow dot access for nested array keys: key.subkey $array = $this->array; - foreach(explode('.', $name) as $segment) { - if ( ! array_key_exists( $segment, $array )) { + foreach (explode('.', $name) as $segment) { + if (! array_key_exists($segment, $array)) { return $default; } $array = $array[$segment]; - } - - return $array; - } - - /** - * @return array - */ - public function all() { - return $this->array; - } - - /** - * @param $prefix - * - * @return array - */ - public function all_with_prefix( $prefix ) { - $return = array(); - $length = strlen( $prefix ); - - foreach( $this->array as $key => $value ) { - if( strpos( $key, $prefix ) === 0 ) { - - $new_key = substr( $key, $length ); - $return[ $new_key ] = $value; - } - } - - return $return; - } - - /** - * @param $prefix - * @return array - */ - public function all_without_prefix( $prefix ) { - $return = array(); - - foreach( $this->array as $key => $value ) { - if( strpos( $key, $prefix ) !== 0 ) { - $return[ $key ] = $value; - } - } - - return $return; - } -} \ No newline at end of file + } + + return $array; + } + + /** + * @return array + */ + public function all() + { + return $this->array; + } + + /** + * @param $prefix + * + * @return array + */ + public function all_with_prefix($prefix) + { + $return = array(); + $length = strlen($prefix); + + foreach ($this->array as $key => $value) { + if (strpos($key, $prefix) === 0) { + $new_key = substr($key, $length); + $return[ $new_key ] = $value; + } + } + + return $return; + } + + /** + * @param $prefix + * @return array + */ + public function all_without_prefix($prefix) + { + $return = array(); + + foreach ($this->array as $key => $value) { + if (strpos($key, $prefix) !== 0) { + $return[ $key ] = $value; + } + } + + return $return; + } +} diff --git a/includes/class-container.php b/includes/class-container.php index 269fbbe..946c7d3 100755 --- a/includes/class-container.php +++ b/includes/class-container.php @@ -6,116 +6,123 @@ * @access private * @ignore */ -class NL4WP_Container implements ArrayAccess { +class NL4WP_Container implements ArrayAccess +{ - /** - * @var array - */ - protected $services = array(); + /** + * @var array + */ + protected $services = array(); - /** - * @var array - */ - protected $resolved_services = array(); + /** + * @var array + */ + protected $resolved_services = array(); - /** - * @param $name - * @return boolean - */ - public function has( $name ) { - return isset( $this->services[ $name ] ); - } + /** + * @param $name + * @return boolean + */ + public function has($name) + { + return isset($this->services[ $name ]); + } - /** - * @param $name - * - * @return mixed - * @throws Exception - */ - public function get( $name ) { + /** + * @param $name + * + * @return mixed + * @throws Exception + */ + public function get($name) + { + if (! $this->has($name)) { + throw new Exception(sprintf('No service named %s was registered.', $name)); + } - if( ! $this->has( $name ) ) { - throw new Exception( sprintf( 'No service named %s was registered.', $name ) ); - } + $service = $this->services[ $name ]; - $service = $this->services[ $name ]; + // is this a resolvable service? + if (is_callable($service)) { - // is this a resolvable service? - if( is_callable( $service ) ) { + // resolve service if it's not resolved yet + if (! isset($this->resolved_services[ $name ])) { + $this->resolved_services[ $name ] = call_user_func($service); + } - // resolve service if it's not resolved yet - if( ! isset( $this->resolved_services[ $name ] ) ) { - $this->resolved_services[ $name ] = call_user_func( $service ); - } + return $this->resolved_services[ $name ]; + } - return $this->resolved_services[ $name ]; - } + return $this->services[ $name ]; + } - return $this->services[ $name ]; - } + /** + * (PHP 5 >= 5.0.0)
+ * Whether a offset exists + * @link http://php.net/manual/en/arrayaccess.offsetexists.php + * + * @param mixed $offset

+ * An offset to check for. + *

+ * + * @return boolean true on success or false on failure. + *

+ *

+ * The return value will be casted to boolean if non-boolean was returned. + */ + public function offsetExists($offset) + { + return $this->has($offset); + } - /** - * (PHP 5 >= 5.0.0)
- * Whether a offset exists - * @link http://php.net/manual/en/arrayaccess.offsetexists.php - * - * @param mixed $offset

- * An offset to check for. - *

- * - * @return boolean true on success or false on failure. - *

- *

- * The return value will be casted to boolean if non-boolean was returned. - */ - public function offsetExists( $offset ) { - return $this->has( $offset ); - } + /** + * (PHP 5 >= 5.0.0)
+ * Offset to retrieve + * @link http://php.net/manual/en/arrayaccess.offsetget.php + * + * @param mixed $offset

+ * The offset to retrieve. + *

+ * + * @return mixed Can return all value types. + */ + public function offsetGet($offset) + { + return $this->get($offset); + } - /** - * (PHP 5 >= 5.0.0)
- * Offset to retrieve - * @link http://php.net/manual/en/arrayaccess.offsetget.php - * - * @param mixed $offset

- * The offset to retrieve. - *

- * - * @return mixed Can return all value types. - */ - public function offsetGet( $offset ) { - return $this->get( $offset ); - } + /** + * (PHP 5 >= 5.0.0)
+ * Offset to set + * @link http://php.net/manual/en/arrayaccess.offsetset.php + * + * @param mixed $offset

+ * The offset to assign the value to. + *

+ * @param mixed $value

+ * The value to set. + *

+ * + * @return void + */ + public function offsetSet($offset, $value) + { + $this->services[ $offset ] = $value; + } - /** - * (PHP 5 >= 5.0.0)
- * Offset to set - * @link http://php.net/manual/en/arrayaccess.offsetset.php - * - * @param mixed $offset

- * The offset to assign the value to. - *

- * @param mixed $value

- * The value to set. - *

- * - * @return void - */ - public function offsetSet( $offset, $value ) { - $this->services[ $offset ] = $value; - } - - /** - * (PHP 5 >= 5.0.0)
- * Offset to unset - * @link http://php.net/manual/en/arrayaccess.offsetunset.php - * - * @param mixed $offset

- * The offset to unset. - *

- * - * @return void - */ - public function offsetUnset( $offset ) { - unset( $this->services[ $offset ] ); -}} \ No newline at end of file + /** + * (PHP 5 >= 5.0.0)
+ * Offset to unset + * @link http://php.net/manual/en/arrayaccess.offsetunset.php + * + * @param mixed $offset

+ * The offset to unset. + *

+ * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->services[ $offset ]); + } +} diff --git a/includes/class-debug-log-reader.php b/includes/class-debug-log-reader.php index e3eb3fa..14e2d44 100755 --- a/includes/class-debug-log-reader.php +++ b/includes/class-debug-log-reader.php @@ -3,60 +3,64 @@ /** * Class NL4WP_Debug_Log_Reader */ -class NL4WP_Debug_Log_Reader { +class NL4WP_Debug_Log_Reader +{ - /** - * @var resource|null - */ - private $handle; + /** + * @var resource|null + */ + private $handle; - /** - * @var string - */ - private static $regex = '/^(\[[\d \-\:]+\]) (\w+\:) (.*)$/S'; + /** + * @var string + */ + private static $regex = '/^(\[[\d \-\:]+\]) (\w+\:) (.*)$/S'; /** * @var string */ private static $html_template = '$1 $2 $3'; - /** - * @var string The log file location. - */ - private $file; - - /** - * NL4WP_Debug_Log_Reader constructor. - * - * @param $file - */ - public function __construct( $file ) { - $this->file = $file; - } - - /** - * @return string - */ - public function all() { - return file_get_contents( $this->file ); - } + /** + * @var string The log file location. + */ + private $file; + + /** + * NL4WP_Debug_Log_Reader constructor. + * + * @param $file + */ + public function __construct($file) + { + $this->file = $file; + } + + /** + * @return string + */ + public function all() + { + return file_get_contents($this->file); + } /** * Sets file pointer to $n of lines from the end of file. * * @param int $n */ - private function seek_line_from_end( $n ) { + private function seek_line_from_end($n) + { $line_count = 0; // get line count - while( ! feof( $this->handle ) ) { - fgets( $this->handle ); + while (! feof($this->handle)) { + fgets($this->handle); $line_count++; } // rewind to beginning - rewind( $this->handle ); + rewind($this->handle); // calculate target $target = $line_count - $n; @@ -64,93 +68,95 @@ private function seek_line_from_end( $n ) { $current = 0; // keep reading until we're at target - while( $current < $target ) { - fgets( $this->handle ); + while ($current < $target) { + fgets($this->handle); $current++; } } - /** - * @return string|null - */ - public function read() { + /** + * @return string|null + */ + public function read() + { - // open file if not yet opened - if( ! is_resource( $this->handle ) ) { + // open file if not yet opened + if (! is_resource($this->handle)) { - // doesn't exist? - if( ! file_exists( $this->file ) ) { - return null; - } + // doesn't exist? + if (! file_exists($this->file)) { + return null; + } - $this->handle = @fopen( $this->file, 'r' ); + $this->handle = @fopen($this->file, 'r'); // unable to read? - if( ! is_resource( $this->handle ) ) { + if (! is_resource($this->handle)) { return null; } // set pointer to 1000 files from EOF - $this->seek_line_from_end( 1000 ); - } + $this->seek_line_from_end(1000); + } - // stop reading once we're at the end - if( feof( $this->handle ) ) { - fclose( $this->handle ); + // stop reading once we're at the end + if (feof($this->handle)) { + fclose($this->handle); $this->handle = null; return null; } - // read line, up to 8kb - $text = fgets( $this->handle ); - - // strip tags & trim - $text = strip_tags( $text ); - $text = trim( $text ); - - return $text; - } - - /** - * @return string - */ - public function read_as_html() { - $line = $this->read(); - - // null means end of file - if( is_null( $line ) ) { - return null; - } - - // empty string means empty line, but not yet eof - if( empty( $line ) ) { - return ''; - } - - $line = preg_replace( self::$regex, self::$html_template, $line ); - return $line; - } - - /** - * Reads X number of lines. - * - * If $start is negative, reads from end of log file. - * - * @param int $start - * @param int $number - * @return string - */ - public function lines( $start, $number ) { - $handle = fopen( $start, 'r' ); - $lines = ''; - - $current_line = 0; - while( $current_line < $number ) { - $lines .= fgets( $handle ); - } - - fclose( $handle ); - return $lines; - } + // read line, up to 8kb + $text = fgets($this->handle); + // strip tags & trim + $text = strip_tags($text); + $text = trim($text); + + return $text; + } + + /** + * @return string + */ + public function read_as_html() + { + $line = $this->read(); + + // null means end of file + if (is_null($line)) { + return null; + } + + // empty string means empty line, but not yet eof + if (empty($line)) { + return ''; + } + + $line = preg_replace(self::$regex, self::$html_template, $line); + return $line; + } + + /** + * Reads X number of lines. + * + * If $start is negative, reads from end of log file. + * + * @param int $start + * @param int $number + * @return string + */ + public function lines($start, $number) + { + $handle = fopen($start, 'r'); + $lines = ''; + + $current_line = 0; + while ($current_line < $number) { + $lines .= fgets($handle); + } + + fclose($handle); + return $lines; + } } diff --git a/includes/class-debug-log.php b/includes/class-debug-log.php index 1d59b42..263f5d6 100755 --- a/includes/class-debug-log.php +++ b/includes/class-debug-log.php @@ -5,218 +5,222 @@ * * Simple logging class which writes to a file, loosely based on PSR-3. */ -class NL4WP_Debug_Log{ - - /** - * Detailed debug information - */ - const DEBUG = 100; - - /** - * Interesting events - * - * Examples: Visitor subscribed - */ - const INFO = 200; - - /** - * Exceptional occurrences that are not errors - * - * Examples: User already subscribed - */ - const WARNING = 300; - - /** - * Runtime errors - */ - const ERROR = 400; - - /** - * Logging levels from syslog protocol defined in RFC 5424 - * - * @var array $levels Logging levels - */ - protected static $levels = array( - self::DEBUG => 'DEBUG', - self::INFO => 'INFO', - self::WARNING => 'WARNING', - self::ERROR => 'ERROR', - ); - - /** - * @var string The file to which messages should be written. - */ - public $file; - - /** - * @var int Only write messages with this level or higher - */ - public $level; - - /** - * @var resource - */ - protected $stream; - - /** - * NL4WP_Debug_Log constructor. - * - * @param string $file - * @param mixed $level; - */ - public function __construct( $file, $level = self::DEBUG ) { - $this->file = $file; - $this->level = self::to_level( $level ); - } - - /** - * @param mixed $level - * @param string $message - * @return boolean - */ - public function log( $level, $message ) { - - $level = self::to_level( $level ); - - // only log if message level is higher than log level - if( $level < $this->level ) { - return false; - } - - // obfuscate email addresses in log message since log might be public. - $message = nl4wp_obfuscate_email_addresses( (string) $message ); - - // first, get rid of everything between "invisible" tags - $message = preg_replace( '/<(?:style|script|head)>.+?<\/(?:style|script|head)>/is', '', $message ); - - // then, strip tags (while retaining content of these tags) - $message = strip_tags( $message ); - $message = trim( $message ); - - // generate line - $level_name = self::get_level_name( $level ); - $datetime = date( 'Y-m-d H:i:s', ( time() - date('Z') ) + ( get_option( 'gmt_offset', 0 ) * 3600 ) ); - $message = sprintf( '[%s] %s: %s', $datetime, $level_name, $message ) . PHP_EOL; - - // did we open stream yet? - if( ! is_resource( $this->stream ) ) { - - // open stream - $this->stream = @fopen( $this->file, 'c+' ); - - // if this failed, bail.. - if ( ! is_resource( $this->stream ) ) { - return false; - } +class NL4WP_Debug_Log +{ + + /** + * Detailed debug information + */ + const DEBUG = 100; + + /** + * Interesting events + * + * Examples: Visitor subscribed + */ + const INFO = 200; + + /** + * Exceptional occurrences that are not errors + * + * Examples: User already subscribed + */ + const WARNING = 300; + + /** + * Runtime errors + */ + const ERROR = 400; + + /** + * Logging levels from syslog protocol defined in RFC 5424 + * + * @var array $levels Logging levels + */ + protected static $levels = array( + self::DEBUG => 'DEBUG', + self::INFO => 'INFO', + self::WARNING => 'WARNING', + self::ERROR => 'ERROR', + ); + + /** + * @var string The file to which messages should be written. + */ + public $file; + + /** + * @var int Only write messages with this level or higher + */ + public $level; + + /** + * @var resource + */ + protected $stream; + + /** + * NL4WP_Debug_Log constructor. + * + * @param string $file + * @param mixed $level; + */ + public function __construct($file, $level = self::DEBUG) + { + $this->file = $file; + $this->level = self::to_level($level); + } + + /** + * @param mixed $level + * @param string $message + * @return boolean + */ + public function log($level, $message) + { + $level = self::to_level($level); + + // only log if message level is higher than log level + if ($level < $this->level) { + return false; + } + + // obfuscate email addresses in log message since log might be public. + $message = nl4wp_obfuscate_email_addresses((string) $message); + + // first, get rid of everything between "invisible" tags + $message = preg_replace('/<(?:style|script|head)>.+?<\/(?:style|script|head)>/is', '', $message); + + // then, strip tags (while retaining content of these tags) + $message = strip_tags($message); + $message = trim($message); + + // generate line + $level_name = self::get_level_name($level); + $datetime = date('Y-m-d H:i:s', (time() - date('Z')) + (get_option('gmt_offset', 0) * 3600)); + $message = sprintf('[%s] %s: %s', $datetime, $level_name, $message) . PHP_EOL; + + // did we open stream yet? + if (! is_resource($this->stream)) { + + // open stream + $this->stream = @fopen($this->file, 'c+'); + + // if this failed, bail.. + if (! is_resource($this->stream)) { + return false; + } // make sure first line of log file is a PHP tag + exit statement (to prevent direct file access) - $line = fgets( $this->stream ); + $line = fgets($this->stream); $php_exit_string = ''; - if( strpos( $line, $php_exit_string ) !== 0 ) { - rewind( $this->stream ); - fwrite( $this->stream, $php_exit_string . PHP_EOL . $line ); + if (strpos($line, $php_exit_string) !== 0) { + rewind($this->stream); + fwrite($this->stream, $php_exit_string . PHP_EOL . $line); } // place pointer at end of file - fseek( $this->stream, 0, SEEK_END ); - } - - // lock file while we write, ignore errors (not much we can do) - flock( $this->stream, LOCK_EX ); - - // write the message to the file - fwrite( $this->stream, $message ); - - // unlock file again, but don't close it for remainder of this request - flock( $this->stream, LOCK_UN ); - - return true; - } - - /** - * @param string $message - * @return boolean - */ - public function warning( $message ) { - return $this->log( self::WARNING, $message ); - } - - /** - * @param string $message - * @return boolean - */ - public function info( $message ) { - return $this->log( self::INFO, $message ); - } - - /** - * @param string $message - * @return boolean - */ - public function error( $message ) { - return $this->log( self::ERROR, $message ); - } - - /** - * @param string $message - * @return boolean - */ - public function debug( $message ) { - return $this->log( self::DEBUG, $message ); - } - - /** - * Converts PSR-3 levels to local ones if necessary - * - * @param string|int Level number or name (PSR-3) - * @return int - */ - public static function to_level( $level ) { - - if ( is_string( $level ) ) { - - $level = strtoupper( $level ); - if( defined( __CLASS__ . '::' . $level ) ) { - return constant( __CLASS__ . '::' . $level ); - } - - throw new InvalidArgumentException( 'Level "' . $level . '" is not defined, use one of: ' . implode( ', ', array_keys( self::$levels ) ) ); - } - - return $level; - } - - /** - * Gets the name of the logging level. - * - * @param int $level - * @return string - */ - public static function get_level_name( $level ) { - - if ( ! isset( self::$levels[ $level ] ) ) { - throw new InvalidArgumentException( 'Level "' . $level . '" is not defined, use one of: ' . implode( ', ', array_keys( self::$levels ) ) ); - } - - return self::$levels[ $level ]; - } - - /** - * Tests if the log file is writable - * - * @return bool - */ - public function test() { - $handle = @fopen( $this->file, 'a' ); - $writable = false; - - if( is_resource( $handle ) ) { - $writable = true; - fclose( $handle ); - } - - return $writable; - } + fseek($this->stream, 0, SEEK_END); + } + + // lock file while we write, ignore errors (not much we can do) + flock($this->stream, LOCK_EX); + + // write the message to the file + fwrite($this->stream, $message); + + // unlock file again, but don't close it for remainder of this request + flock($this->stream, LOCK_UN); + + return true; + } + + /** + * @param string $message + * @return boolean + */ + public function warning($message) + { + return $this->log(self::WARNING, $message); + } + + /** + * @param string $message + * @return boolean + */ + public function info($message) + { + return $this->log(self::INFO, $message); + } + + /** + * @param string $message + * @return boolean + */ + public function error($message) + { + return $this->log(self::ERROR, $message); + } + + /** + * @param string $message + * @return boolean + */ + public function debug($message) + { + return $this->log(self::DEBUG, $message); + } + + /** + * Converts PSR-3 levels to local ones if necessary + * + * @param string|int Level number or name (PSR-3) + * @return int + */ + public static function to_level($level) + { + if (is_string($level)) { + $level = strtoupper($level); + if (defined(__CLASS__ . '::' . $level)) { + return constant(__CLASS__ . '::' . $level); + } + throw new InvalidArgumentException('Level "' . $level . '" is not defined, use one of: ' . implode(', ', array_keys(self::$levels))); + } + + return $level; + } + + /** + * Gets the name of the logging level. + * + * @param int $level + * @return string + */ + public static function get_level_name($level) + { + if (! isset(self::$levels[ $level ])) { + throw new InvalidArgumentException('Level "' . $level . '" is not defined, use one of: ' . implode(', ', array_keys(self::$levels))); + } + + return self::$levels[ $level ]; + } + + /** + * Tests if the log file is writable + * + * @return bool + */ + public function test() + { + $handle = @fopen($this->file, 'a'); + $writable = false; + + if (is_resource($handle)) { + $writable = true; + fclose($handle); + } + + return $writable; + } } - diff --git a/includes/class-dynamic-content-tags.php b/includes/class-dynamic-content-tags.php index 0c68e70..93db1a5 100755 --- a/includes/class-dynamic-content-tags.php +++ b/includes/class-dynamic-content-tags.php @@ -6,187 +6,194 @@ * @access private * @ignore */ -class NL4WP_Dynamic_Content_Tags { - - /** - * @var string - */ - public $context; - - /** - * @var string The escape mode for replacement values. - */ - protected $escape_mode = 'html'; - - /** - * @var array Array of registered dynamic content tags - */ - protected $tags = array(); - - - /** - * @param string $context - * @param array $tags; - */ - public function __construct( $context, $tags = array() ) { - $this->context = $context; - $this->tags = $tags; - } - - /** - * Return all registered tags - * - * @return array - */ - public function all() { - - $context = $this->context; - $tags = $this->tags; - - /** - * Filters the registered dynamic content tags for all contexts. - * - * @since 3.0 - * @param array $tags +class NL4WP_Dynamic_Content_Tags +{ + + /** + * @var string + */ + public $context; + + /** + * @var string The escape mode for replacement values. + */ + protected $escape_mode = 'html'; + + /** + * @var array Array of registered dynamic content tags + */ + protected $tags = array(); + + + /** + * @param string $context + * @param array $tags; + */ + public function __construct($context, $tags = array()) + { + $this->context = $context; + $this->tags = $tags; + } + + /** + * Return all registered tags + * + * @return array + */ + public function all() + { + $context = $this->context; + $tags = $this->tags; + + /** + * Filters the registered dynamic content tags for all contexts. + * + * @since 3.0 + * @param array $tags * @ignore - */ - $this->tags = (array) apply_filters( 'nl4wp_dynamic_content_tags', $tags ); - - /** - * Filters the registered dynamic content tags for a specific context. - * - * The dynamic part of the hook, `$context`, refers to the context (forms / integrations) - * - * @since 3.0 - * @param array $tags + */ + $this->tags = (array) apply_filters('nl4wp_dynamic_content_tags', $tags); + + /** + * Filters the registered dynamic content tags for a specific context. + * + * The dynamic part of the hook, `$context`, refers to the context (forms / integrations) + * + * @since 3.0 + * @param array $tags * @ignore - */ - $this->tags = (array) apply_filters( 'nl4wp_dynamic_content_tags_' . $context, $tags ); - return $this->tags; - } - - /** - * @param $matches - * - * @return string - */ - protected function replace_tag( $matches ) { - - $tags = $this->all(); - $tag = $matches[1]; - - if( isset( $tags[ $tag ] ) ) { - - $config = $tags[ $tag ]; - $replacement = ''; - - if( isset( $config['replacement'] ) ) { - $replacement = $config['replacement']; - } elseif( isset( $config['callback'] ) ) { - - // parse attributes - $attributes = array(); - if( isset( $matches[2] ) ) { - $attribute_string = $matches[2]; - $attributes = shortcode_parse_atts( $attribute_string ); - } - - // call function - $replacement = call_user_func( $config['callback'], $attributes ); - } - - return $this->escape_value( $replacement ); - } - - - // default to not replacing it - // @todo always replace with empty string? - return $matches[0]; - } - - /** - * @param string $string The string containing dynamic content tags. - * @param string $escape_mode Escape mode for the replacement value. Leave empty for no escaping. - * @return string - */ - public function replace( $string, $escape_mode = '' ) { + */ + $this->tags = (array) apply_filters('nl4wp_dynamic_content_tags_' . $context, $tags); + return $this->tags; + } + + /** + * @param $matches + * + * @return string + */ + protected function replace_tag($matches) + { + $tags = $this->all(); + $tag = $matches[1]; + + if (isset($tags[ $tag ])) { + $config = $tags[ $tag ]; + $replacement = ''; + + if (isset($config['replacement'])) { + $replacement = $config['replacement']; + } elseif (isset($config['callback'])) { + + // parse attributes + $attributes = array(); + if (isset($matches[2])) { + $attribute_string = $matches[2]; + $attributes = shortcode_parse_atts($attribute_string); + } + + // call function + $replacement = call_user_func($config['callback'], $attributes); + } + + return $this->escape_value($replacement); + } + + + // default to not replacing it + return $matches[0]; + } + + /** + * @param string $string The string containing dynamic content tags. + * @param string $escape_mode Escape mode for the replacement value. Leave empty for no escaping. + * @return string + */ + public function replace($string, $escape_mode = '') + { $this->escape_mode = $escape_mode; // replace strings like this: {tagname attr="value"} - $string = preg_replace_callback( '/\{(\w+)(\ +(?:(?!\{)[^}\n])+)*\}/', array( $this, 'replace_tag' ), $string ); + $string = preg_replace_callback('/\{(\w+)(\ +(?:(?!\{)[^}\n])+)*\}/', array( $this, 'replace_tag' ), $string); // call again to take care of nested variables - $string = preg_replace_callback( '/\{(\w+)(\ +(?:(?!\{)[^}\n])+)*\}/', array( $this, 'replace_tag' ), $string ); - return $string; - } - - /** - * @param string $string - * - * @return string - */ - public function replace_in_html( $string ) { - return $this->replace( $string, 'html' ); - } - - /** - * @param string $string - * - * @return string - */ - public function replace_in_attributes( $string ) { - return $this->replace( $string, 'attributes' ); - } - - /** - * @param string $string - * - * @return string - */ - public function replace_in_url( $string ) { - return $this->replace( $string, 'url' ); - } - - - - /** - * @param $value - * - * @return string - */ - protected function escape_value_url( $value ) { - return urlencode( $value ); - } - - /** - * @param $value - * - * @return string - */ - protected function escape_value_attributes( $value ) { - return esc_attr( $value ); - } - - /** - * @param $value - * - * @return string - */ - protected function escape_value_html( $value ) { - return esc_html( $value ); - } - - /** - * @param $value - * - * @return mixed - */ - protected function escape_value( $value ) { - - if( empty( $this->escape_mode ) ) { - return $value; - } - - return call_user_func( array( $this, 'escape_value_' . $this->escape_mode ), $value ); - } -} \ No newline at end of file + $string = preg_replace_callback('/\{(\w+)(\ +(?:(?!\{)[^}\n])+)*\}/', array( $this, 'replace_tag' ), $string); + return $string; + } + + /** + * @param string $string + * + * @return string + */ + public function replace_in_html($string) + { + return $this->replace($string, 'html'); + } + + /** + * @param string $string + * + * @return string + */ + public function replace_in_attributes($string) + { + return $this->replace($string, 'attributes'); + } + + /** + * @param string $string + * + * @return string + */ + public function replace_in_url($string) + { + return $this->replace($string, 'url'); + } + + + + /** + * @param $value + * + * @return string + */ + protected function escape_value_url($value) + { + return urlencode($value); + } + + /** + * @param $value + * + * @return string + */ + protected function escape_value_attributes($value) + { + return esc_attr($value); + } + + /** + * @param $value + * + * @return string + */ + protected function escape_value_html($value) + { + return esc_html($value); + } + + /** + * @param $value + * + * @return mixed + */ + protected function escape_value($value) + { + if (empty($this->escape_mode)) { + return $value; + } + + return call_user_func(array( $this, 'escape_value_' . $this->escape_mode ), $value); + } +} diff --git a/includes/class-field-formatter.php b/includes/class-field-formatter.php index ccf63d0..39b4cb7 100755 --- a/includes/class-field-formatter.php +++ b/includes/class-field-formatter.php @@ -5,122 +5,125 @@ * * Formats values based on what the Newsletter API expects or accepts for the given field types. */ -class NL4WP_Field_Formatter { - - /** - * @param mixed $value - * - * @return array - */ - public function address( $value ) { - // auto-format if this is a string - if( is_string( $value ) ) { - - // addr1, addr2, city, state, zip, country - $address_pieces = explode( ',', $value ); - $address_pieces = array_filter( $address_pieces ); - $address_pieces = array_values( $address_pieces ); - - // try to fill it.... this is a long shot - $value = array( - 'addr1' => $address_pieces[0], - 'city' => isset( $address_pieces[1] ) ? $address_pieces[1] : '', - 'state' => isset( $address_pieces[2] ) ? $address_pieces[2] : '', - 'zip' => isset( $address_pieces[3] ) ? $address_pieces[3] : '', - ); - - if( ! empty( $address_pieces[4] ) ) { - $value['country'] = $address_pieces[4]; - } - - } elseif( is_array( $value ) ) { - // merge with array of empty defaults to allow skipping certain fields - $default = array_fill_keys( array( 'addr1', 'city', 'state', 'zip' ), '' ); - $value = array_merge( $default, $value ); - } - - return $value; - } - - /** - * @param mixed $value - * - * @return string - */ - public function birthday( $value ) { - if( is_array( $value ) ) { - // allow for "day" and "month" fields - if( isset( $value['month'] ) && isset( $value['day'] ) ) { - $value = $value['month'] . '/' . $value['day']; - } else { - // if other array, just join together - $value = join( '/', $value ); - } - } - - $value = trim( $value ); - if( empty( $value ) ) { +class NL4WP_Field_Formatter +{ + + /** + * @param mixed $value + * + * @return array + */ + public function address($value) + { + // auto-format if this is a string + if (is_string($value)) { + + // addr1, addr2, city, state, zip, country + $address_pieces = explode(',', $value); + $address_pieces = array_filter($address_pieces); + $address_pieces = array_values($address_pieces); + + // try to fill it.... this is a long shot + $value = array( + 'addr1' => $address_pieces[0], + 'city' => isset($address_pieces[1]) ? $address_pieces[1] : '', + 'state' => isset($address_pieces[2]) ? $address_pieces[2] : '', + 'zip' => isset($address_pieces[3]) ? $address_pieces[3] : '', + ); + + if (! empty($address_pieces[4])) { + $value['country'] = $address_pieces[4]; + } + } elseif (is_array($value)) { + // merge with array of empty defaults to allow skipping certain fields + $default = array_fill_keys(array( 'addr1', 'city', 'state', 'zip' ), ''); + $value = array_merge($default, $value); + } + + return $value; + } + + /** + * @param mixed $value + * + * @return string + */ + public function birthday($value) + { + if (is_array($value)) { + // allow for "day" and "month" fields + if (isset($value['month']) && isset($value['day'])) { + $value = $value['month'] . '/' . $value['day']; + } else { + // if other array, just join together + $value = join('/', $value); + } + } + + $value = trim($value); + if (empty($value)) { return $value; } - // always use slashes as delimiter, so next part works - $value = str_replace( array( '.', '-' ), '/', $value ); - - // if first part looks like a day, flip order so month (or even year) comes first - // this allows `strtotime` to understand `dd/mm` values - $values = explode( '/', $value ); - if( $values[0] > 12 && $values[0] <= 31 && isset( $values[1] ) && $values[1] <= 12 ) { - $values = array_reverse ( $values ); - $value = join( '/', $values ); - } - - $value = (string) date('m/d', strtotime( $value ) ); - - return $value; - } - - /** - * @param mixed $value - * - * @return string - */ - public function date( $value ) { - - if( is_array( $value ) ) { - - // allow for "year", "month" and "day" keys - if( isset( $value['year'] ) && isset( $value['month'] ) && isset( $value['day'] ) ) { - $value = $value['year'] . '/' . $value['month'] . '/' . $value['day']; - } else { - // if other array, just join together - $value = join( '/', $value ); - } - } - - $value = trim( $value ); - if( empty( $value ) ) { + // always use slashes as delimiter, so next part works + $value = str_replace(array( '.', '-' ), '/', $value); + + // if first part looks like a day, flip order so month (or even year) comes first + // this allows `strtotime` to understand `dd/mm` values + $values = explode('/', $value); + if ($values[0] > 12 && $values[0] <= 31 && isset($values[1]) && $values[1] <= 12) { + $values = array_reverse($values); + $value = join('/', $values); + } + + $value = (string) date('m/d', strtotime($value)); + + return $value; + } + + /** + * @param mixed $value + * + * @return string + */ + public function date($value) + { + if (is_array($value)) { + + // allow for "year", "month" and "day" keys + if (isset($value['year']) && isset($value['month']) && isset($value['day'])) { + $value = $value['year'] . '/' . $value['month'] . '/' . $value['day']; + } else { + // if other array, just join together + $value = join('/', $value); + } + } + + $value = trim($value); + if (empty($value)) { return $value; } - return (string) date('Y-m-d', strtotime( $value ) ); - } + return (string) date('Y-m-d', strtotime($value)); + } /** * @param string $value * * @return string */ - public function language( $value ) { - $value = trim( $value ); + public function language($value) + { + $value = trim($value); - $exceptions = array( + $exceptions = array( 'pt_PT', 'es_ES', 'fr_CA', ); - if( ! in_array( $value, $exceptions ) ) { - $value = substr( $value, 0, 2 ); + if (! in_array($value, $exceptions)) { + $value = substr($value, 0, 2); } return $value; @@ -131,14 +134,15 @@ public function language( $value ) { * * @return bool */ - public function boolean( $value ) { + public function boolean($value) + { $falsey = array( 'false', '0' ); - if( in_array( $value, $falsey, true ) ) { + if (in_array($value, $falsey, true)) { return false; } // otherwise, just cast. return (bool) $value; } -} \ No newline at end of file +} diff --git a/includes/class-field-guesser.php b/includes/class-field-guesser.php index 81b2211..71593f4 100755 --- a/includes/class-field-guesser.php +++ b/includes/class-field-guesser.php @@ -6,119 +6,122 @@ * @access private * @ignore */ -class NL4WP_Field_Guesser { - - /** - * @var NL4WP_Array_Bag - */ - protected $fields; - - /** - * @param array $fields - */ - public function __construct( array $fields ) { - $fields = array_change_key_case( $fields, CASE_UPPER ); - $this->fields = new NL4WP_Array_Bag( $fields ); - } - - /** - * Get all data which is namespaced with a given namespace - * - * @param string $namespace - * - * @return array - */ - public function namespaced( $namespace = 'nl4wp-' ) { - $namespace = strtoupper( $namespace ); - return $this->fields->all_with_prefix( $namespace ); - } - - /** - * Guess values for the following fields - * - EMAIL - * - NAME - * - FNAME - * - LNAME - * - * @return array - */ - public function guessed() { - $guessed = array(); - - $fields = $this->fields->all(); - - foreach( $fields as $field => $value ) { +class NL4WP_Field_Guesser +{ + + /** + * @var NL4WP_Array_Bag + */ + protected $fields; + + /** + * @param array $fields + */ + public function __construct(array $fields) + { + $fields = array_change_key_case($fields, CASE_UPPER); + $this->fields = new NL4WP_Array_Bag($fields); + } + + /** + * Get all data which is namespaced with a given namespace + * + * @param string $namespace + * + * @return array + */ + public function namespaced($namespace = 'nl4wp-') + { + $namespace = strtoupper($namespace); + return $this->fields->all_with_prefix($namespace); + } + + /** + * Guess values for the following fields + * - EMAIL + * - NAME + * - FNAME + * - LNAME + * + * @return array + */ + public function guessed() + { + $guessed = array(); + + $fields = $this->fields->all(); + + foreach ($fields as $field => $value) { // transform value into array to support 1-level arrays - $sub_fields = is_array( $value ) ? $value : array( $value ); + $sub_fields = is_array($value) ? $value : array( $value ); - foreach( $sub_fields as $sub_field_value ) { + foreach ($sub_fields as $sub_field_value) { // poor man's urldecode, to get Enfold theme's contact element to work. - $sub_field_value = str_replace( '%40', '@', $sub_field_value ); + $sub_field_value = str_replace('%40', '@', $sub_field_value); // is this an email value? if so, assume it's the EMAIL field - if( empty( $guessed['EMAIL'] ) && is_string( $sub_field_value ) && is_email( $sub_field_value ) ) { + if (empty($guessed['EMAIL']) && is_string($sub_field_value) && is_email($sub_field_value)) { $guessed['EMAIL'] = $sub_field_value; continue 2; } // remove special characters from field name - $simple_key = str_replace( array( '-', '_', ' ' ), '', $field ); + $simple_key = str_replace(array( '-', '_', ' ' ), '', $field); - if( empty( $guessed['FNAME'] ) && $this->string_contains( $simple_key, array( 'FIRSTNAME', 'FNAME', 'GIVENNAME', 'FORENAME' ) ) ) { + if (empty($guessed['FNAME']) && $this->string_contains($simple_key, array( 'FIRSTNAME', 'FNAME', 'GIVENNAME', 'FORENAME' ))) { // find first name field $guessed['FNAME'] = $sub_field_value; - } elseif( empty( $guessed['LNAME'] ) && $this->string_contains( $simple_key, array( 'LASTNAME', 'LNAME', 'SURNAME', 'FAMILYNAME' ) ) ) { + } elseif (empty($guessed['LNAME']) && $this->string_contains($simple_key, array( 'LASTNAME', 'LNAME', 'SURNAME', 'FAMILYNAME' ))) { // find last name field $guessed['LNAME'] = $sub_field_value; - } elseif( empty( $guessed['NAME'] ) && $this->string_contains( $simple_key, 'NAME' ) ){ + } elseif (empty($guessed['NAME']) && $this->string_contains($simple_key, 'NAME')) { // find name field $guessed['NAME'] = $sub_field_value; } } + } + + return $guessed; + } + + /** + * @param $methods + * + * @return array + */ + public function combine($methods) + { + $combined = array(); + + foreach ($methods as $method) { + if (method_exists($this, $method)) { + $combined = array_merge($combined, call_user_func(array( $this, $method ))); + } + } + + return $combined; + } + + /** + * @param $haystack + * @param $needles + * + * @return bool + */ + private function string_contains($haystack, $needles) + { + if (! is_array($needles)) { + $needles = array( $needles ); + } + + foreach ($needles as $needle) { + if (strpos($haystack, $needle) !== false) { + return true; + } + } - } - - return $guessed; - } - - /** - * @param $methods - * - * @return array - */ - public function combine( $methods ) { - $combined = array(); - - foreach( $methods as $method ) { - if( method_exists( $this, $method ) ) { - $combined = array_merge( $combined, call_user_func( array( $this, $method ) ) ); - } - } - - return $combined; - } - - /** - * @param $haystack - * @param $needles - * - * @return bool - */ - private function string_contains( $haystack, $needles ) { - - if( ! is_array( $needles ) ) { - $needles = array( $needles ); - } - - foreach( $needles as $needle ) { - - if( strpos( $haystack, $needle ) !== false ) { - return true; - } - } - - return false; - } + return false; + } } diff --git a/includes/class-list-data-mapper.php b/includes/class-list-data-mapper.php index 8fbffda..7181c4c 100755 --- a/includes/class-list-data-mapper.php +++ b/includes/class-list-data-mapper.php @@ -7,154 +7,157 @@ * @since 4.0 * @ignore */ -class NL4WP_List_Data_Mapper { - - /** - * @var array - */ - private $data = array(); - - /** - * @var array - */ - private $list_ids = array(); - - /** - * @var NL4WP_Field_Formatter - */ - private $formatter; - - /** - * @param array $data - * @param array $list_ids - */ - public function __construct( array $data, array $list_ids ) { - $this->data = array_change_key_case( $data, CASE_UPPER ); - $this->list_ids = $list_ids; - $this->formatter = new NL4WP_Field_Formatter(); - - if( ! isset( $this->data['EMAIL'] ) ) { - throw new InvalidArgumentException( 'Data needs at least an EMAIL key.' ); - } - } - - /** - * @return NL4WP_Newsletter_Subscriber[] - */ - public function map() { - $newsletter = new NL4WP_Newsletter(); - $map = array(); - - foreach( $this->list_ids as $list_id ) { - $list = $newsletter->get_list( $list_id, true ); - - if( $list instanceof NL4WP_Newsletter_List ) { - $map[ $list_id ] = $this->map_list( $list ); - } - } - - return $map; - } - - /** - * @param NL4WP_Newsletter_List $list - * - * @return NL4WP_Newsletter_Subscriber - */ - protected function map_list( NL4WP_Newsletter_List $list ) { - - $subscriber = new NL4WP_Newsletter_Subscriber(); - $subscriber->email_address = $this->data['EMAIL']; - - // find merge fields - foreach( $list->merge_fields as $merge_field ) { - - // skip EMAIL field as that is handled separately (see above) - if( $merge_field->tag === 'EMAIL' ) { - continue; - } - - // use empty() here to skip empty field values - if( empty( $this->data[ $merge_field->tag ] ) ) { - continue; - } - - // format field value - $value = $this->data[ $merge_field->tag ]; - $value = $this->format_merge_field_value( $value, $merge_field->field_type ); - - // add to map - $subscriber->merge_fields[ $merge_field->tag ] = $value; - } - - // find interest categories - if( ! empty( $this->data['INTERESTS'] ) ) { - foreach( $list->interest_categories as $interest_category ) { - foreach( $interest_category->interests as $interest_id => $interest_name ) { - // straight lookup by ID as key with value copy. - if( isset( $this->data['INTERESTS'][ $interest_id ] ) ) { - $subscriber->interests[ $interest_id ] = $this->formatter->boolean( $this->data['INTERESTS'][ $interest_id ] ); - } - - // straight lookup by ID as top-level value - if( in_array( $interest_id, $this->data['INTERESTS'], false ) ) { - $subscriber->interests[ $interest_id ] = true; - } - - // look in array with category ID as key. - if( isset( $this->data['INTERESTS'][ $interest_category->id ] ) ) { - $value = $this->data['INTERESTS'][ $interest_category->id ]; - $values = is_array( $value ) ? $value : array_map( 'trim', explode( '|', $value ) ); - - // find by category ID + interest ID - if( in_array( $interest_id, $values, false ) ) { - $subscriber->interests[ $interest_id ] = true; - } - - // find by category ID + interest name - if( in_array( $interest_name, $values ) ) { - $subscriber->interests[ $interest_id ] = true; - } - } - } - } - } - - // find language - /* @see http://kb.newsletter.com/lists/managing-subscribers/view-and-edit-subscriber-languages?utm_source=mc-api&utm_medium=docs&utm_campaign=apidocs&_ga=1.211519638.2083589671.1469697070 */ - if( ! empty( $this->data['MC_LANGUAGE'] ) ) { - $subscriber->language = $this->formatter->language( $this->data['MC_LANGUAGE'] ); - } - - return $subscriber; - } - - - /** - * @param mixed $field_value - * @param string $field_type - * - * @return mixed - */ - private function format_merge_field_value( $field_value, $field_type ) { - $field_type = strtolower( $field_type ); - - if( method_exists( $this->formatter, $field_type ) ) { - $field_value = call_user_func( array( $this->formatter, $field_type ), $field_value ); - } - - /** - * Filters the value of a field after it is formatted. - * - * Use this to format a field value according to the field type (in Newsletter). - * - * @since 3.0 - * @param string $field_value The value - * @param string $field_type The type of the field (in Newsletter) - */ - $field_value = apply_filters( 'nl4wp_format_field_value', $field_value, $field_type ); - - return $field_value; - } - +class NL4WP_List_Data_Mapper +{ + + /** + * @var array + */ + private $data = array(); + + /** + * @var array + */ + private $list_ids = array(); + + /** + * @var NL4WP_Field_Formatter + */ + private $formatter; + + /** + * @param array $data + * @param array $list_ids + */ + public function __construct(array $data, array $list_ids) + { + $this->data = array_change_key_case($data, CASE_UPPER); + $this->list_ids = $list_ids; + $this->formatter = new NL4WP_Field_Formatter(); + + if (! isset($this->data['EMAIL'])) { + throw new InvalidArgumentException('Data needs at least an EMAIL key.'); + } + } + + /** + * @return NL4WP_Newsletter_Subscriber[] + */ + public function map() + { + $newsletter = new NL4WP_Newsletter(); + $map = array(); + + foreach ($this->list_ids as $list_id) { + $list = $newsletter->get_list($list_id, true); + + if ($list instanceof NL4WP_Newsletter_List) { + $map[ $list_id ] = $this->map_list($list); + } + } + + return $map; + } + + /** + * @param NL4WP_Newsletter_List $list + * + * @return NL4WP_Newsletter_Subscriber + */ + protected function map_list(NL4WP_Newsletter_List $list) + { + $subscriber = new NL4WP_Newsletter_Subscriber(); + $subscriber->email_address = $this->data['EMAIL']; + + // find merge fields + foreach ($list->merge_fields as $merge_field) { + + // skip EMAIL field as that is handled separately (see above) + if ($merge_field->tag === 'EMAIL') { + continue; + } + + // use empty() here to skip empty field values + if (empty($this->data[ $merge_field->tag ])) { + continue; + } + + // format field value + $value = $this->data[ $merge_field->tag ]; + $value = $this->format_merge_field_value($value, $merge_field->field_type); + + // add to map + $subscriber->merge_fields[ $merge_field->tag ] = $value; + } + + // find interest categories + if (! empty($this->data['INTERESTS'])) { + foreach ($list->interest_categories as $interest_category) { + foreach ($interest_category->interests as $interest_id => $interest_name) { + // straight lookup by ID as key with value copy. + if (isset($this->data['INTERESTS'][ $interest_id ])) { + $subscriber->interests[ $interest_id ] = $this->formatter->boolean($this->data['INTERESTS'][ $interest_id ]); + } + + // straight lookup by ID as top-level value + if (in_array($interest_id, $this->data['INTERESTS'], false)) { + $subscriber->interests[ $interest_id ] = true; + } + + // look in array with category ID as key. + if (isset($this->data['INTERESTS'][ $interest_category->id ])) { + $value = $this->data['INTERESTS'][ $interest_category->id ]; + $values = is_array($value) ? $value : array_map('trim', explode('|', $value)); + + // find by category ID + interest ID + if (in_array($interest_id, $values, false)) { + $subscriber->interests[ $interest_id ] = true; + } + + // find by category ID + interest name + if (in_array($interest_name, $values)) { + $subscriber->interests[ $interest_id ] = true; + } + } + } + } + } + + // find language + /* @see http://kb.newsletter.com/lists/managing-subscribers/view-and-edit-subscriber-languages?utm_source=mc-api&utm_medium=docs&utm_campaign=apidocs&_ga=1.211519638.2083589671.1469697070 */ + if (! empty($this->data['MC_LANGUAGE'])) { + $subscriber->language = $this->formatter->language($this->data['MC_LANGUAGE']); + } + + return $subscriber; + } + + + /** + * @param mixed $field_value + * @param string $field_type + * + * @return mixed + */ + private function format_merge_field_value($field_value, $field_type) + { + $field_type = strtolower($field_type); + + if (method_exists($this->formatter, $field_type)) { + $field_value = call_user_func(array( $this->formatter, $field_type ), $field_value); + } + + /** + * Filters the value of a field after it is formatted. + * + * Use this to format a field value according to the field type (in Newsletter). + * + * @since 3.0 + * @param string $field_value The value + * @param string $field_type The type of the field (in Newsletter) + */ + $field_value = apply_filters('nl4wp_format_field_value', $field_value, $field_type); + + return $field_value; + } } diff --git a/includes/class-newsletter.php b/includes/class-newsletter.php index 71754f5..a2a9767 100755 --- a/includes/class-newsletter.php +++ b/includes/class-newsletter.php @@ -1,476 +1,493 @@ reset_error(); - - $default_args = array( - 'status' => 'pending', - 'email_address' => $email_address, - 'interests' => array(), - 'merge_fields' => array(), - ); - $already_on_list = false; - - // setup default args - $args = $args + $default_args; - - // first, check if subscriber is already on the given list - try { - $existing_member_data = $this->get_api()->get_list_member( $list_id, $email_address ); - - if( $existing_member_data->status === 'subscribed' ) { - $already_on_list = true; - - // if we're not supposed to update, bail. - if( ! $update_existing ) { - $this->error_code = 214; - $this->error_message = 'That subscriber already exists.'; - return null; - } - - $args['status'] = 'subscribed'; - - // this key only exists if list actually has interests - if( isset( $existing_member_data->interests ) ) { - $existing_interests = (array) $existing_member_data->interests; - - // if replace, assume all existing interests disabled - if( $replace_interests ) { - $existing_interests = array_fill_keys( array_keys( $existing_interests ), false ); - } - - // TODO: Use array_replace here (PHP 5.3+) - $new_interests = $args['interests']; - $args['interests'] = $existing_interests; - foreach( $new_interests as $interest_id => $interest_status ) { - $args['interests']["{$interest_id}"] = $interest_status; - } - } - } else if( $args['status'] === 'pending' && $existing_member_data->status === 'pending' ) { - // if status is "pending", delete & then re-subscribe - // this ensures that a new double opt-in email is send out - $this->get_api()->delete_list_member( $list_id, $email_address ); - } - } catch( NL4WP_API_Resource_Not_Found_Exception $e ) { - // subscriber does not exist (not an issue in this case) - } catch( NL4WP_API_Exception $e ) { - // other errors. - $this->error_code = $e->getCode(); - $this->error_message = $e; - return null; - } - - try { - $data = $this->get_api()->add_list_member( $list_id, $args ); - } catch ( NL4WP_API_Exception $e ) { - $this->error_code = $e->getCode(); - $this->error_message = $e; - return null; - } - - $data->was_already_on_list = $already_on_list; - - return $data; - } - - /** - * Changes the subscriber status to "unsubscribed" - * - * @param string $list_id - * @param string $email_address - * - * @return boolean - */ - public function list_unsubscribe( $list_id, $email_address ) { - $this->reset_error(); - - try { - $this->get_api()->update_list_member( $list_id, $email_address, array( 'status' => 'unsubscribed' ) ); - } catch( NL4WP_API_Resource_Not_Found_Exception $e ) { - // if email wasn't even on the list: great. - return true; - } catch( NL4WP_API_Exception $e ) { - $this->error_code = $e->getCode(); - $this->error_message = $e; - return false; - } - - return true; - } - - /** - * Deletes the subscriber from the given list. - * - * @param string $list_id - * @param string $email_address - * - * @return boolean - */ - public function list_unsubscribe_delete( $list_id, $email_address ) { - $this->reset_error(); - - try { - $this->get_api()->delete_list_member( $list_id, $email_address ); - } catch( NL4WP_API_Resource_Not_Found_Exception $e ) { - // if email wasn't even on the list: great. - return true; - } catch( NL4WP_API_Exception $e ) { - $this->error_code = $e->getCode(); - $this->error_message = $e; - return false; - } - - return true; - } - - /** - * Checks if an email address is on a given list with status "subscribed" - * - * @param string $list_id - * @param string $email_address - * - * @return boolean - */ - public function list_has_subscriber( $list_id, $email_address ) { - try{ - $data = $this->get_api()->get_list_member( $list_id, $email_address ); - } catch( NL4WP_API_Resource_Not_Found_Exception $e ) { - return false; - } - - return ! empty( $data->id ) && $data->status === 'subscribed'; - } - - - /** - * Empty the Lists cache - */ - public function empty_cache() { - global $wpdb; - - delete_option( 'nl4wp_newsletter_list_ids' ); - $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'nl4wp_newsletter_list_%'" ); - delete_transient( 'nl4wp_list_counts' ); - } - - /** - * Get Newsletter lists from cache. - * - * @param boolean deprecated parameter. - * @return array - */ - public function get_cached_lists() { - return $this->get_lists( false ); - } - - /** - * Get a specific Newsletter list from local DB. - * - * @param string $list_id - * @return NL4WP_Newsletter_List - */ - public function get_cached_list( $list_id ) { - return $this->get_list( $list_id, false ); - } - - /** - * Get Newsletter lists, from cache or remote API. - * - * @param boolean $force Whether to force a result by hitting Newsletter API - * @return array - */ - public function get_lists( $force = true ) { - - // first, get all list id's - $list_ids = $this->get_list_ids( $force ); - - // then, fill $lists array with individual list details - $lists = array(); - foreach( $list_ids as $list_id ) { - $list = $this->get_list( $list_id, $force ); - $lists["{$list_id}"] = $list; - } - - return $lists; - } - - /** - * @param string $list_id - * - * @return NL4WP_Newsletter_List - */ - private function fetch_list( $list_id ) { - try{ - $list_data = $this->get_api()->get_list( $list_id, array( 'fields' => 'id,name,stats,web_id,campaign_defaults.from_name,campaign_defaults.from_email' ) ); - - // create local object - $list = new NL4WP_Newsletter_List( $list_data->id, $list_data->name ); - $list->subscriber_count = $list_data->stats->member_count; - $list->web_id = $list_data->web_id; - $list->campaign_defaults = $list_data->campaign_defaults; - - // get merge fields (if any) - if( $list_data->stats->merge_field_count > 0 ) { - $field_data = $this->get_api()->get_list_merge_fields( $list->id, array( 'count' => 100, 'fields' => 'merge_fields.name,merge_fields.tag,merge_fields.type,merge_fields.required,merge_fields.default_value,merge_fields.options,merge_fields.public' ) ); - - // hydrate data into object - foreach( $field_data as $data ) { - $object = NL4WP_Newsletter_Merge_Field::from_data( $data ); - $list->merge_fields[] = $object; - } - } - - // get interest categories - $interest_categories_data = $this->get_api()->get_list_interest_categories( $list->id, array( 'count' => 100, 'fields' => 'categories.id,categories.title,categories.type' ) ); - foreach( $interest_categories_data as $interest_category_data ) { - $interest_category = NL4WP_Newsletter_Interest_Category::from_data( $interest_category_data ); - - // fetch groups for this interest - $interests_data = $this->get_api()->get_list_interest_category_interests( $list->id, $interest_category->id, array( 'count' => 100, 'fields' => 'interests.id,interests.name') ); - foreach( $interests_data as $interest_data ) { - $interest_category->interests[ (string) $interest_data->id ] = $interest_data->name; - } - - $list->interest_categories[] = $interest_category; - } - } catch( NL4WP_API_Exception $e ) { - return null; - } - - // save in option - update_option( 'nl4wp_newsletter_list_' . $list_id, $list, false ); - return $list; - } - - /** - * Get Newsletter list ID's - * - * @param bool $force Force result by hitting Newsletter API - * @return array - */ - public function get_list_ids( $force = false ) { - $list_ids = (array) get_option( 'nl4wp_newsletter_list_ids', array() ); - - if( empty( $list_ids ) && $force ) { - $list_ids = $this->fetch_list_ids(); - } - - return $list_ids; - } - - /** - * @return array - */ - public function fetch_list_ids() { - /** - * Filters the amount of Newsletter lists to fetch. - * - * If you increase this, it might be necessary to increase your PHP configuration to allow for a higher max_execution_time. - * - * @param int - */ - $limit = apply_filters( 'nl4wp_newsletter_list_limit', 200 ); - - try{ - $lists_data = $this->get_api()->get_lists( array( 'count' => $limit, 'fields' => 'lists.id' ) ); - } catch( NL4WP_API_Exception $e ) { - return array(); - } - - $list_ids = wp_list_pluck( $lists_data, 'id' ); - - // store list id's - update_option( 'nl4wp_newsletter_list_ids', $list_ids, false ); - - return $list_ids; - } - - /** - * Fetch list ID's + lists from Newsletter. - * - * @return bool - */ - public function fetch_lists() { - // try to increase time limit as this can take a while - @set_time_limit(300); - $list_ids = $this->fetch_list_ids(); - - // randomize array order - shuffle( $list_ids ); - - // fetch individual list details - foreach ( $list_ids as $list_id ) { - $list = $this->fetch_list( $list_id ); - } - - return ! empty( $list_ids ); - } - - /** - * Get a given Newsletter list - * - * @param string $list_id - * @param bool $force Whether to force a result by hitting remote API - * @return NL4WP_Newsletter_List - */ - public function get_list( $list_id, $force = false ) { - $list = get_option( 'nl4wp_newsletter_list_' . $list_id ); - - if( empty( $list ) && $force ) { - $list = $this->fetch_list( $list_id ); - } - - if( empty( $list ) ) { - return new NL4WP_Newsletter_List( $list_id, 'Unknown List' ); - } - - return $list; - } - - /** - * Get an array of list_id => number of subscribers - * - * @return array - */ - public function get_subscriber_counts() { - - // get from transient - $list_counts = get_transient( 'nl4wp_list_counts' ); - if( is_array( $list_counts ) ) { - return $list_counts; - } - - // transient not valid, fetch from API - try { - $lists = $this->get_api()->get_lists( array( 'count' => 100, 'fields' => 'lists.id,lists.stats' ) ); - } catch( NL4WP_API_Exception $e ) { - return array(); - } - - $list_counts = array(); - - // we got a valid response - foreach ( $lists as $list ) { - $list_counts["{$list->id}"] = $list->stats->member_count; - } - - $seconds = 3600; - - /** - * Filters the cache time for Newsletter lists configuration, in seconds. Defaults to 3600 seconds (1 hour). - * - * @since 2.0 - * @param int $seconds - */ - $transient_lifetime = (int) apply_filters( 'nl4wp_lists_count_cache_time', $seconds ); - set_transient( 'nl4wp_list_counts', $list_counts, $transient_lifetime ); - - // bail - return $list_counts; - } - - - /** - * Returns number of subscribers on given lists. - * - * @param array|string $list_ids Array of list ID's, or single string. - * @return int Total # subscribers for given lists. - */ - public function get_subscriber_count( $list_ids ) { - - // make sure we're getting an array - if( ! is_array( $list_ids ) ) { - $list_ids = array( $list_ids ); - } - - // if we got an empty array, return 0 - if( empty( $list_ids ) ) { - return 0; - } - - // get total number of subscribers for all lists - $counts = $this->get_subscriber_counts(); - - // start calculating subscribers count for all given list ID's combined - $count = 0; - foreach ( $list_ids as $id ) { - $count += ( isset( $counts["{$id}"] ) ) ? $counts["{$id}"] : 0; - } - - /** - * Filters the total subscriber_count for the given List ID's. - * - * @since 2.0 - * @param string $count - * @param array $list_ids - */ - return apply_filters( 'nl4wp_subscriber_count', $count, $list_ids ); - } - - /** - * Resets error properties. - */ - public function reset_error() { - $this->error_message = ''; - $this->error_code = ''; - } - - /** - * @return bool - */ - public function has_error() { - return ! empty( $this->error_code ); - } - - /** - * @return string - */ - public function get_error_message() { - return $this->error_message; - } - - /** - * @return string - */ - public function get_error_code() { - return $this->error_code; - } - - /** - * @return NL4WP_API_v3 - */ - private function get_api() { - return nl4wp( 'api' ); - } - +class NL4WP_Newsletter +{ + + /** + * @var string + */ + public $error_code = ''; + + /** + * @var string + */ + public $error_message = ''; + + /** + * + * Sends a subscription request to the Newsletter API + * + * @param string $list_id The list id to subscribe to + * @param string $email_address The email address to subscribe + * @param array $args + * @param boolean $update_existing Update information if this email is already on list? + * @param boolean $replace_interests Replace interest groupings, only if update_existing is true. + * + * @return object + */ + public function list_subscribe($list_id, $email_address, array $args = array(), $update_existing = false, $replace_interests = true) + { + $this->reset_error(); + + $default_args = array( + 'status' => 'pending', + 'email_address' => $email_address, + 'interests' => array(), + 'merge_fields' => array(), + ); + $already_on_list = false; + + // setup default args + $args = $args + $default_args; + + // first, check if subscriber is already on the given list + try { + $existing_member_data = $this->get_api()->get_list_member($list_id, $email_address); + + if ($existing_member_data->status === 'subscribed') { + $already_on_list = true; + + // if we're not supposed to update, bail. + if (! $update_existing) { + $this->error_code = 214; + $this->error_message = 'That subscriber already exists.'; + return null; + } + + $args['status'] = 'subscribed'; + + // this key only exists if list actually has interests + if (isset($existing_member_data->interests)) { + $existing_interests = (array) $existing_member_data->interests; + + // if replace, assume all existing interests disabled + if ($replace_interests) { + $existing_interests = array_fill_keys(array_keys($existing_interests), false); + } + + // TODO: Use array_replace here (PHP 5.3+) + $new_interests = $args['interests']; + $args['interests'] = $existing_interests; + foreach ($new_interests as $interest_id => $interest_status) { + $args['interests']["{$interest_id}"] = $interest_status; + } + } + } elseif ($args['status'] === 'pending' && $existing_member_data->status === 'pending') { + // if status is "pending", delete & then re-subscribe + // this ensures that a new double opt-in email is send out + $this->get_api()->delete_list_member($list_id, $email_address); + } + } catch (NL4WP_API_Resource_Not_Found_Exception $e) { + // subscriber does not exist (not an issue in this case) + } catch (NL4WP_API_Exception $e) { + // other errors. + $this->error_code = $e->getCode(); + $this->error_message = $e; + return null; + } + + try { + $data = $this->get_api()->add_list_member($list_id, $args); + } catch (NL4WP_API_Exception $e) { + $this->error_code = $e->getCode(); + $this->error_message = $e; + return null; + } + + $data->was_already_on_list = $already_on_list; + + return $data; + } + + /** + * Changes the subscriber status to "unsubscribed" + * + * @param string $list_id + * @param string $email_address + * + * @return boolean + */ + public function list_unsubscribe($list_id, $email_address) + { + $this->reset_error(); + + try { + $this->get_api()->update_list_member($list_id, $email_address, array( 'status' => 'unsubscribed' )); + } catch (NL4WP_API_Resource_Not_Found_Exception $e) { + // if email wasn't even on the list: great. + return true; + } catch (NL4WP_API_Exception $e) { + $this->error_code = $e->getCode(); + $this->error_message = $e; + return false; + } + + return true; + } + + /** + * Deletes the subscriber from the given list. + * + * @param string $list_id + * @param string $email_address + * + * @return boolean + */ + public function list_unsubscribe_delete($list_id, $email_address) + { + $this->reset_error(); + + try { + $this->get_api()->delete_list_member($list_id, $email_address); + } catch (NL4WP_API_Resource_Not_Found_Exception $e) { + // if email wasn't even on the list: great. + return true; + } catch (NL4WP_API_Exception $e) { + $this->error_code = $e->getCode(); + $this->error_message = $e; + return false; + } + + return true; + } + + /** + * Checks if an email address is on a given list with status "subscribed" + * + * @param string $list_id + * @param string $email_address + * + * @return boolean + */ + public function list_has_subscriber($list_id, $email_address) + { + try { + $data = $this->get_api()->get_list_member($list_id, $email_address); + } catch (NL4WP_API_Resource_Not_Found_Exception $e) { + return false; + } + + return ! empty($data->id) && $data->status === 'subscribed'; + } + + + /** + * Empty the Lists cache + */ + public function empty_cache() + { + global $wpdb; + + delete_option('nl4wp_newsletter_list_ids'); + $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'nl4wp_newsletter_list_%'"); + delete_transient('nl4wp_list_counts'); + } + + /** + * Get Newsletter lists from cache. + * + * @param boolean deprecated parameter. + * @return array + */ + public function get_cached_lists() + { + return $this->get_lists(false); + } + + /** + * Get a specific Newsletter list from local DB. + * + * @param string $list_id + * @return NL4WP_Newsletter_List + */ + public function get_cached_list($list_id) + { + return $this->get_list($list_id, false); + } + + /** + * Get Newsletter lists, from cache or remote API. + * + * @param boolean $force Whether to force a result by hitting Newsletter API + * @return array + */ + public function get_lists($force = true) + { + + // first, get all list id's + $list_ids = $this->get_list_ids($force); + + // then, fill $lists array with individual list details + $lists = array(); + foreach ($list_ids as $list_id) { + $list = $this->get_list($list_id, $force); + $lists["{$list_id}"] = $list; + } + + return $lists; + } + + /** + * @param string $list_id + * + * @return NL4WP_Newsletter_List + */ + private function fetch_list($list_id) + { + try { + $list_data = $this->get_api()->get_list($list_id, array( 'fields' => 'id,name,stats,web_id,campaign_defaults.from_name,campaign_defaults.from_email' )); + + // create local object + $list = new NL4WP_Newsletter_List($list_data->id, $list_data->name); + $list->subscriber_count = $list_data->stats->member_count; + $list->web_id = $list_data->web_id; + $list->campaign_defaults = $list_data->campaign_defaults; + + // get merge fields (if any) + if ($list_data->stats->merge_field_count > 0) { + $field_data = $this->get_api()->get_list_merge_fields($list->id, array( 'count' => 100, 'fields' => 'merge_fields.name,merge_fields.tag,merge_fields.type,merge_fields.required,merge_fields.default_value,merge_fields.options,merge_fields.public' )); + + // hydrate data into object + foreach ($field_data as $data) { + $object = NL4WP_Newsletter_Merge_Field::from_data($data); + $list->merge_fields[] = $object; + } + } + + // get interest categories + $interest_categories_data = $this->get_api()->get_list_interest_categories($list->id, array( 'count' => 100, 'fields' => 'categories.id,categories.title,categories.type' )); + foreach ($interest_categories_data as $interest_category_data) { + $interest_category = NL4WP_Newsletter_Interest_Category::from_data($interest_category_data); + + // fetch groups for this interest + $interests_data = $this->get_api()->get_list_interest_category_interests($list->id, $interest_category->id, array( 'count' => 100, 'fields' => 'interests.id,interests.name')); + foreach ($interests_data as $interest_data) { + $interest_category->interests[ (string) $interest_data->id ] = $interest_data->name; + } + + $list->interest_categories[] = $interest_category; + } + } catch (NL4WP_API_Exception $e) { + return null; + } + + // save in option + update_option('nl4wp_newsletter_list_' . $list_id, $list, false); + return $list; + } + + /** + * Get Newsletter list ID's + * + * @param bool $force Force result by hitting Newsletter API + * @return array + */ + public function get_list_ids($force = false) + { + $list_ids = (array) get_option('nl4wp_newsletter_list_ids', array()); + + if (empty($list_ids) && $force) { + $list_ids = $this->fetch_list_ids(); + } + + return $list_ids; + } + + /** + * @return array + */ + public function fetch_list_ids() + { + /** + * Filters the amount of Newsletter lists to fetch. + * + * If you increase this, it might be necessary to increase your PHP configuration to allow for a higher max_execution_time. + * + * @param int + */ + $limit = apply_filters('nl4wp_newsletter_list_limit', 200); + + try { + $lists_data = $this->get_api()->get_lists(array( 'count' => $limit, 'fields' => 'lists.id' )); + } catch (NL4WP_API_Exception $e) { + return array(); + } + + $list_ids = wp_list_pluck($lists_data, 'id'); + + // store list id's + update_option('nl4wp_newsletter_list_ids', $list_ids, false); + + return $list_ids; + } + + /** + * Fetch list ID's + lists from Newsletter. + * + * @return bool + */ + public function fetch_lists() + { + // try to increase time limit as this can take a while + @set_time_limit(600); + $list_ids = $this->fetch_list_ids(); + + // randomize array order + shuffle($list_ids); + + // fetch individual list details + foreach ($list_ids as $list_id) { + $list = $this->fetch_list($list_id); + } + + return ! empty($list_ids); + } + + /** + * Get a given Newsletter list + * + * @param string $list_id + * @param bool $force Whether to force a result by hitting remote API + * @return NL4WP_Newsletter_List + */ + public function get_list($list_id, $force = false) + { + $list = get_option('nl4wp_newsletter_list_' . $list_id); + + if (empty($list) && $force) { + $list = $this->fetch_list($list_id); + } + + if (empty($list)) { + return new NL4WP_Newsletter_List($list_id, 'Unknown List'); + } + + return $list; + } + + /** + * Get an array of list_id => number of subscribers + * + * @return array + */ + public function get_subscriber_counts() + { + $list_counts = get_transient('nl4wp_list_counts'); + if (is_array($list_counts)) { + return $list_counts; + } + + // transient not valid, fetch from API + try { + $lists = $this->get_api()->get_lists(array( 'count' => 100, 'fields' => 'lists.id,lists.stats' )); + } catch (NL4WP_API_Exception $e) { + return array(); + } + + $list_counts = array(); + + // we got a valid response + foreach ($lists as $list) { + $list_counts["{$list->id}"] = $list->stats->member_count; + } + + + /** + * Filters the cache time for Newsletter lists configuration, in seconds. Defaults to 3600 seconds (1 hour). + * + * @since 2.0 + * @param int $seconds + */ + $transient_lifetime = (int) apply_filters('nl4wp_lists_count_cache_time', 3600); + + // make sure transient lifetime is not lower than 60 seconds + $transient_lifetime = max(60, $transient_lifetime); + set_transient('nl4wp_list_counts', $list_counts, $transient_lifetime); + + return $list_counts; + } + + + /** + * Returns number of subscribers on given lists. + * + * @param array|string $list_ids Array of list ID's, or single string. + * @return int Total # subscribers for given lists. + */ + public function get_subscriber_count($list_ids) + { + + // make sure we're getting an array + if (! is_array($list_ids)) { + $list_ids = array( $list_ids ); + } + + // if we got an empty array, return 0 + if (empty($list_ids)) { + return 0; + } + + // get total number of subscribers for all lists + $counts = $this->get_subscriber_counts(); + + // start calculating subscribers count for all given list ID's combined + $count = 0; + foreach ($list_ids as $id) { + $count += (isset($counts["{$id}"])) ? $counts["{$id}"] : 0; + } + + /** + * Filters the total subscriber_count for the given List ID's. + * + * @since 2.0 + * @param string $count + * @param array $list_ids + */ + return apply_filters('nl4wp_subscriber_count', $count, $list_ids); + } + + /** + * Resets error properties. + */ + public function reset_error() + { + $this->error_message = ''; + $this->error_code = ''; + } + + /** + * @return bool + */ + public function has_error() + { + return ! empty($this->error_code); + } + + /** + * @return string + */ + public function get_error_message() + { + return $this->error_message; + } + + /** + * @return string + */ + public function get_error_code() + { + return $this->error_code; + } + + /** + * @return NL4WP_API_v3 + */ + private function get_api() + { + return nl4wp('api'); + } } diff --git a/includes/class-plugin.php b/includes/class-plugin.php index 9678afe..67df8c8 100755 --- a/includes/class-plugin.php +++ b/includes/class-plugin.php @@ -8,70 +8,76 @@ * @access public * @ignore */ -class NL4WP_Plugin { +class NL4WP_Plugin +{ - /** - * @var string The plugin version. - */ - protected $version; + /** + * @var string The plugin version. + */ + protected $version; - /** - * @var string The main plugin file. - */ - protected $file; + /** + * @var string The main plugin file. + */ + protected $file; - /** - * @param string $file The plugin version. - * @param string $version The main plugin file. - */ - public function __construct( $file, $version ) { - $this->file = $file; - $this->version = $version; - } + /** + * @param string $file The plugin version. + * @param string $version The main plugin file. + */ + public function __construct($file, $version) + { + $this->file = $file; + $this->version = $version; + } - /** - * Get the main plugin file. - * - * @return string - */ - public function file() { - return $this->file; - } + /** + * Get the main plugin file. + * + * @return string + */ + public function file() + { + return $this->file; + } - /** - * Get the plugin version. - * - * @return string - */ - public function version() { - return $this->version; - } + /** + * Get the plugin version. + * + * @return string + */ + public function version() + { + return $this->version; + } - /** - * Gets the directory the plugin lives in. - * - * @param string $path - * - * @return string - */ - public function dir( $path = '' ) { + /** + * Gets the directory the plugin lives in. + * + * @param string $path + * + * @return string + */ + public function dir($path = '') + { - // ensure path has leading slash - if( '' !== $path ) { - $path = '/' . ltrim( $path, '/' ); - } + // ensure path has leading slash + if ('' !== $path) { + $path = '/' . ltrim($path, '/'); + } - return dirname( $this->file ) . $path; - } + return dirname($this->file) . $path; + } - /** - * Gets the URL to the plugin files. - * - * @param string $path - * - * @return string - */ - public function url( $path = '' ) { - return plugins_url( $path, $this->file ); - } -} \ No newline at end of file + /** + * Gets the URL to the plugin files. + * + * @param string $path + * + * @return string + */ + public function url($path = '') + { + return plugins_url($path, $this->file); + } +} diff --git a/includes/class-queue-job.php b/includes/class-queue-job.php index e422a8e..21084ba 100755 --- a/includes/class-queue-job.php +++ b/includes/class-queue-job.php @@ -5,25 +5,27 @@ * * @ignore */ -class NL4WP_Queue_Job { +class NL4WP_Queue_Job +{ - /** - * @var string - */ - public $id; + /** + * @var string + */ + public $id; - /** - * @var mixed - */ - public $data; + /** + * @var mixed + */ + public $data; - /** - * NL4WP_Queue_Job constructor. - * - * @param $data - */ - public function __construct( $data ) { - $this->id = (string) microtime( true ) . rand( 1, 10000 ); - $this->data = $data; - } -} \ No newline at end of file + /** + * NL4WP_Queue_Job constructor. + * + * @param $data + */ + public function __construct($data) + { + $this->id = (string) microtime(true) . rand(1, 10000); + $this->data = $data; + } +} diff --git a/includes/class-queue.php b/includes/class-queue.php index 9a31bd2..2d6eb23 100755 --- a/includes/class-queue.php +++ b/includes/class-queue.php @@ -5,7 +5,8 @@ * * @ignore */ -class NL4WP_Queue { +class NL4WP_Queue +{ /** * @var NL4WP_Queue_Job[] @@ -27,19 +28,21 @@ class NL4WP_Queue { * * @param string $option_name */ - public function __construct( $option_name ) { + public function __construct($option_name) + { $this->option_name = $option_name; - register_shutdown_function( array( $this, 'save' ) ); + register_shutdown_function(array( $this, 'save' )); } /** * Load jobs from option */ - protected function load() { - $jobs = get_option( $this->option_name, array() ); + protected function load() + { + $jobs = get_option($this->option_name, array()); - if( ! is_array( $jobs ) ) { + if (! is_array($jobs)) { $jobs = array(); } @@ -51,9 +54,9 @@ protected function load() { * * @return NL4WP_Queue_Job[] Array of jobs */ - public function all() { - - if( is_null( $this->jobs ) ) { + public function all() + { + if (is_null($this->jobs)) { $this->load(); } @@ -66,21 +69,21 @@ public function all() { * @param mixed $data * @return boolean */ - public function put( $data ) { - - if( is_null( $this->jobs ) ) { + public function put($data) + { + if (is_null($this->jobs)) { $this->load(); } // check if we already have a job with same data - foreach( $this->jobs as $job ) { - if( $job->data === $data ) { + foreach ($this->jobs as $job) { + if ($job->data === $data) { return false; } } // add job to queue - $job = new NL4WP_Queue_Job( $data ); + $job = new NL4WP_Queue_Job($data); $this->jobs[] = $job; $this->dirty = true; return true; @@ -91,36 +94,36 @@ public function put( $data ) { * * @return NL4WP_Queue_Job|false */ - public function get() { - - if( is_null( $this->jobs ) ) { + public function get() + { + if (is_null($this->jobs)) { $this->load(); } // do we have jobs? - if( count( $this->jobs ) === 0 ) { + if (count($this->jobs) === 0) { return false; } // return first element - return reset( $this->jobs ); + return reset($this->jobs); } /** * @param NL4WP_Queue_Job $job */ - public function delete( NL4WP_Queue_Job $job ) { - - if( is_null( $this->jobs ) ) { + public function delete(NL4WP_Queue_Job $job) + { + if (is_null($this->jobs)) { $this->load(); } - $index = array_search( $job, $this->jobs, true ); + $index = array_search($job, $this->jobs, true); // check for "false" here, as 0 is a valid index. - if( $index !== false ) { - unset( $this->jobs[ $index ] ); - $this->jobs = array_values( $this->jobs ); + if ($index !== false) { + unset($this->jobs[ $index ]); + $this->jobs = array_values($this->jobs); $this->dirty = true; } } @@ -128,13 +131,14 @@ public function delete( NL4WP_Queue_Job $job ) { /** * @param NL4WP_Queue_Job $job */ - public function reschedule( NL4WP_Queue_Job $job ) { - if( is_null( $this->jobs ) ) { + public function reschedule(NL4WP_Queue_Job $job) + { + if (is_null($this->jobs)) { $this->load(); } // delete job from start of queue - $this->delete( $job ); + $this->delete($job); // add job to end of queue $this->jobs[] = $job; @@ -144,7 +148,8 @@ public function reschedule( NL4WP_Queue_Job $job ) { /** * Reset queue */ - public function reset() { + public function reset() + { $this->jobs = array(); $this->dirty = true; } @@ -152,20 +157,18 @@ public function reset() { /** * Save the queue */ - public function save() { - - if( ! $this->dirty || is_null( $this->jobs ) ) { + public function save() + { + if (! $this->dirty || is_null($this->jobs)) { return false; } - $success = update_option( $this->option_name, $this->jobs, false ); + $success = update_option($this->option_name, $this->jobs, false); - if( $success ) { + if ($success) { $this->dirty = false; } return $success; } - - -} \ No newline at end of file +} diff --git a/includes/class-request.php b/includes/class-request.php index d696773..afcb6e9 100755 --- a/includes/class-request.php +++ b/includes/class-request.php @@ -7,116 +7,124 @@ * @ignore * @access private */ -class NL4WP_Request { - - /** - * @var NL4WP_Array_Bag - */ - public $params; - - /** - * @var NL4WP_Array_Bag - */ - public $get; - - /** - * @var NL4WP_Array_Bag - */ - public $post; - - /** - * @var NL4WP_Array_Bag - */ - public $server; - - - /** - * Create a new instance from `$_GET`, `$_POST` and `$_SERVER` superglobals. - * - * @return NL4WP_Request - */ - public static function create_from_globals() { - $get_data = is_array( $_GET ) ? $_GET : array(); - $get_data = nl4wp_sanitize_deep( $get_data ); - $get_data = stripslashes_deep( $get_data ); - - $post_data = is_array( $_POST ) ? $_POST : array(); - $post_data = nl4wp_sanitize_deep( $post_data ); - $post_data = stripslashes_deep( $post_data ); - - $server_data = is_array( $_SERVER ) ? $_SERVER : array(); - $server_data = nl4wp_sanitize_deep( $server_data ); - return new self( $get_data, $post_data, $server_data ); - } - - /** - * Constructor - * - * @param array $get - * @param array $post - * @param array $server - */ - public function __construct( $get = array(), $post = array(), $server = array() ) { - $this->get = new NL4WP_Array_Bag( $get ); - $this->post = new NL4WP_Array_Bag( $post ); - $this->params = new NL4WP_Array_Bag( array_merge( $post, $get ) ); - $this->server = new NL4WP_Array_Bag( $server ); - } - - /** - * @return bool - */ - public function is_ajax() { - return defined( 'DOING_AJAX' ) && DOING_AJAX; - } - - /** - * @return string - */ - public function get_method() { - return $this->server->get( 'REQUEST_METHOD' ); - } - - /** - * @param $method - * - * @return bool - */ - public function is_method( $method ) { - return $this->get_method() === $method; - } - - /** - * @return string - */ - public function get_url() { - return $this->server->get( 'REQUEST_URI' ); - } - - /** - * @return string - */ - public function get_referer() { - return $this->server->get( 'HTTP_REFERER', '' ); - } - - /** - * Get the IP address of the visitor. Takes proxies into account. - * - * @return string - */ - public function get_client_ip() { - $headers = ( function_exists( 'apache_request_headers' ) ) ? apache_request_headers() : $this->server->all(); - - if ( array_key_exists( 'X-Forwarded-For', $headers ) && filter_var( $headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) { - return $headers['X-Forwarded-For']; - } - - if ( array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) && filter_var( $headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) { - return $headers['HTTP_X_FORWARDED_FOR']; - } - - return $this->server->get( 'REMOTE_ADDR', '' ); - } - -} \ No newline at end of file +class NL4WP_Request +{ + + /** + * @var NL4WP_Array_Bag + */ + public $params; + + /** + * @var NL4WP_Array_Bag + */ + public $get; + + /** + * @var NL4WP_Array_Bag + */ + public $post; + + /** + * @var NL4WP_Array_Bag + */ + public $server; + + + /** + * Create a new instance from `$_GET`, `$_POST` and `$_SERVER` superglobals. + * + * @return NL4WP_Request + */ + public static function create_from_globals() + { + $get_data = is_array($_GET) ? $_GET : array(); + $get_data = nl4wp_sanitize_deep($get_data); + $get_data = stripslashes_deep($get_data); + + $post_data = is_array($_POST) ? $_POST : array(); + $post_data = nl4wp_sanitize_deep($post_data); + $post_data = stripslashes_deep($post_data); + + $server_data = is_array($_SERVER) ? $_SERVER : array(); + $server_data = nl4wp_sanitize_deep($server_data); + return new self($get_data, $post_data, $server_data); + } + + /** + * Constructor + * + * @param array $get + * @param array $post + * @param array $server + */ + public function __construct($get = array(), $post = array(), $server = array()) + { + $this->get = new NL4WP_Array_Bag($get); + $this->post = new NL4WP_Array_Bag($post); + $this->params = new NL4WP_Array_Bag(array_merge($post, $get)); + $this->server = new NL4WP_Array_Bag($server); + } + + /** + * @return bool + */ + public function is_ajax() + { + return defined('DOING_AJAX') && DOING_AJAX; + } + + /** + * @return string + */ + public function get_method() + { + return $this->server->get('REQUEST_METHOD'); + } + + /** + * @param $method + * + * @return bool + */ + public function is_method($method) + { + return $this->get_method() === $method; + } + + /** + * @return string + */ + public function get_url() + { + return $this->server->get('REQUEST_URI'); + } + + /** + * @return string + */ + public function get_referer() + { + return $this->server->get('HTTP_REFERER', ''); + } + + /** + * Get the IP address of the visitor. Takes proxies into account. + * + * @return string + */ + public function get_client_ip() + { + $headers = (function_exists('apache_request_headers')) ? apache_request_headers() : $this->server->all(); + + if (array_key_exists('X-Forwarded-For', $headers) && filter_var($headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + return $headers['X-Forwarded-For']; + } + + if (array_key_exists('HTTP_X_FORWARDED_FOR', $headers) && filter_var($headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + return $headers['HTTP_X_FORWARDED_FOR']; + } + + return $this->server->get('REMOTE_ADDR', ''); + } +} diff --git a/includes/class-tools.php b/includes/class-tools.php index 99634fa..7122142 100755 --- a/includes/class-tools.php +++ b/includes/class-tools.php @@ -6,283 +6,284 @@ * @access private * @ignore */ -class NL4WP_Tools { +class NL4WP_Tools +{ - /** + /** * @deprecated - * @param $datetime - * @param string $format - * - * @return bool|string - */ - public static function mysql_datetime_to_local_datetime( $datetime, $format = '' ) { + * @param $datetime + * @param string $format + * + * @return bool|string + */ + public static function mysql_datetime_to_local_datetime($datetime, $format = '') + { + if ($format === '') { + $format = get_option('date_format') . ' ' . get_option('time_format'); + } - if( $format === '' ) { - $format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' ); - } + // add or subtract GMT offset to given mysql time + $local_datetime = strtotime($datetime) + (get_option('gmt_offset') * HOUR_IN_SECONDS); - // add or subtract GMT offset to given mysql time - $local_datetime = strtotime( $datetime ) + ( get_option( 'gmt_offset') * HOUR_IN_SECONDS ); + return date($format, $local_datetime); + } - return date( $format, $local_datetime ); - } - - /** - * @return array - */ - public static function get_countries() { - return array( - 'AF' => 'Afghanistan', - 'AX' => 'Aland Islands', - 'AL' => 'Albania', - 'DZ' => 'Algeria', - 'AS' => 'American Samoa', - 'AD' => 'Andorra', - 'AO' => 'Angola', - 'AI' => 'Anguilla', - 'AQ' => 'Antarctica', - 'AG' => 'Antigua and Barbuda', - 'AR' => 'Argentina', - 'AM' => 'Armenia', - 'AW' => 'Aruba', - 'AU' => 'Australia', - 'AT' => 'Austria', - 'AZ' => 'Azerbaijan', - 'BS' => 'Bahamas', - 'BH' => 'Bahrain', - 'BD' => 'Bangladesh', - 'BB' => 'Barbados', - 'BY' => 'Belarus', - 'BE' => 'Belgium', - 'BZ' => 'Belize', - 'BJ' => 'Benin', - 'BM' => 'Bermuda', - 'BT' => 'Bhutan', - 'BO' => 'Bolivia', - 'BQ' => 'Bonaire, Saint Eustatius and Saba', - 'BA' => 'Bosnia and Herzegovina', - 'BW' => 'Botswana', - 'BV' => 'Bouvet Island', - 'BR' => 'Brazil', - 'IO' => 'British Indian Ocean Territory', - 'VG' => 'British Virgin Islands', - 'BN' => 'Brunei', - 'BG' => 'Bulgaria', - 'BF' => 'Burkina Faso', - 'BI' => 'Burundi', - 'KH' => 'Cambodia', - 'CM' => 'Cameroon', - 'CA' => 'Canada', - 'CV' => 'Cape Verde', - 'KY' => 'Cayman Islands', - 'CF' => 'Central African Republic', - 'TD' => 'Chad', - 'CL' => 'Chile', - 'CN' => 'China', - 'CX' => 'Christmas Island', - 'CC' => 'Cocos Islands', - 'CO' => 'Colombia', - 'KM' => 'Comoros', - 'CK' => 'Cook Islands', - 'CR' => 'Costa Rica', - 'HR' => 'Croatia', - 'CU' => 'Cuba', - 'CW' => 'Curacao', - 'CY' => 'Cyprus', - 'CZ' => 'Czech Republic', - 'CD' => 'Democratic Republic of the Congo', - 'DK' => 'Denmark', - 'DJ' => 'Djibouti', - 'DM' => 'Dominica', - 'DO' => 'Dominican Republic', - 'TL' => 'East Timor', - 'EC' => 'Ecuador', - 'EG' => 'Egypt', - 'SV' => 'El Salvador', - 'GQ' => 'Equatorial Guinea', - 'ER' => 'Eritrea', - 'EE' => 'Estonia', - 'ET' => 'Ethiopia', - 'FK' => 'Falkland Islands', - 'FO' => 'Faroe Islands', - 'FJ' => 'Fiji', - 'FI' => 'Finland', - 'FR' => 'France', - 'GF' => 'French Guiana', - 'PF' => 'French Polynesia', - 'TF' => 'French Southern Territories', - 'GA' => 'Gabon', - 'GM' => 'Gambia', - 'GE' => 'Georgia', - 'DE' => 'Germany', - 'GH' => 'Ghana', - 'GI' => 'Gibraltar', - 'GR' => 'Greece', - 'GL' => 'Greenland', - 'GD' => 'Grenada', - 'GP' => 'Guadeloupe', - 'GU' => 'Guam', - 'GT' => 'Guatemala', - 'GG' => 'Guernsey', - 'GN' => 'Guinea', - 'GW' => 'Guinea-Bissau', - 'GY' => 'Guyana', - 'HT' => 'Haiti', - 'HM' => 'Heard Island and McDonald Islands', - 'HN' => 'Honduras', - 'HK' => 'Hong Kong', - 'HU' => 'Hungary', - 'IS' => 'Iceland', - 'IN' => 'India', - 'ID' => 'Indonesia', - 'IR' => 'Iran', - 'IQ' => 'Iraq', - 'IE' => 'Ireland', - 'IM' => 'Isle of Man', - 'IL' => 'Israel', - 'IT' => 'Italy', - 'CI' => 'Ivory Coast', - 'JM' => 'Jamaica', - 'JP' => 'Japan', - 'JE' => 'Jersey', - 'JO' => 'Jordan', - 'KZ' => 'Kazakhstan', - 'KE' => 'Kenya', - 'KI' => 'Kiribati', - 'XK' => 'Kosovo', - 'KW' => 'Kuwait', - 'KG' => 'Kyrgyzstan', - 'LA' => 'Laos', - 'LV' => 'Latvia', - 'LB' => 'Lebanon', - 'LS' => 'Lesotho', - 'LR' => 'Liberia', - 'LY' => 'Libya', - 'LI' => 'Liechtenstein', - 'LT' => 'Lithuania', - 'LU' => 'Luxembourg', - 'MO' => 'Macao', - 'MK' => 'Macedonia', - 'MG' => 'Madagascar', - 'MW' => 'Malawi', - 'MY' => 'Malaysia', - 'MV' => 'Maldives', - 'ML' => 'Mali', - 'MT' => 'Malta', - 'MH' => 'Marshall Islands', - 'MQ' => 'Martinique', - 'MR' => 'Mauritania', - 'MU' => 'Mauritius', - 'YT' => 'Mayotte', - 'MX' => 'Mexico', - 'FM' => 'Micronesia', - 'MD' => 'Moldova', - 'MC' => 'Monaco', - 'MN' => 'Mongolia', - 'ME' => 'Montenegro', - 'MS' => 'Montserrat', - 'MA' => 'Morocco', - 'MZ' => 'Mozambique', - 'MM' => 'Myanmar', - 'NA' => 'Namibia', - 'NR' => 'Nauru', - 'NP' => 'Nepal', - 'NL' => 'Netherlands', - 'NC' => 'New Caledonia', - 'NZ' => 'New Zealand', - 'NI' => 'Nicaragua', - 'NE' => 'Niger', - 'NG' => 'Nigeria', - 'NU' => 'Niue', - 'NF' => 'Norfolk Island', - 'KP' => 'North Korea', - 'MP' => 'Northern Mariana Islands', - 'NO' => 'Norway', - 'OM' => 'Oman', - 'PK' => 'Pakistan', - 'PW' => 'Palau', - 'PS' => 'Palestinian Territory', - 'PA' => 'Panama', - 'PG' => 'Papua New Guinea', - 'PY' => 'Paraguay', - 'PE' => 'Peru', - 'PH' => 'Philippines', - 'PN' => 'Pitcairn', - 'PL' => 'Poland', - 'PT' => 'Portugal', - 'PR' => 'Puerto Rico', - 'QA' => 'Qatar', - 'CG' => 'Republic of the Congo', - 'RE' => 'Reunion', - 'RO' => 'Romania', - 'RU' => 'Russia', - 'RW' => 'Rwanda', - 'BL' => 'Saint Barthelemy', - 'SH' => 'Saint Helena', - 'KN' => 'Saint Kitts and Nevis', - 'LC' => 'Saint Lucia', - 'MF' => 'Saint Martin', - 'PM' => 'Saint Pierre and Miquelon', - 'VC' => 'Saint Vincent and the Grenadines', - 'WS' => 'Samoa', - 'SM' => 'San Marino', - 'ST' => 'Sao Tome and Principe', - 'SA' => 'Saudi Arabia', - 'SN' => 'Senegal', - 'RS' => 'Serbia', - 'SC' => 'Seychelles', - 'SL' => 'Sierra Leone', - 'SG' => 'Singapore', - 'SX' => 'Sint Maarten', - 'SK' => 'Slovakia', - 'SI' => 'Slovenia', - 'SB' => 'Solomon Islands', - 'SO' => 'Somalia', - 'ZA' => 'South Africa', - 'GS' => 'South Georgia and the South Sandwich Islands', - 'KR' => 'South Korea', - 'SS' => 'South Sudan', - 'ES' => 'Spain', - 'LK' => 'Sri Lanka', - 'SD' => 'Sudan', - 'SR' => 'Suriname', - 'SJ' => 'Svalbard and Jan Mayen', - 'SZ' => 'Swaziland', - 'SE' => 'Sweden', - 'CH' => 'Switzerland', - 'SY' => 'Syria', - 'TW' => 'Taiwan', - 'TJ' => 'Tajikistan', - 'TZ' => 'Tanzania', - 'TH' => 'Thailand', - 'TG' => 'Togo', - 'TK' => 'Tokelau', - 'TO' => 'Tonga', - 'TT' => 'Trinidad and Tobago', - 'TN' => 'Tunisia', - 'TR' => 'Turkey', - 'TM' => 'Turkmenistan', - 'TC' => 'Turks and Caicos Islands', - 'TV' => 'Tuvalu', - 'VI' => 'U.S. Virgin Islands', - 'UG' => 'Uganda', - 'UA' => 'Ukraine', - 'AE' => 'United Arab Emirates', - 'GB' => 'United Kingdom', - 'US' => 'United States', - 'UM' => 'United States Minor Outlying Islands', - 'UY' => 'Uruguay', - 'UZ' => 'Uzbekistan', - 'VU' => 'Vanuatu', - 'VA' => 'Vatican', - 'VE' => 'Venezuela', - 'VN' => 'Vietnam', - 'WF' => 'Wallis and Futuna', - 'EH' => 'Western Sahara', - 'YE' => 'Yemen', - 'ZM' => 'Zambia', - 'ZW' => 'Zimbabwe', - ); - } - -} \ No newline at end of file + /** + * @return array + */ + public static function get_countries() + { + return array( + 'AF' => 'Afghanistan', + 'AX' => 'Aland Islands', + 'AL' => 'Albania', + 'DZ' => 'Algeria', + 'AS' => 'American Samoa', + 'AD' => 'Andorra', + 'AO' => 'Angola', + 'AI' => 'Anguilla', + 'AQ' => 'Antarctica', + 'AG' => 'Antigua and Barbuda', + 'AR' => 'Argentina', + 'AM' => 'Armenia', + 'AW' => 'Aruba', + 'AU' => 'Australia', + 'AT' => 'Austria', + 'AZ' => 'Azerbaijan', + 'BS' => 'Bahamas', + 'BH' => 'Bahrain', + 'BD' => 'Bangladesh', + 'BB' => 'Barbados', + 'BY' => 'Belarus', + 'BE' => 'Belgium', + 'BZ' => 'Belize', + 'BJ' => 'Benin', + 'BM' => 'Bermuda', + 'BT' => 'Bhutan', + 'BO' => 'Bolivia', + 'BQ' => 'Bonaire, Saint Eustatius and Saba', + 'BA' => 'Bosnia and Herzegovina', + 'BW' => 'Botswana', + 'BV' => 'Bouvet Island', + 'BR' => 'Brazil', + 'IO' => 'British Indian Ocean Territory', + 'VG' => 'British Virgin Islands', + 'BN' => 'Brunei', + 'BG' => 'Bulgaria', + 'BF' => 'Burkina Faso', + 'BI' => 'Burundi', + 'KH' => 'Cambodia', + 'CM' => 'Cameroon', + 'CA' => 'Canada', + 'CV' => 'Cape Verde', + 'KY' => 'Cayman Islands', + 'CF' => 'Central African Republic', + 'TD' => 'Chad', + 'CL' => 'Chile', + 'CN' => 'China', + 'CX' => 'Christmas Island', + 'CC' => 'Cocos Islands', + 'CO' => 'Colombia', + 'KM' => 'Comoros', + 'CK' => 'Cook Islands', + 'CR' => 'Costa Rica', + 'HR' => 'Croatia', + 'CU' => 'Cuba', + 'CW' => 'Curacao', + 'CY' => 'Cyprus', + 'CZ' => 'Czech Republic', + 'CD' => 'Democratic Republic of the Congo', + 'DK' => 'Denmark', + 'DJ' => 'Djibouti', + 'DM' => 'Dominica', + 'DO' => 'Dominican Republic', + 'TL' => 'East Timor', + 'EC' => 'Ecuador', + 'EG' => 'Egypt', + 'SV' => 'El Salvador', + 'GQ' => 'Equatorial Guinea', + 'ER' => 'Eritrea', + 'EE' => 'Estonia', + 'ET' => 'Ethiopia', + 'FK' => 'Falkland Islands', + 'FO' => 'Faroe Islands', + 'FJ' => 'Fiji', + 'FI' => 'Finland', + 'FR' => 'France', + 'GF' => 'French Guiana', + 'PF' => 'French Polynesia', + 'TF' => 'French Southern Territories', + 'GA' => 'Gabon', + 'GM' => 'Gambia', + 'GE' => 'Georgia', + 'DE' => 'Germany', + 'GH' => 'Ghana', + 'GI' => 'Gibraltar', + 'GR' => 'Greece', + 'GL' => 'Greenland', + 'GD' => 'Grenada', + 'GP' => 'Guadeloupe', + 'GU' => 'Guam', + 'GT' => 'Guatemala', + 'GG' => 'Guernsey', + 'GN' => 'Guinea', + 'GW' => 'Guinea-Bissau', + 'GY' => 'Guyana', + 'HT' => 'Haiti', + 'HM' => 'Heard Island and McDonald Islands', + 'HN' => 'Honduras', + 'HK' => 'Hong Kong', + 'HU' => 'Hungary', + 'IS' => 'Iceland', + 'IN' => 'India', + 'ID' => 'Indonesia', + 'IR' => 'Iran', + 'IQ' => 'Iraq', + 'IE' => 'Ireland', + 'IM' => 'Isle of Man', + 'IL' => 'Israel', + 'IT' => 'Italy', + 'CI' => 'Ivory Coast', + 'JM' => 'Jamaica', + 'JP' => 'Japan', + 'JE' => 'Jersey', + 'JO' => 'Jordan', + 'KZ' => 'Kazakhstan', + 'KE' => 'Kenya', + 'KI' => 'Kiribati', + 'XK' => 'Kosovo', + 'KW' => 'Kuwait', + 'KG' => 'Kyrgyzstan', + 'LA' => 'Laos', + 'LV' => 'Latvia', + 'LB' => 'Lebanon', + 'LS' => 'Lesotho', + 'LR' => 'Liberia', + 'LY' => 'Libya', + 'LI' => 'Liechtenstein', + 'LT' => 'Lithuania', + 'LU' => 'Luxembourg', + 'MO' => 'Macao', + 'MK' => 'Macedonia', + 'MG' => 'Madagascar', + 'MW' => 'Malawi', + 'MY' => 'Malaysia', + 'MV' => 'Maldives', + 'ML' => 'Mali', + 'MT' => 'Malta', + 'MH' => 'Marshall Islands', + 'MQ' => 'Martinique', + 'MR' => 'Mauritania', + 'MU' => 'Mauritius', + 'YT' => 'Mayotte', + 'MX' => 'Mexico', + 'FM' => 'Micronesia', + 'MD' => 'Moldova', + 'MC' => 'Monaco', + 'MN' => 'Mongolia', + 'ME' => 'Montenegro', + 'MS' => 'Montserrat', + 'MA' => 'Morocco', + 'MZ' => 'Mozambique', + 'MM' => 'Myanmar', + 'NA' => 'Namibia', + 'NR' => 'Nauru', + 'NP' => 'Nepal', + 'NL' => 'Netherlands', + 'NC' => 'New Caledonia', + 'NZ' => 'New Zealand', + 'NI' => 'Nicaragua', + 'NE' => 'Niger', + 'NG' => 'Nigeria', + 'NU' => 'Niue', + 'NF' => 'Norfolk Island', + 'KP' => 'North Korea', + 'MP' => 'Northern Mariana Islands', + 'NO' => 'Norway', + 'OM' => 'Oman', + 'PK' => 'Pakistan', + 'PW' => 'Palau', + 'PS' => 'Palestinian Territory', + 'PA' => 'Panama', + 'PG' => 'Papua New Guinea', + 'PY' => 'Paraguay', + 'PE' => 'Peru', + 'PH' => 'Philippines', + 'PN' => 'Pitcairn', + 'PL' => 'Poland', + 'PT' => 'Portugal', + 'PR' => 'Puerto Rico', + 'QA' => 'Qatar', + 'CG' => 'Republic of the Congo', + 'RE' => 'Reunion', + 'RO' => 'Romania', + 'RU' => 'Russia', + 'RW' => 'Rwanda', + 'BL' => 'Saint Barthelemy', + 'SH' => 'Saint Helena', + 'KN' => 'Saint Kitts and Nevis', + 'LC' => 'Saint Lucia', + 'MF' => 'Saint Martin', + 'PM' => 'Saint Pierre and Miquelon', + 'VC' => 'Saint Vincent and the Grenadines', + 'WS' => 'Samoa', + 'SM' => 'San Marino', + 'ST' => 'Sao Tome and Principe', + 'SA' => 'Saudi Arabia', + 'SN' => 'Senegal', + 'RS' => 'Serbia', + 'SC' => 'Seychelles', + 'SL' => 'Sierra Leone', + 'SG' => 'Singapore', + 'SX' => 'Sint Maarten', + 'SK' => 'Slovakia', + 'SI' => 'Slovenia', + 'SB' => 'Solomon Islands', + 'SO' => 'Somalia', + 'ZA' => 'South Africa', + 'GS' => 'South Georgia and the South Sandwich Islands', + 'KR' => 'South Korea', + 'SS' => 'South Sudan', + 'ES' => 'Spain', + 'LK' => 'Sri Lanka', + 'SD' => 'Sudan', + 'SR' => 'Suriname', + 'SJ' => 'Svalbard and Jan Mayen', + 'SZ' => 'Swaziland', + 'SE' => 'Sweden', + 'CH' => 'Switzerland', + 'SY' => 'Syria', + 'TW' => 'Taiwan', + 'TJ' => 'Tajikistan', + 'TZ' => 'Tanzania', + 'TH' => 'Thailand', + 'TG' => 'Togo', + 'TK' => 'Tokelau', + 'TO' => 'Tonga', + 'TT' => 'Trinidad and Tobago', + 'TN' => 'Tunisia', + 'TR' => 'Turkey', + 'TM' => 'Turkmenistan', + 'TC' => 'Turks and Caicos Islands', + 'TV' => 'Tuvalu', + 'VI' => 'U.S. Virgin Islands', + 'UG' => 'Uganda', + 'UA' => 'Ukraine', + 'AE' => 'United Arab Emirates', + 'GB' => 'United Kingdom', + 'US' => 'United States', + 'UM' => 'United States Minor Outlying Islands', + 'UY' => 'Uruguay', + 'UZ' => 'Uzbekistan', + 'VU' => 'Vanuatu', + 'VA' => 'Vatican', + 'VE' => 'Venezuela', + 'VN' => 'Vietnam', + 'WF' => 'Wallis and Futuna', + 'EH' => 'Western Sahara', + 'YE' => 'Yemen', + 'ZM' => 'Zambia', + 'ZW' => 'Zimbabwe', + ); + } +} diff --git a/includes/default-actions.php b/includes/default-actions.php index 0d11a88..b0b9159 100755 --- a/includes/default-actions.php +++ b/includes/default-actions.php @@ -1,5 +1,5 @@ output_checkbox(); +function nl4wp_checkbox() +{ + _deprecated_function(__FUNCTION__, 'Newsletter for WordPress v3.0'); + nl4wp_get_integration('wp-comment-form')->output_checkbox(); } /** @@ -41,9 +43,10 @@ function nl4wp_checkbox() { * @return string * */ -function nl4wp_form( $id = 0, $attributes = array() ) { - _deprecated_function( __FUNCTION__, 'Newsletter for WordPress v3.0', 'nl4wp_show_form' ); - return nl4wp_show_form( $id, $attributes ); +function nl4wp_form($id = 0, $attributes = array()) +{ + _deprecated_function(__FUNCTION__, 'Newsletter for WordPress v3.0', 'nl4wp_show_form'); + return nl4wp_show_form($id, $attributes); } /** @@ -52,5 +55,5 @@ function nl4wp_form( $id = 0, $attributes = array() ) { */ function nl4wp_get_current_url() { - return $nl4wp_get_current_url(); + return $nl4wp_get_current_url(); } diff --git a/includes/forms/admin-functions.php b/includes/forms/admin-functions.php index 116870b..d49d8fe 100755 --- a/includes/forms/admin-functions.php +++ b/includes/forms/admin-functions.php @@ -8,14 +8,15 @@ * * @return string */ -function nl4wp_get_edit_form_url( $form_id, $tab = '' ) { - $url = admin_url( sprintf( 'admin.php?page=newsletter-for-wp-forms&view=edit-form&form_id=%d', $form_id ) ); +function nl4wp_get_edit_form_url($form_id, $tab = '') +{ + $url = admin_url(sprintf('admin.php?page=newsletter-for-wp-forms&view=edit-form&form_id=%d', $form_id)); - if( ! empty( $tab ) ) { - $url .= sprintf( '&tab=%s', $tab ); - } + if (! empty($tab)) { + $url .= sprintf('&tab=%s', $tab); + } - return $url; + return $url; } /** @@ -23,9 +24,10 @@ function nl4wp_get_edit_form_url( $form_id, $tab = '' ) { * * @return string */ -function nl4wp_get_add_form_url() { - $url = admin_url( 'admin.php?page=newsletter-for-wp-forms&view=add-form' ); - return $url; +function nl4wp_get_add_form_url() +{ + $url = admin_url('admin.php?page=newsletter-for-wp-forms&view=add-form'); + return $url; } /** @@ -62,4 +64,4 @@ function nl4wp_get_add_form_url() { // echo ''; // // return ''; -//} \ No newline at end of file +//} diff --git a/includes/forms/class-admin.php b/includes/forms/class-admin.php index bcb5b5c..f0a01c9 100755 --- a/includes/forms/class-admin.php +++ b/includes/forms/class-admin.php @@ -6,448 +6,473 @@ * @ignore * @access private */ -class NL4WP_Forms_Admin { - - /** - * @var NL4WP_Admin_Messages - */ - protected $messages; - - /** - * @var NL4WP_Newsletter - */ - protected $newsletter; - - /** - * @param NL4WP_Admin_Messages $messages - * @param NL4WP_Newsletter $newsletter - */ - public function __construct( NL4WP_Admin_Messages $messages, NL4WP_Newsletter $newsletter ) { - $this->messages = $messages; - $this->newsletter = $newsletter; - } - - /** - * Add hooks - */ - public function add_hooks() { - add_action( 'register_shortcode_ui', array( $this, 'register_shortcake_ui' ) ); - add_action( 'nl4wp_save_form', array( $this, 'update_form_stylesheets' ) ); - add_action( 'nl4wp_admin_edit_form', array( $this, 'process_save_form' ) ); - add_action( 'nl4wp_admin_add_form', array( $this, 'process_add_form' ) ); - add_filter( 'nl4wp_admin_menu_items', array( $this, 'add_menu_item' ), 5 ); - add_action( 'nl4wp_admin_show_forms_page-edit-form', array( $this, 'show_edit_page' ) ); - add_action( 'nl4wp_admin_show_forms_page-add-form', array( $this, 'show_add_page' ) ); - add_action( 'nl4wp_admin_enqueue_assets', array( $this, 'enqueue_assets' ), 10, 2 ); - } - - /** - * @param string $suffix - * @param string $page - */ - public function enqueue_assets( $suffix, $page = '' ) { - - if( $page !== 'forms' || empty( $_GET['view'] ) || $_GET['view'] !== 'edit-form' ) { - return; - } - - wp_register_script( 'nl4wp-forms-admin', NL4WP_PLUGIN_URL . 'assets/js/forms-admin' . $suffix . '.js', array( 'nl4wp-admin' ), NL4WP_VERSION, true ); - wp_enqueue_script( 'nl4wp-forms-admin'); - wp_localize_script( 'nl4wp-forms-admin', 'nl4wp_forms_i18n', array( - 'addToForm' => __( "Add to form", 'newsletter-for-wp' ), - 'agreeToTerms' => __( "I have read and agree to the terms & conditions", 'newsletter-for-wp' ), - 'agreeToTermsShort' => __( "Agree to terms", 'newsletter-for-wp' ), - 'agreeToTermsLink' => __( 'Link to your terms & conditions page', 'newsletter-for-wp' ), - 'city' => __( 'City', 'newsletter-for-wp' ), - 'checkboxes' => __( 'Checkboxes', 'newsletter-for-wp' ), - 'choices' => __( 'Choices', 'newsletter-for-wp' ), - 'choiceType' => __( "Choice type", 'newsletter-for-wp' ), - 'chooseField' => __( "Choose a field to add to the form", 'newsletter-for-wp' ), - 'close' => __( 'Close', 'newsletter-for-wp' ), - 'country' => __( 'Country', 'newsletter-for-wp' ), - 'dropdown' => __( 'Dropdown', 'newsletter-for-wp' ), - 'fieldType' => __( 'Field type', 'newsletter-for-wp' ), - 'fieldLabel' => __( "Field label", 'newsletter-for-wp' ), - 'formAction' => __( 'Form action', 'newsletter-for-wp' ), - 'formActionDescription' => __( 'This field will allow your visitors to choose whether they would like to subscribe or unsubscribe', 'newsletter-for-wp' ), - 'formFields' => __( 'Form fields', 'newsletter-for-wp' ), - 'forceRequired' => __( 'This field is marked as required in Newsletter.', 'newsletter-for-wp' ), - 'initialValue' => __( "Initial value", 'newsletter-for-wp' ), - 'interestCategories' => __( 'Interest categories', 'newsletter-for-wp' ), - 'isFieldRequired' => __( "Is this field required?", 'newsletter-for-wp' ), - 'listChoice' => __( 'List choice', 'newsletter-for-wp' ), - 'listChoiceDescription' => __( 'This field will allow your visitors to choose a list to subscribe to.', 'newsletter-for-wp' ), - 'listFields' => __( 'List fields', 'newsletter-for-wp' ), - 'min' => __( 'Min', 'newsletter-for-wp' ), - 'max' => __( 'Max', 'newsletter-for-wp' ), - 'noAvailableFields' => __( 'No available fields. Did you select a Newsletter list in the form settings?', 'newsletter-for-wp' ), - 'optional' => __( 'Optional', 'newsletter-for-wp' ), - 'placeholder' => __( 'Placeholder', 'newsletter-for-wp' ), - 'placeholderHelp' => __( "Text to show when field has no value.", 'newsletter-for-wp' ), - 'preselect' => __( 'Preselect', 'newsletter-for-wp' ), - 'remove' => __( 'Remove', 'newsletter-for-wp' ), - 'radioButtons' => __( 'Radio buttons', 'newsletter-for-wp' ), - 'streetAddress' => __( 'Street Address', 'newsletter-for-wp' ), - 'state' => __( 'State', 'newsletter-for-wp' ), - 'subscribe' => __( 'Subscribe', 'newsletter-for-wp' ), - 'submitButton' => __( 'Submit button', 'newsletter-for-wp' ), - 'wrapInParagraphTags' => __( "Wrap in paragraph tags?", 'newsletter-for-wp' ), - 'value' => __( "Value", 'newsletter-for-wp' ), - 'valueHelp' => __( "Text to prefill this field with.", 'newsletter-for-wp' ), - 'zip' => __( 'ZIP', 'newsletter-for-wp' ), - )); - } - - /** - * @param $items - * - * @return mixed - */ - public function add_menu_item( $items ) { - - $items['forms'] = array( - 'title' => __( 'Forms', 'newsletter-for-wp' ), - 'text' => __( 'Form', 'newsletter-for-wp' ), - 'slug' => 'forms', - 'callback' => array( $this, 'show_forms_page' ), - 'load_callback' => array( $this, 'redirect_to_form_action' ), - 'position' => 10 - ); - - return $items; - } - - /** - * Act on the "add form" form - */ - public function process_add_form() { - - check_admin_referer( 'add_form', '_nl4wp_nonce' ); - - $form_data = $_POST['nl4wp_form']; - $form_content = include NL4WP_PLUGIN_DIR . 'config/default-form-content.php'; - - // Fix for MultiSite stripping KSES for roles other than administrator - remove_all_filters( 'content_save_pre' ); - - $form_id = wp_insert_post( - array( - 'post_type' => 'nl4wp-form', - 'post_status' => 'publish', - 'post_title' => $form_data['name'], - 'post_content' => $form_content, - ) - ); +class NL4WP_Forms_Admin +{ + + /** + * @var NL4WP_Admin_Messages + */ + protected $messages; + + /** + * @var NL4WP_Newsletter + */ + protected $newsletter; + + /** + * @param NL4WP_Admin_Messages $messages + * @param NL4WP_Newsletter $newsletter + */ + public function __construct(NL4WP_Admin_Messages $messages, NL4WP_Newsletter $newsletter) + { + $this->messages = $messages; + $this->newsletter = $newsletter; + } + + /** + * Add hooks + */ + public function add_hooks() + { + add_action('register_shortcode_ui', array( $this, 'register_shortcake_ui' )); + add_action('nl4wp_save_form', array( $this, 'update_form_stylesheets' )); + add_action('nl4wp_admin_edit_form', array( $this, 'process_save_form' )); + add_action('nl4wp_admin_add_form', array( $this, 'process_add_form' )); + add_filter('nl4wp_admin_menu_items', array( $this, 'add_menu_item' ), 5); + add_action('nl4wp_admin_show_forms_page-edit-form', array( $this, 'show_edit_page' )); + add_action('nl4wp_admin_show_forms_page-add-form', array( $this, 'show_add_page' )); + add_action('nl4wp_admin_enqueue_assets', array( $this, 'enqueue_assets' ), 10, 2); + + add_action('enqueue_block_editor_assets', array($this, 'enqueue_gutenberg_assets')); + } + + + public function enqueue_gutenberg_assets() + { + wp_enqueue_script('nl4wp-form-block', NL4WP_PLUGIN_URL . 'assets/js/forms-block.js', array('wp-blocks', 'wp-i18n', 'wp-element', 'wp-components')); + + $forms = nl4wp_get_forms(); + $data = array(); + foreach ($forms as $form) { + $data[] = array( 'name' => $form->name, 'id' => $form->ID ); + } + wp_localize_script('nl4wp-form-block', 'nl4wp_forms', $data ); + } + + /** + * @param string $suffix + * @param string $page + */ + public function enqueue_assets($suffix, $page = '') + { + if ($page !== 'forms' || empty($_GET['view']) || $_GET['view'] !== 'edit-form') { + return; + } + + wp_register_script('nl4wp-forms-admin', NL4WP_PLUGIN_URL . 'assets/js/forms-admin' . $suffix . '.js', array( 'nl4wp-admin' ), NL4WP_VERSION, true); + wp_enqueue_script('nl4wp-forms-admin'); + wp_localize_script('nl4wp-forms-admin', 'nl4wp_forms_i18n', array( + 'addToForm' => __("Add to form", 'newsletter-for-wp'), + 'agreeToTerms' => __("I have read and agree to the terms & conditions", 'newsletter-for-wp'), + 'agreeToTermsShort' => __("Agree to terms", 'newsletter-for-wp'), + 'agreeToTermsLink' => __('Link to your terms & conditions page', 'newsletter-for-wp'), + 'city' => __('City', 'newsletter-for-wp'), + 'checkboxes' => __('Checkboxes', 'newsletter-for-wp'), + 'choices' => __('Choices', 'newsletter-for-wp'), + 'choiceType' => __("Choice type", 'newsletter-for-wp'), + 'chooseField' => __("Choose a field to add to the form", 'newsletter-for-wp'), + 'close' => __('Close', 'newsletter-for-wp'), + 'country' => __('Country', 'newsletter-for-wp'), + 'dropdown' => __('Dropdown', 'newsletter-for-wp'), + 'fieldType' => __('Field type', 'newsletter-for-wp'), + 'fieldLabel' => __("Field label", 'newsletter-for-wp'), + 'formAction' => __('Form action', 'newsletter-for-wp'), + 'formActionDescription' => __('This field will allow your visitors to choose whether they would like to subscribe or unsubscribe', 'newsletter-for-wp'), + 'formFields' => __('Form fields', 'newsletter-for-wp'), + 'forceRequired' => __('This field is marked as required in Newsletter.', 'newsletter-for-wp'), + 'initialValue' => __("Initial value", 'newsletter-for-wp'), + 'interestCategories' => __('Interest categories', 'newsletter-for-wp'), + 'isFieldRequired' => __("Is this field required?", 'newsletter-for-wp'), + 'listChoice' => __('List choice', 'newsletter-for-wp'), + 'listChoiceDescription' => __('This field will allow your visitors to choose a list to subscribe to.', 'newsletter-for-wp'), + 'listFields' => __('List fields', 'newsletter-for-wp'), + 'min' => __('Min', 'newsletter-for-wp'), + 'max' => __('Max', 'newsletter-for-wp'), + 'noAvailableFields' => __('No available fields. Did you select a Newsletter list in the form settings?', 'newsletter-for-wp'), + 'optional' => __('Optional', 'newsletter-for-wp'), + 'placeholder' => __('Placeholder', 'newsletter-for-wp'), + 'placeholderHelp' => __("Text to show when field has no value.", 'newsletter-for-wp'), + 'preselect' => __('Preselect', 'newsletter-for-wp'), + 'remove' => __('Remove', 'newsletter-for-wp'), + 'radioButtons' => __('Radio buttons', 'newsletter-for-wp'), + 'streetAddress' => __('Street Address', 'newsletter-for-wp'), + 'state' => __('State', 'newsletter-for-wp'), + 'subscribe' => __('Subscribe', 'newsletter-for-wp'), + 'submitButton' => __('Submit button', 'newsletter-for-wp'), + 'wrapInParagraphTags' => __("Wrap in paragraph tags?", 'newsletter-for-wp'), + 'value' => __("Value", 'newsletter-for-wp'), + 'valueHelp' => __("Text to prefill this field with.", 'newsletter-for-wp'), + 'zip' => __('ZIP', 'newsletter-for-wp'), + )); + } + + /** + * @param $items + * + * @return mixed + */ + public function add_menu_item($items) + { + $items['forms'] = array( + 'title' => __('Forms', 'newsletter-for-wp'), + 'text' => __('Form', 'newsletter-for-wp'), + 'slug' => 'forms', + 'callback' => array( $this, 'show_forms_page' ), + 'load_callback' => array( $this, 'redirect_to_form_action' ), + 'position' => 10 + ); + + return $items; + } + + /** + * Act on the "add form" form + */ + public function process_add_form() + { + check_admin_referer('add_form', '_nl4wp_nonce'); + + $form_data = $_POST['nl4wp_form']; + $form_content = include NL4WP_PLUGIN_DIR . 'config/default-form-content.php'; + + // Fix for MultiSite stripping KSES for roles other than administrator + remove_all_filters('content_save_pre'); + + $form_id = wp_insert_post( + array( + 'post_type' => 'nl4wp-form', + 'post_status' => 'publish', + 'post_title' => $form_data['name'], + 'post_content' => $form_content, + ) + ); // if settings were passed, save those too. - if( isset( $form_data['settings'] ) ) { - update_post_meta( $form_id, '_nl4wp_settings', $form_data['settings'] ); + if (isset($form_data['settings'])) { + update_post_meta($form_id, '_nl4wp_settings', $form_data['settings']); } // set default form ID - $this->set_default_form_id( $form_id ); - - $this->messages->flash( __( "Success! Form successfully saved.", 'newsletter-for-wp' ) ); - wp_redirect( nl4wp_get_edit_form_url( $form_id ) ); - exit; - } - - /** - * Saves a form to the database - * - * @param array $data - * @return int - */ - public function save_form( $data ) { - $keys = array( - 'settings' => array(), - 'messages' => array(), - 'name' => '', - 'content' => '' - ); - - $data = array_merge( $keys, $data ); - $data = $this->sanitize_form_data( $data ); - - $post_data = array( - 'post_type' => 'nl4wp-form', - 'post_status' => ! empty( $data['status'] ) ? $data['status'] : 'publish', - 'post_title' => $data['name'], - 'post_content' => $data['content'] - ); - - // if an `ID` is given, make sure post is of type `nl4wp-form` - if( ! empty( $data['ID'] ) ) { - $post = get_post( $data['ID'] ); - - if( $post instanceof WP_Post && $post->post_type === 'nl4wp-form' ) { - $post_data['ID'] = $data['ID']; - - // merge new settings with current settings to allow passing partial data - $current_settings = get_post_meta( $post->ID, '_nl4wp_settings', true ); - if( is_array( $current_settings ) ) { - $data['settings'] = array_merge( $current_settings, $data['settings'] ); - } - } - } - - // Fix for MultiSite stripping KSES for roles other than administrator - remove_all_filters( 'content_save_pre' ); - - $form_id = wp_insert_post( $post_data ); - update_post_meta( $form_id, '_nl4wp_settings', $data['settings'] ); - - // save form messages in individual meta keys - foreach( $data['messages'] as $key => $message ) { - update_post_meta( $form_id, 'text_' . $key, $message ); - } - - /** - * Runs right after a form is updated. - * - * @since 3.0 - * - * @param int $form_id - */ - do_action( 'nl4wp_save_form', $form_id ); - - return $form_id; - } - - /** - * @param array $data - * @return array - */ - public function sanitize_form_data( $data ) { - - $raw_data = $data; - - // strip
tags from content - $data['content'] = preg_replace( '/<\/?form(.|\s)*?>/i', '', $data['content'] ); - - // replace lowercased name="name" to prevent 404 - $data['content'] = str_ireplace( ' name=\"name\"', ' name=\"NAME\"', $data['content'] ); - - // sanitize text fields - $data['settings']['redirect'] = sanitize_text_field( $data['settings']['redirect'] ); - - // strip tags from messages - foreach( $data['messages'] as $key => $message ) { - $data['messages'][$key] = strip_tags( $message, '
'; - } - - /** - * Outputs the inline JavaScript that is used to enhance forms - */ - public function load_scripts() { - - $load_scripts = $this->load_scripts; - - /** @ignore */ - $load_scripts = apply_filters( 'nl4wp_load_form_scripts', $load_scripts ); - if( ! $load_scripts ) { - return; - } - - global $wp_scripts; - - // make sure scripts are loaded - wp_enqueue_script( 'nl4wp-forms-api', NL4WP_PLUGIN_URL . 'assets/js/forms-api'. $this->filename_suffix .'.js', array(), NL4WP_VERSION, true ); - wp_localize_script( 'nl4wp-forms-api', 'nl4wp_forms_config', $this->get_javascript_config() ); - - // load placeholder polyfill if browser is Internet Explorer - wp_enqueue_script( 'nl4wp-forms-placeholders', NL4WP_PLUGIN_URL . 'assets/js/third-party/placeholders.min.js', array(), NL4WP_VERSION, true ); - $wp_scripts->add_data( 'nl4wp-forms-placeholders', 'conditional', 'lte IE 9' ); - - // print inline scripts depending on printed fields - echo ''; - - /** @ignore */ - do_action( 'nl4wp_load_form_scripts' ); - } - - - - +class NL4WP_Form_Asset_Manager +{ + + /** + * @var bool + */ + protected $load_scripts = false; + + /** + * @var string + */ + protected $filename_suffix = ''; + + /** + * NL4WP_Form_Asset_Manager constructor. + */ + public function __construct() + { + $this->filename_suffix =(defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? '' : '.min'; + } + + /** + * Add hooks + */ + public function hook() + { + // load checkbox css if necessary + add_action('wp_enqueue_scripts', array( $this, 'load_stylesheets' )); + add_action('nl4wp_output_form', array( $this, 'before_output_form' )); + add_action('wp_footer', array( $this, 'load_scripts' )); + + $this->register_assets(); + } + + /** + * Register the various JS files used by the plugin + */ + public function register_assets() + { + $suffix = $this->filename_suffix; + + wp_register_script('nl4wp-forms-api', NL4WP_PLUGIN_URL . 'assets/js/forms-api'. $this->filename_suffix .'.js', array(), NL4WP_VERSION, true); + + /** + * Runs right after all assets (scripts & stylesheets) for forms have been registered + * + * @since 3.0 + * @deprecated 3.1.9 + * + * @param string $suffix The suffix to add to the filename, before the file extension. Is usually set to ".min". + * @ignore + */ + do_action('nl4wp_register_form_assets', $suffix); + } + + + /** + * @param string $stylesheet + * + * @return bool + */ + public function is_registered_stylesheet($stylesheet) + { + $stylesheets = $this->get_registered_stylesheets(); + return in_array($stylesheet, $stylesheets); + } + + /** + * @return array + */ + public function get_registered_stylesheets() + { + return array( + 'basic', + 'themes' + ); + } + + /** + * @param string $stylesheet + * + * @return string + */ + public function get_stylesheet_url($stylesheet) + { + if (! $this->is_registered_stylesheet($stylesheet)) { + return ''; + } + + $suffix = $this->filename_suffix; + return NL4WP_PLUGIN_URL . 'assets/css/form-' . $stylesheet . $suffix . '.css'; + } + + /** + * Get array of stylesheet handles which should be enqueued. + * + * @return array + */ + public function get_active_stylesheets() + { + $stylesheets = (array) get_option('nl4wp_form_stylesheets', array()); + + /** + * Filters the stylesheets to be loaded + * + * Should be an array of stylesheet handles previously registered using `wp_register_style`. + * Each value is prefixed with `nl4wp-form-` to get the handle. + * + * Return an empty array if you want to disable the loading of all stylesheets. + * + * @since 3.0 + * @param array $stylesheets Array of valid stylesheet handles + */ + $stylesheets = (array) apply_filters('nl4wp_form_stylesheets', $stylesheets); + return $stylesheets; + } + + /** + * Load the various stylesheets + */ + public function load_stylesheets() + { + $stylesheets = $this->get_active_stylesheets(); + + foreach ($stylesheets as $stylesheet) { + if (! $this->is_registered_stylesheet($stylesheet)) { + continue; + } + + $handle = 'nl4wp-form-' . $stylesheet; + wp_enqueue_style($handle, $this->get_stylesheet_url($stylesheet), array(), NL4WP_VERSION); + add_editor_style($this->get_stylesheet_url($stylesheet)); + } + + /** + * @ignore + */ + do_action('nl4wp_load_form_stylesheets', $stylesheets); + + return true; + } + + /** + * Get configuration object for client-side use. + * + * @return array + */ + public function get_javascript_config() + { + $submitted_form = nl4wp_get_submitted_form(); + if (! $submitted_form) { + return array(); + } + + $config = array( + 'submitted_form' => array( + 'id' => $submitted_form->ID, + 'event' => $submitted_form->last_event, + 'data' => $submitted_form->get_data(), + 'element_id' => $submitted_form->config['element_id'], + ) + ); + + if ($submitted_form->has_errors()) { + $config['submitted_form']['errors'] = $submitted_form->errors; + } + + $auto_scroll = 'default'; + + /** + * Filters the `auto_scroll` setting for when a form is submitted. + * + * Accepts the following values: + * + * - false + * - "default" + * - "animated" + * + * @param boolean|string $auto_scroll + * @since 3.0 + */ + $config['auto_scroll'] = apply_filters('nl4wp_form_auto_scroll', $auto_scroll); + + return $config; + } + + /** + * Load JavaScript files + */ + public function before_output_form() + { + // print dummy JS + $this->print_dummy_javascript(); + + // set flags + $this->load_scripts = true; + } + + /** + * Prints dummy JavaScript which allows people to call `nl4wp.forms.on()` before the JS is loaded. + */ + public function print_dummy_javascript() + { + $file = dirname(__FILE__) . '/views/js/dummy-api.js'; + echo ''; + } + + /** + * Outputs the inline JavaScript that is used to enhance forms + */ + public function load_scripts() + { + $load_scripts = $this->load_scripts; + + /** @ignore */ + $load_scripts = apply_filters('nl4wp_load_form_scripts', $load_scripts); + if (! $load_scripts) { + return; + } + + global $wp_scripts; + + // make sure scripts are loaded + wp_enqueue_script('nl4wp-forms-api'); + wp_localize_script('nl4wp-forms-api', 'nl4wp_forms_config', $this->get_javascript_config()); + + // load placeholder polyfill if browser is Internet Explorer + wp_enqueue_script('nl4wp-forms-placeholders', NL4WP_PLUGIN_URL . 'assets/js/third-party/placeholders.min.js', array(), NL4WP_VERSION, true); + $wp_scripts->add_data('nl4wp-forms-placeholders', 'conditional', 'lte IE 9'); + + // print inline scripts depending on printed fields + echo ''; + + /** @ignore */ + do_action('nl4wp_load_form_scripts'); + } } diff --git a/includes/forms/class-form-element.php b/includes/forms/class-form-element.php index 78a60c4..90561e3 100755 --- a/includes/forms/class-form-element.php +++ b/includes/forms/class-form-element.php @@ -7,363 +7,366 @@ * @ignore * @access private */ -class NL4WP_Form_Element { - - /** - * @var string - */ - public $ID; - - /** - * @var NL4WP_Form - */ - public $form; - - /** - * @var array - * - * Can be used to set element-specific config settings. Accepts the following keys. - * - * - lists: Customized number of Newsletter list ID's to subscribe to. - * - email_type: The email type - */ - public $config = array(); - - /** - * @var bool - */ - public $is_submitted = false; - - /** - * @param NL4WP_Form $form - * @param string $ID - * @param $config array - */ - public function __construct( NL4WP_Form $form, $ID, $config = array() ) { - $this->form = $form; - $this->ID = $ID; - $this->config = $config; - - $this->is_submitted = $this->form->is_submitted - && $this->form->config['element_id'] == $this->ID; - } - - - /** - * @return string - */ - protected function get_visible_fields() { - - $content = $this->form->content; - $form = $this->form; - $element = $this; - - /** - * Filters the HTML for the form fields. - * - * Use this filter to add custom HTML to a form programmatically - * - * @param string $content - * @param NL4WP_Form $form - * @param NL4WP_Form_Element $element - * @since 2.0 - */ - $visible_fields = (string) apply_filters( 'nl4wp_form_content', $content, $form, $element ); - - return $visible_fields; - } - - /** - * @return string - */ - protected function get_hidden_fields() { - - // hidden fields - $hidden_fields = ''; - $hidden_fields .= ''; - $hidden_fields .= ''; - $hidden_fields .= ''; - - // was "lists" parameter passed in shortcode arguments? - if( ! empty( $this->config['lists'] ) ) { - $lists_string = is_array( $this->config['lists'] ) ? join( ',', $this->config['lists'] ) : $this->config['lists']; - $hidden_fields .= ''; - } - - // was "lists" parameter passed in shortcode arguments? - if( ! empty( $this->config['email_type'] ) ) { - $hidden_fields .= ''; - } - - return (string) $hidden_fields; - } - - /** - * Get HTML string for a notice, including wrapper element. - * - * @param NL4WP_Form_Notice $notice - * - * @return string - */ - protected function get_notice_html( NL4WP_Form_Notice $notice ) { - $html = sprintf( '

%s

', esc_attr( $notice->type ), $notice->text ); - return $html; - } - - /** - * Gets the form response string - * - * @param boolean $force_show - * @return string - */ - public function get_response_html( $force_show = false ) { - - $html = ''; - $form = $this->form; - - if( $this->is_submitted || $force_show ) { - foreach( $this->form->notices as $notice ) { - $html .= $this->get_notice_html( $notice ); - } - } - - /** - * Filter the form response HTML - * - * Use this to add your own HTML to the form response. The form instance is passed to the callback function. - * - * @since 3.0 - * - * @param string $html The complete HTML string of the response, excluding the wrapper element. - * @param NL4WP_Form $form The form object - */ - $html = (string) apply_filters( 'nl4wp_form_response_html', $html, $form ); - - // wrap entire response in div, regardless of a form was submitted - $html = '
' . $html . '
'; - return $html; - } - - /** - * @return string - */ - protected function get_response_position() { - - $position = 'after'; - $form = $this->form; - - // check if content contains {response} tag - if( stripos( $this->form->content, '{response}' ) !== false ) { - return ''; - } - - /** - * Filters the position for the form response. - * - * Valid values are "before" and "after". Will have no effect if `{response}` is used in the form content. - * - * @param string $position - * @param NL4WP_Form $form - * @since 2.0 - */ - $response_position = (string) apply_filters( 'nl4wp_form_response_position', $position, $form ); - - return $response_position; - } - - /** - * Get HTML to be added _before_ the HTML of the form fields. - * - * @return string - */ - protected function get_html_before_fields() { - - $html = ''; - $form = $this->form; - - /** - * Filters the HTML before the form fields. - * - * @param string $html - * @param NL4WP_Form $form +class NL4WP_Form_Element +{ + + /** + * @var string + */ + public $ID; + + /** + * @var NL4WP_Form + */ + public $form; + + /** + * @var array + * + * Can be used to set element-specific config settings. Accepts the following keys. + * + * - lists: Customized number of Newsletter list ID's to subscribe to. + * - email_type: The email type + */ + public $config = array(); + + /** + * @var bool + */ + public $is_submitted = false; + + /** + * @param NL4WP_Form $form + * @param string $ID + * @param $config array + */ + public function __construct(NL4WP_Form $form, $ID, $config = array()) + { + $this->form = $form; + $this->ID = $ID; + $this->config = $config; + + $this->is_submitted = $this->form->is_submitted + && $this->form->config['element_id'] == $this->ID; + } + + + /** + * @return string + */ + protected function get_visible_fields() + { + $content = $this->form->content; + $form = $this->form; + $element = $this; + + /** + * Filters the HTML for the form fields. + * + * Use this filter to add custom HTML to a form programmatically + * + * @param string $content + * @param NL4WP_Form $form + * @param NL4WP_Form_Element $element + * @since 2.0 + */ + $visible_fields = (string) apply_filters('nl4wp_form_content', $content, $form, $element); + + return $visible_fields; + } + + /** + * @return string + */ + protected function get_hidden_fields() + { + + // hidden fields + $hidden_fields = ''; + $hidden_fields .= ''; + $hidden_fields .= ''; + $hidden_fields .= ''; + + // was "lists" parameter passed in shortcode arguments? + if (! empty($this->config['lists'])) { + $lists_string = is_array($this->config['lists']) ? join(',', $this->config['lists']) : $this->config['lists']; + $hidden_fields .= ''; + } + + // was "lists" parameter passed in shortcode arguments? + if (! empty($this->config['email_type'])) { + $hidden_fields .= ''; + } + + return (string) $hidden_fields; + } + + /** + * Get HTML string for a notice, including wrapper element. + * + * @param NL4WP_Form_Notice $notice + * + * @return string + */ + protected function get_notice_html(NL4WP_Form_Notice $notice) + { + $html = sprintf('

%s

', esc_attr($notice->type), $notice->text); + return $html; + } + + /** + * Gets the form response string + * + * @param boolean $force_show + * @return string + */ + public function get_response_html($force_show = false) + { + $html = ''; + $form = $this->form; + + if ($this->is_submitted || $force_show) { + foreach ($this->form->notices as $notice) { + $html .= $this->get_notice_html($notice); + } + } + + /** + * Filter the form response HTML + * + * Use this to add your own HTML to the form response. The form instance is passed to the callback function. + * + * @since 3.0 + * + * @param string $html The complete HTML string of the response, excluding the wrapper element. + * @param NL4WP_Form $form The form object + */ + $html = (string) apply_filters('nl4wp_form_response_html', $html, $form); + + // wrap entire response in div, regardless of a form was submitted + $html = '
' . $html . '
'; + return $html; + } + + /** + * @return string + */ + protected function get_response_position() + { + $position = 'after'; + $form = $this->form; + + // check if content contains {response} tag + if (stripos($this->form->content, '{response}') !== false) { + return ''; + } + + /** + * Filters the position for the form response. + * + * Valid values are "before" and "after". Will have no effect if `{response}` is used in the form content. + * + * @param string $position + * @param NL4WP_Form $form + * @since 2.0 + */ + $response_position = (string) apply_filters('nl4wp_form_response_position', $position, $form); + + return $response_position; + } + + /** + * Get HTML to be added _before_ the HTML of the form fields. + * + * @return string + */ + protected function get_html_before_fields() + { + $html = ''; + $form = $this->form; + + /** + * Filters the HTML before the form fields. + * + * @param string $html + * @param NL4WP_Form $form * @ignore - */ - $html = (string) apply_filters( 'nl4wp_form_before_fields', $html, $form ); - - if( $this->get_response_position() === 'before' ) { - $html = $html . $this->get_response_html(); - } - - return $html; - } - - /** - * Get HTML to be added _after_ the HTML of the form fields. - * - * @return string - */ - protected function get_html_after_fields() { - - $html = ''; - $form = $this->form; - - /** - * Filters the HTML after the form fields. - * - * @param string $html - * @param NL4WP_Form $form + */ + $html = (string) apply_filters('nl4wp_form_before_fields', $html, $form); + + if ($this->get_response_position() === 'before') { + $html = $html . $this->get_response_html(); + } + + return $html; + } + + /** + * Get HTML to be added _after_ the HTML of the form fields. + * + * @return string + */ + protected function get_html_after_fields() + { + $html = ''; + $form = $this->form; + + /** + * Filters the HTML after the form fields. + * + * @param string $html + * @param NL4WP_Form $form * @ignore - */ - $html = (string) apply_filters( 'nl4wp_form_after_fields', $html, $form ); - - if( $this->get_response_position() === 'after' ) { - $html = $this->get_response_html() . $html; - } - - return $html; - } - - /** - * Get all HTMl attributes for the form element - * - * @return string - */ - protected function get_form_element_attributes() { - - $form = $this; - $form_action_attribute = null; - - $attributes = array( - 'id' => $this->ID, - 'class' => $this->get_css_classes() - ); - - /** - * Filters the `action` attribute of the `` element. - * - * Defaults to `null`, which means no `action` attribute will be printed. - * - * @param string $form_action_attribute - * @param NL4WP_Form $form - */ - $form_action_attribute = apply_filters( 'nl4wp_form_action', $form_action_attribute, $form ); - if( is_string( $form_action_attribute ) ) { - $attributes['action'] = $form_action_attribute; - } - - /** - * Filters all attributes to be added to the `` element - * - * @param array $attributes Key-value pairs of attributes. - * @param NL4WP_Form $form - */ - $attributes = (array) apply_filters( 'nl4wp_form_element_attributes', $attributes, $form ); - - // hardcoded attributes, can not be changed. - $attributes['method'] = 'post'; - $attributes['data-id'] = $this->form->ID; - $attributes['data-name'] = $this->form->name; - - // build string of key="value" from array - $string = ''; - foreach( $attributes as $name => $value ) { - $string .= sprintf( '%s="%s" ', $name, esc_attr( $value ) ); - } - - return $string; - } - - /** - * @param array|null $config Use this to override the configuration for this form element - * @return string - */ - public function generate_html( array $config = null ) { - - if( $config ) { - $this->config = $config; - } - - // return empty string if form is in trash - if( $this->form->status !== 'publish' ) { - return ''; - } - - // Start building content string - $opening_html = ''; - $opening_html .= 'get_form_element_attributes() .'>'; - $before_fields = $this->get_html_before_fields(); - $fields = ''; - $after_fields = $this->get_html_after_fields(); - $closing_html = ''; - - if( ! $this->is_submitted - || ! $this->form->settings['hide_after_success'] - || $this->form->has_errors()) { - - // add HTML for fields + wrapper element. - $fields = '
' . - $this->get_visible_fields() . - '
' . - $this->get_hidden_fields(); - } - - // concatenate everything - $output = $opening_html . - $before_fields . - $fields . - $after_fields . - $closing_html; - - return $output; - } - - /** - * Get a space separated list of CSS classes for this form - * - * @return string - */ - protected function get_css_classes() { - - $classes = array(); - $form = $this->form; - - $classes[] = 'nl4wp-form'; - $classes[] = 'nl4wp-form-' . $form->ID; - - // Add form classes if this specific form element was submitted - if( $this->is_submitted ) { - $classes[] = 'nl4wp-form-submitted'; - - if( ! $form->has_errors() ) { - $classes[] = 'nl4wp-form-success'; - } else { - $classes[] = 'nl4wp-form-error'; - } - } - - // add class for CSS targeting in custom stylesheets - if( ! empty( $form->settings['css'] ) ) { - - if( strpos( $form->settings['css'], 'theme-' ) === 0 ) { - $classes[] = 'nl4wp-form-theme'; - } - - $classes[] = 'nl4wp-form-' . $form->settings['css']; - } - - // add classes from config array - if( ! empty( $this->config['element_class'] ) ) { - $classes = array_merge( $classes, explode( ' ', $this->config['element_class'] ) ); + */ + $html = (string) apply_filters('nl4wp_form_after_fields', $html, $form); + + if ($this->get_response_position() === 'after') { + $html = $this->get_response_html() . $html; + } + + return $html; + } + + /** + * Get all HTMl attributes for the form element + * + * @return string + */ + protected function get_form_element_attributes() + { + $form = $this; + $form_action_attribute = null; + + $attributes = array( + 'id' => $this->ID, + 'class' => $this->get_css_classes() + ); + + /** + * Filters the `action` attribute of the `
` element. + * + * Defaults to `null`, which means no `action` attribute will be printed. + * + * @param string $form_action_attribute + * @param NL4WP_Form $form + */ + $form_action_attribute = apply_filters('nl4wp_form_action', $form_action_attribute, $form); + if (is_string($form_action_attribute)) { + $attributes['action'] = $form_action_attribute; + } + + /** + * Filters all attributes to be added to the `` element + * + * @param array $attributes Key-value pairs of attributes. + * @param NL4WP_Form $form + */ + $attributes = (array) apply_filters('nl4wp_form_element_attributes', $attributes, $form); + + // hardcoded attributes, can not be changed. + $attributes['method'] = 'post'; + $attributes['data-id'] = $this->form->ID; + $attributes['data-name'] = $this->form->name; + + // build string of key="value" from array + $string = ''; + foreach ($attributes as $name => $value) { + $string .= sprintf('%s="%s" ', $name, esc_attr($value)); + } + + return $string; + } + + /** + * @param array|null $config Use this to override the configuration for this form element + * @return string + */ + public function generate_html(array $config = null) + { + if ($config) { + $this->config = $config; + } + + // return empty string if form is in trash + if ($this->form->status !== 'publish') { + return ''; + } + + // Start building content string + $opening_html = ''; + $opening_html .= 'get_form_element_attributes() .'>'; + $before_fields = $this->get_html_before_fields(); + $fields = ''; + $after_fields = $this->get_html_after_fields(); + $closing_html = '
'; + + if (! $this->is_submitted + || ! $this->form->settings['hide_after_success'] + || $this->form->has_errors()) { + + // add HTML for fields + wrapper element. + $fields = '
' . + $this->get_visible_fields() . + '
' . + $this->get_hidden_fields(); + } + + // concatenate everything + $output = $opening_html . + $before_fields . + $fields . + $after_fields . + $closing_html; + + return $output; + } + + /** + * Get a space separated list of CSS classes for this form + * + * @return string + */ + protected function get_css_classes() + { + $classes = array(); + $form = $this->form; + + $classes[] = 'nl4wp-form'; + $classes[] = 'nl4wp-form-' . $form->ID; + + // Add form classes if this specific form element was submitted + if ($this->is_submitted) { + $classes[] = 'nl4wp-form-submitted'; + + if (! $form->has_errors()) { + $classes[] = 'nl4wp-form-success'; + } else { + $classes[] = 'nl4wp-form-error'; + } + } + + // add class for CSS targeting in custom stylesheets + if (! empty($form->settings['css'])) { + if (strpos($form->settings['css'], 'theme-') === 0) { + $classes[] = 'nl4wp-form-theme'; + } + + $classes[] = 'nl4wp-form-' . $form->settings['css']; + } + + // add classes from config array + if (! empty($this->config['element_class'])) { + $classes = array_merge($classes, explode(' ', $this->config['element_class'])); } - /** - * Filters `class` attributes for the `
` element. - * - * @param array $classes - * @param NL4WP_Form $form - */ - $classes = apply_filters( 'nl4wp_form_css_classes', $classes, $form ); + /** + * Filters `class` attributes for the `` element. + * + * @param array $classes + * @param NL4WP_Form $form + */ + $classes = apply_filters('nl4wp_form_css_classes', $classes, $form); - return implode( ' ', $classes ); - } + return implode(' ', $classes); + } } diff --git a/includes/forms/class-form-listener.php b/includes/forms/class-form-listener.php index cb095c9..f57c9a3 100755 --- a/includes/forms/class-form-listener.php +++ b/includes/forms/class-form-listener.php @@ -6,319 +6,322 @@ * @since 3.0 * @access private */ -class NL4WP_Form_Listener { - - /** - * @var NL4WP_Form The submitted form instance - */ - public $submitted_form; - - public function add_hooks() { - add_action( 'init', array( $this, 'listen' ) ); - } - - /** - * Listen for submitted forms - * @return bool - */ - public function listen() { - if( empty( $_POST['_nl4wp_form_id'] ) ) { - return false; - } - - // get form instance - try { - $form_id = (int) $_POST['_nl4wp_form_id']; - $form = nl4wp_get_form( $form_id ); - } catch( Exception $e ) { - return false; - } - - // sanitize request data - $request_data = $_POST; - $request_data = nl4wp_sanitize_deep( $request_data ); - $request_data = stripslashes_deep( $request_data ); - - // bind request to form & validate - $form->handle_request( $request_data ); - $form->validate(); - - // store submitted form - $this->submitted_form = $form; - - // did form have errors? - if( ! $form->has_errors() ) { - switch( $form->get_action() ) { - case "subscribe": - $result = $this->process_subscribe_form( $form ); - break; - - case "unsubscribe": - $result = $this->process_unsubscribe_form( $form ); - break; - } - } else { - foreach( $form->errors as $error_code ) { - $form->add_notice( $form->get_message( $error_code ), 'error' ); - } - - $this->get_log()->info( sprintf( "Form %d > Submitted with errors: %s", $form->ID, join( ', ', $form->errors ) ) ); - } - - $this->respond( $form ); - return true; - } - - /** - * Process a subscribe form. - * - * @param NL4WP_Form $form - */ - public function process_subscribe_form( NL4WP_Form $form ) { - $result = false; - $newsletter = new NL4WP_Newsletter(); - $email_type = $form->get_email_type(); - $data = $form->get_data(); - $ip_address = nl4wp_get_request_ip_address(); - - /** @var NL4WP_Newsletter_Subscriber $subscriber */ - $subscriber = null; - - /** - * @ignore - * @deprecated 4.0 - */ - $data = apply_filters( 'nl4wp_merge_vars', $data ); - - /** - * @ignore - * @deprecated 4.0 - */ - $data = (array) apply_filters( 'nl4wp_form_merge_vars', $data, $form ); - - // create a map of all lists with list-specific data - $mapper = new NL4WP_List_Data_Mapper( $data, $form->get_lists() ); - - /** @var NL4WP_Newsletter_Subscriber[] $map */ - $map = $mapper->map(); - - // loop through lists - foreach( $map as $list_id => $subscriber ) { - $subscriber->status = $form->settings['double_optin'] ? 'pending' : 'subscribed'; - $subscriber->email_type = $email_type; - $subscriber->ip_signup = $ip_address; - - /** - * Filters subscriber data before it is sent to Newsletter. Fires for both form & integration requests. - * - * @param NL4WP_Newsletter_Subscriber $subscriber - */ - $subscriber = apply_filters( 'nl4wp_subscriber_data', $subscriber ); - - /** - * Filters subscriber data before it is sent to Newsletter. Only fires for form requests. - * - * @param NL4WP_Newsletter_Subscriber $subscriber - */ - $subscriber = apply_filters( 'nl4wp_form_subscriber_data', $subscriber ); - - // send a subscribe request to Newsletter for each list - $result = $newsletter->list_subscribe( $list_id, $subscriber->email_address, $subscriber->to_array(), $form->settings['update_existing'], $form->settings['replace_interests'] ); - } - - $log = $this->get_log(); - - // do stuff on failure - if( ! is_object( $result ) || empty( $result->id ) ) { - - $error_code = $newsletter->get_error_code(); - $error_message = $newsletter->get_error_message(); - - if( $newsletter->get_error_code() == 214 ) { - $form->add_error( 'already_subscribed' ); - $form->add_notice( $form->messages['already_subscribed'], 'notice' ); - $log->warning( sprintf( "Form %d > %s is already subscribed to the selected list(s)", $form->ID, $data['EMAIL'] ) ); - } else { - $form->add_error( $error_code ); - $form->add_notice( $form->messages['error'], 'error' ); - $log->error( sprintf( 'Form %d > Newsletter API error: %s %s', $form->ID, $error_code, $error_message ) ); - - /** - * Fire action hook so API errors can be hooked into. - * - * @param NL4WP_Form $form - * @param string $error_message - */ - do_action( 'nl4wp_form_api_error', $form, $error_message ); - } - - // bail - return; - } - - // Success! Did we update or newly subscribe? - if( $result->status === 'subscribed' && $result->was_already_on_list ) { - $form->last_event = 'updated_subscriber'; - $form->add_notice( $form->messages['updated'], 'success' ); - $log->info( sprintf( "Form %d > Successfully updated %s", $form->ID, $data['EMAIL'] ) ); - - /** - * Fires right after a form was used to update an existing subscriber. - * - * @since 3.0 - * - * @param NL4WP_Form $form Instance of the submitted form - * @param string $email - * @param array $data - */ - do_action( 'nl4wp_form_updated_subscriber', $form, $subscriber->email_address, $data ); - } else { - $form->last_event = 'subscribed'; - $form->add_notice( $form->messages['subscribed'], 'success' ); - $log->info( sprintf( "Form %d > Successfully subscribed %s", $form->ID, $data['EMAIL'] ) ); - } - - /** - * Fires right after a form was used to add a new subscriber (or update an existing one). - * - * @since 3.0 - * - * @param NL4WP_Form $form Instance of the submitted form - * @param string $email - * @param array $data - * @param NL4WP_Newsletter_Subscriber[] $subscriber - */ - do_action( 'nl4wp_form_subscribed', $form, $subscriber->email_address, $data, $map ); - } - - /** - * @param NL4WP_Form $form - */ - public function process_unsubscribe_form( NL4WP_Form $form ) { - - $newsletter = new NL4WP_Newsletter(); - $log = $this->get_log(); - $result = null; - $data = $form->get_data(); - - // unsubscribe from each list - foreach( $form->get_lists() as $list_id ) { - $result = $newsletter->list_unsubscribe( $list_id, $data['EMAIL'] ); - } - - if( ! $result ) { - $form->add_notice( $form->messages['error'], 'error' ); - $log->error( sprintf( 'Form %d > Newsletter API error: %s', $form->ID, $newsletter->get_error_message() ) ); - - // bail - return; - } - - // Success! Unsubscribed. - $form->last_event = 'unsubscribed'; - $form->add_notice( $form->messages['unsubscribed'], 'notice' ); - $log->info( sprintf( "Form %d > Successfully unsubscribed %s", $form->ID, $data['EMAIL'] ) ); - - - /** - * Fires right after a form was used to unsubscribe. - * - * @since 3.0 - * - * @param NL4WP_Form $form Instance of the submitted form. - * @param string $email - */ - do_action( 'nl4wp_form_unsubscribed', $form, $data['EMAIL'] ); - } - - /** - * @param NL4WP_Form $form - */ - public function respond( NL4WP_Form $form ) { - - $success = ! $form->has_errors(); - - if( $success ) { - - /** - * Fires right after a form is submitted without any errors (success). - * - * @since 3.0 - * - * @param NL4WP_Form $form Instance of the submitted form - */ - do_action( 'nl4wp_form_success', $form ); - - } else { - - /** - * Fires right after a form is submitted with errors. - * - * @since 3.0 - * - * @param NL4WP_Form $form The submitted form instance. - */ - do_action( 'nl4wp_form_error', $form ); - - // fire a dedicated event for each error - foreach( $form->errors as $error ) { - - /** - * Fires right after a form was submitted with errors. - * - * The dynamic portion of the hook, `$error`, refers to the error that occurred. - * - * Default errors give us the following possible hooks: - * - * - nl4wp_form_error_error General errors - * - nl4wp_form_error_spam - * - nl4wp_form_error_invalid_email Invalid email address - * - nl4wp_form_error_already_subscribed Email is already on selected list(s) - * - nl4wp_form_error_required_field_missing One or more required fields are missing - * - nl4wp_form_error_no_lists_selected No Newsletter lists were selected - * - * @since 3.0 - * - * @param NL4WP_Form $form The form instance of the submitted form. - */ - do_action( 'nl4wp_form_error_' . $error, $form ); - } - - } - - /** - * Fires right before responding to the form request. - * - * @since 3.0 - * - * @param NL4WP_Form $form Instance of the submitted form. - */ - do_action( 'nl4wp_form_respond', $form ); - - // do stuff on success (non-AJAX only) - if( $success && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) { - - // do we want to redirect? - $redirect_url = $form->get_redirect_url(); - if ( ! empty( $redirect_url ) ) { - wp_redirect( $redirect_url ); - exit; - } - } - } - - /** - * @return NL4WP_API_v3 - */ - protected function get_api() { - return nl4wp('api'); - } - - /** - * @return NL4WP_Debug_Log - */ - protected function get_log() { - return nl4wp('log'); - } - +class NL4WP_Form_Listener +{ + + /** + * @var NL4WP_Form The submitted form instance + */ + public $submitted_form; + + public function add_hooks() + { + add_action('init', array( $this, 'listen' )); + } + + /** + * Listen for submitted forms + * @return bool + */ + public function listen() + { + if (empty($_POST['_nl4wp_form_id'])) { + return false; + } + + // get form instance + try { + $form_id = (int) $_POST['_nl4wp_form_id']; + $form = nl4wp_get_form($form_id); + } catch (Exception $e) { + return false; + } + + // sanitize request data + $request_data = $_POST; + $request_data = nl4wp_sanitize_deep($request_data); + $request_data = stripslashes_deep($request_data); + + // bind request to form & validate + $form->handle_request($request_data); + $form->validate(); + + // store submitted form + $this->submitted_form = $form; + + // did form have errors? + if (! $form->has_errors()) { + switch ($form->get_action()) { + case "subscribe": + $this->process_subscribe_form($form); + break; + + case "unsubscribe": + $this->process_unsubscribe_form($form); + break; + } + } else { + foreach ($form->errors as $error_code) { + $form->add_notice($form->get_message($error_code), 'error'); + } + + $this->get_log()->info(sprintf("Form %d > Submitted with errors: %s", $form->ID, join(', ', $form->errors))); + } + + $this->respond($form); + return true; + } + + /** + * Process a subscribe form. + * + * @param NL4WP_Form $form + */ + public function process_subscribe_form(NL4WP_Form $form) + { + $result = false; + $newsletter = new NL4WP_Newsletter(); + $email_type = $form->get_email_type(); + $data = $form->get_data(); + $ip_address = nl4wp_get_request_ip_address(); + + /** @var NL4WP_Newsletter_Subscriber $subscriber */ + $subscriber = null; + + /** + * @ignore + * @deprecated 4.0 + */ + $data = apply_filters('nl4wp_merge_vars', $data); + + /** + * @ignore + * @deprecated 4.0 + */ + $data = (array) apply_filters('nl4wp_form_merge_vars', $data, $form); + + // create a map of all lists with list-specific data + $mapper = new NL4WP_List_Data_Mapper($data, $form->get_lists()); + + /** @var NL4WP_Newsletter_Subscriber[] $map */ + $map = $mapper->map(); + + // loop through lists + foreach ($map as $list_id => $subscriber) { + $subscriber->status = $form->settings['double_optin'] ? 'pending' : 'subscribed'; + $subscriber->email_type = $email_type; + $subscriber->ip_signup = $ip_address; + $subscriber->tags = $form->get_subscriber_tags(); + + /** + * Filters subscriber data before it is sent to Newsletter. Fires for both form & integration requests. + * + * @param NL4WP_Newsletter_Subscriber $subscriber + */ + $subscriber = apply_filters('nl4wp_subscriber_data', $subscriber); + + /** + * Filters subscriber data before it is sent to Newsletter. Only fires for form requests. + * + * @param NL4WP_Newsletter_Subscriber $subscriber + */ + $subscriber = apply_filters('nl4wp_form_subscriber_data', $subscriber); + + // send a subscribe request to Newsletter for each list + $result = $newsletter->list_subscribe($list_id, $subscriber->email_address, $subscriber->to_array(), $form->settings['update_existing'], $form->settings['replace_interests']); + } + + $log = $this->get_log(); + + // do stuff on failure + if (! is_object($result) || empty($result->id)) { + $error_code = $newsletter->get_error_code(); + $error_message = $newsletter->get_error_message(); + + if ($newsletter->get_error_code() == 214) { + $form->add_error('already_subscribed'); + $form->add_notice($form->messages['already_subscribed'], 'notice'); + $log->warning(sprintf("Form %d > %s is already subscribed to the selected list(s)", $form->ID, $data['EMAIL'])); + } else { + $form->add_error($error_code); + $form->add_notice($form->messages['error'], 'error'); + $log->error(sprintf('Form %d > Newsletter API error: %s %s', $form->ID, $error_code, $error_message)); + + /** + * Fire action hook so API errors can be hooked into. + * + * @param NL4WP_Form $form + * @param string $error_message + */ + do_action('nl4wp_form_api_error', $form, $error_message); + } + + // bail + return; + } + + // Success! Did we update or newly subscribe? + if ($result->status === 'subscribed' && $result->was_already_on_list) { + $form->last_event = 'updated_subscriber'; + $form->add_notice($form->messages['updated'], 'success'); + $log->info(sprintf("Form %d > Successfully updated %s", $form->ID, $data['EMAIL'])); + + /** + * Fires right after a form was used to update an existing subscriber. + * + * @since 3.0 + * + * @param NL4WP_Form $form Instance of the submitted form + * @param string $email + * @param array $data + */ + do_action('nl4wp_form_updated_subscriber', $form, $subscriber->email_address, $data); + } else { + $form->last_event = 'subscribed'; + $form->add_notice($form->messages['subscribed'], 'success'); + $log->info(sprintf("Form %d > Successfully subscribed %s", $form->ID, $data['EMAIL'])); + } + + /** + * Fires right after a form was used to add a new subscriber (or update an existing one). + * + * @since 3.0 + * + * @param NL4WP_Form $form Instance of the submitted form + * @param string $email + * @param array $data + * @param NL4WP_Newsletter_Subscriber[] $subscriber + */ + do_action('nl4wp_form_subscribed', $form, $subscriber->email_address, $data, $map); + } + + /** + * @param NL4WP_Form $form + */ + public function process_unsubscribe_form(NL4WP_Form $form) + { + $newsletter = new NL4WP_Newsletter(); + $log = $this->get_log(); + $result = null; + $data = $form->get_data(); + + // unsubscribe from each list + foreach ($form->get_lists() as $list_id) { + $result = $newsletter->list_unsubscribe($list_id, $data['EMAIL']); + } + + if (! $result) { + $form->add_notice($form->messages['error'], 'error'); + $log->error(sprintf('Form %d > Newsletter API error: %s', $form->ID, $newsletter->get_error_message())); + + // bail + return; + } + + // Success! Unsubscribed. + $form->last_event = 'unsubscribed'; + $form->add_notice($form->messages['unsubscribed'], 'notice'); + $log->info(sprintf("Form %d > Successfully unsubscribed %s", $form->ID, $data['EMAIL'])); + + + /** + * Fires right after a form was used to unsubscribe. + * + * @since 3.0 + * + * @param NL4WP_Form $form Instance of the submitted form. + * @param string $email + */ + do_action('nl4wp_form_unsubscribed', $form, $data['EMAIL']); + } + + /** + * @param NL4WP_Form $form + */ + public function respond(NL4WP_Form $form) + { + $success = ! $form->has_errors(); + + if ($success) { + + /** + * Fires right after a form is submitted without any errors (success). + * + * @since 3.0 + * + * @param NL4WP_Form $form Instance of the submitted form + */ + do_action('nl4wp_form_success', $form); + } else { + + /** + * Fires right after a form is submitted with errors. + * + * @since 3.0 + * + * @param NL4WP_Form $form The submitted form instance. + */ + do_action('nl4wp_form_error', $form); + + // fire a dedicated event for each error + foreach ($form->errors as $error) { + + /** + * Fires right after a form was submitted with errors. + * + * The dynamic portion of the hook, `$error`, refers to the error that occurred. + * + * Default errors give us the following possible hooks: + * + * - nl4wp_form_error_error General errors + * - nl4wp_form_error_spam + * - nl4wp_form_error_invalid_email Invalid email address + * - nl4wp_form_error_already_subscribed Email is already on selected list(s) + * - nl4wp_form_error_required_field_missing One or more required fields are missing + * - nl4wp_form_error_no_lists_selected No Newsletter lists were selected + * + * @since 3.0 + * + * @param NL4WP_Form $form The form instance of the submitted form. + */ + do_action('nl4wp_form_error_' . $error, $form); + } + } + + /** + * Fires right before responding to the form request. + * + * @since 3.0 + * + * @param NL4WP_Form $form Instance of the submitted form. + */ + do_action('nl4wp_form_respond', $form); + + // do stuff on success (non-AJAX only) + if ($success && (! defined('DOING_AJAX') || ! DOING_AJAX)) { + + // do we want to redirect? + $redirect_url = $form->get_redirect_url(); + if (! empty($redirect_url)) { + wp_redirect($redirect_url); + exit; + } + } + } + + /** + * @return NL4WP_API_v3 + */ + protected function get_api() + { + return nl4wp('api'); + } + + /** + * @return NL4WP_Debug_Log + */ + protected function get_log() + { + return nl4wp('log'); + } } diff --git a/includes/forms/class-form-manager.php b/includes/forms/class-form-manager.php index da80d69..68d90ed 100755 --- a/includes/forms/class-form-manager.php +++ b/includes/forms/class-form-manager.php @@ -9,122 +9,146 @@ * @ignore * @access private */ -class NL4WP_Form_Manager { - - /** - * @var NL4WP_Form_Output_Manager - */ - protected $output_manager; - - /** - * @var NL4WP_Form_Listener - */ - protected $listener; - - /** - * @var NL4WP_Form_Tags - */ - protected $tags; - - /** - * @var NL4WP_Form_Previewer - */ - protected $previewer; - - /** - * Constructor - */ - public function __construct() { - $this->output_manager = new NL4WP_Form_Output_Manager(); - $this->tags = new NL4WP_Form_Tags(); - $this->listener = new NL4WP_Form_Listener(); - $this->previewer = new NL4WP_Form_Previewer(); - } - - /** - * Hook! - */ - public function add_hooks() { - add_action( 'init', array( $this, 'initialize' ) ); - add_action( 'wp', array( $this, 'init_asset_manager' ), 90 ); - add_action( 'widgets_init', array( $this, 'register_widget' ) ); - - $this->listener->add_hooks(); - $this->output_manager->add_hooks(); - $this->tags->add_hooks(); - $this->previewer->add_hooks(); - } - - /** - * Initialize - */ - public function initialize() { - $this->register_post_type(); - } - - - /** - * Register post type "nl4wp-form" - */ - public function register_post_type() { - // register post type - register_post_type( 'nl4wp-form', array( - 'labels' => array( - 'name' => 'Newsletter Sign-up Forms', - 'singular_name' => 'Sign-up Form', - ), - 'public' => false - ) - ); - } - - /** - * Initialise asset manager - * - * @hooked `template_redirect` - */ - public function init_asset_manager() { - $assets = new NL4WP_Form_Asset_Manager(); - $assets->hook(); - } - - /** - * Register our Form widget - */ - public function register_widget() { - register_widget( 'NL4WP_Form_Widget' ); - } - - /** - * @param $form_id - * @param array $config - * @param bool $echo - * - * @return string - */ - public function output_form( $form_id, $config = array(), $echo = true ) { - return $this->output_manager->output_form( $form_id, $config, $echo ); - } - - /** - * Gets the currently submitted form - * - * @return NL4WP_Form|null - */ - public function get_submitted_form() { - if( $this->listener->submitted_form instanceof NL4WP_Form ) { - return $this->listener->submitted_form; - } - - return null; - } - - /** - * Return all tags - * - * @return array - */ - public function get_tags() { - return $this->tags->get(); - } +class NL4WP_Form_Manager +{ + + /** + * @var NL4WP_Form_Output_Manager + */ + protected $output_manager; + + /** + * @var NL4WP_Form_Listener + */ + protected $listener; + + /** + * @var NL4WP_Form_Tags + */ + protected $tags; + + /** + * @var NL4WP_Form_Previewer + */ + protected $previewer; + + /** + * Constructor + */ + public function __construct() + { + $this->output_manager = new NL4WP_Form_Output_Manager(); + $this->tags = new NL4WP_Form_Tags(); + $this->listener = new NL4WP_Form_Listener(); + $this->previewer = new NL4WP_Form_Previewer(); + } + + /** + * Hook! + */ + public function add_hooks() + { + add_action('init', array( $this, 'initialize' )); + add_action('wp', array( $this, 'init_asset_manager' ), 90); + add_action('widgets_init', array( $this, 'register_widget' )); + + $this->listener->add_hooks(); + $this->output_manager->add_hooks(); + $this->tags->add_hooks(); + $this->previewer->add_hooks(); + } + + /** + * Initialize + */ + public function initialize() + { + $this->register_post_type(); + $this->register_block_type(); + } + + private function register_block_type() + { + // Bail if register_block_type does not exist (available since WP 5.0) + if (! function_exists('register_block_type')) { + return; + } + + register_block_type( 'newsletter-for-wp/form', array( + 'render_callback' => array($this->output_manager, 'shortcode'), + )); + } + + /** + * Register post type "nl4wp-form" + */ + private function register_post_type() + { + // register post type + register_post_type( + 'nl4wp-form', + array( + 'labels' => array( + 'name' => 'Newsletter Sign-up Forms', + 'singular_name' => 'Sign-up Form', + ), + 'public' => false + ) + ); + } + + /** + * Initialise asset manager + * + * @hooked `template_redirect` + */ + public function init_asset_manager() + { + $assets = new NL4WP_Form_Asset_Manager(); + $assets->hook(); + } + + /** + * Register our Form widget + */ + public function register_widget() + { + register_widget('NL4WP_Form_Widget'); + } + + /** + * @param $form_id + * @param array $config + * @param bool $echo + * + * @return string + */ + public function output_form($form_id, $config = array(), $echo = true) + { + return $this->output_manager->output_form($form_id, $config, $echo); + } + + /** + * Gets the currently submitted form + * + * @return NL4WP_Form|null + */ + public function get_submitted_form() + { + if ($this->listener->submitted_form instanceof NL4WP_Form) { + return $this->listener->submitted_form; + } + + return null; + } + + /** + * Return all tags + * + * @return array + */ + public function get_tags() + { + return $this->tags->get(); + } } diff --git a/includes/forms/class-form-message.php b/includes/forms/class-form-message.php index c48f034..29e5e4f 100755 --- a/includes/forms/class-form-message.php +++ b/includes/forms/class-form-message.php @@ -6,35 +6,37 @@ * @ignore * @access private */ -class NL4WP_Form_Notice { +class NL4WP_Form_Notice +{ - /** - * @var string - */ - public $type = 'error'; + /** + * @var string + */ + public $type = 'error'; - /** - * @var string - */ - public $text; + /** + * @var string + */ + public $text; - /** - * @param string $text - * @param string $type - */ - public function __construct( $text, $type = 'error' ) { - $this->text = $text; + /** + * @param string $text + * @param string $type + */ + public function __construct($text, $type = 'error') + { + $this->text = $text; - if( ! empty( $type ) ) { - $this->type = $type; - } - } - - /** - * @return string - */ - public function __toString() { - return $this->text; - } + if (! empty($type)) { + $this->type = $type; + } + } + /** + * @return string + */ + public function __toString() + { + return $this->text; + } } diff --git a/includes/forms/class-form-previewer.php b/includes/forms/class-form-previewer.php index 7bafdf2..7fe67d0 100644 --- a/includes/forms/class-form-previewer.php +++ b/includes/forms/class-form-previewer.php @@ -1,37 +1,40 @@ 0 ) { + public function load_preview() + { + // clear output, some plugin or hooked code might have thrown errors by now. + if (ob_get_level() > 0) { ob_end_clean(); } $form_id = (int) $_GET['nl4wp_preview_form']; status_header(200); - require dirname( __FILE__ ) . '/views/preview.php'; + require dirname(__FILE__) . '/views/preview.php'; exit; - } + } } diff --git a/includes/forms/class-form-tags.php b/includes/forms/class-form-tags.php index d9cf4f8..022013c 100755 --- a/includes/forms/class-form-tags.php +++ b/includes/forms/class-form-tags.php @@ -6,7 +6,8 @@ * @access private * @ignore */ -class NL4WP_Form_Tags { +class NL4WP_Form_Tags +{ /** * @var NL4WP_Dynamic_Content_Tags @@ -26,22 +27,25 @@ class NL4WP_Form_Tags { /** * Constructor */ - public function __construct() { - $this->tags = new NL4WP_Dynamic_Content_Tags( 'form' ); + public function __construct() + { + $this->tags = new NL4WP_Dynamic_Content_Tags('form'); } - public function add_hooks() { - add_filter( 'nl4wp_dynamic_content_tags_form', array( $this, 'register' ) ); - add_filter( 'nl4wp_form_response_html', array( $this, 'replace' ), 10, 2 ); - add_filter( 'nl4wp_form_content', array( $this, 'replace' ), 10, 3 ); - add_filter( 'nl4wp_form_redirect_url', array( $this, 'replace_in_url' ), 10, 2 ); + public function add_hooks() + { + add_filter('nl4wp_dynamic_content_tags_form', array( $this, 'register' )); + add_filter('nl4wp_form_response_html', array( $this, 'replace' ), 10, 2); + add_filter('nl4wp_form_content', array( $this, 'replace' ), 10, 3); + add_filter('nl4wp_form_redirect_url', array( $this, 'replace_in_url' ), 10, 2); } /** * @return array */ - public function get() { + public function get() + { return $this->tags->all(); } @@ -49,72 +53,73 @@ public function get() { * @param array $tags * @return array */ - public function register( array $tags ) { + public function register(array $tags) + { $tags['response'] = array( - 'description' => __( 'Replaced with the form response (error or success messages).', 'newsletter-for-wp' ), + 'description' => __('Replaced with the form response (error or success messages).', 'newsletter-for-wp'), 'callback' => array( $this, 'get_form_response' ) ); $tags['data'] = array( - 'description' => sprintf( __( "Data from the URL or a submitted form.", 'newsletter-for-wp' ) ), + 'description' => sprintf(__("Data from the URL or a submitted form.", 'newsletter-for-wp')), 'callback' => array( $this, 'get_data' ), 'example' => "data key='UTM_SOURCE' default='Default Source'" ); $tags['cookie'] = array( - 'description' => sprintf( __( "Data from a cookie.", 'newsletter-for-wp' ) ), + 'description' => sprintf(__("Data from a cookie.", 'newsletter-for-wp')), 'callback' => array( $this, 'get_cookie' ), 'example' => "cookie name='my_cookie' default='Default Value'" ); $tags['subscriber_count'] = array( - 'description' => __( 'Replaced with the number of subscribers on the selected list(s)', 'newsletter-for-wp' ), + 'description' => __('Replaced with the number of subscribers on the selected list(s)', 'newsletter-for-wp'), 'callback' => array( $this, 'get_subscriber_count' ) ); $tags['email'] = array( - 'description' => __( 'The email address of the current visitor (if known).', 'newsletter-for-wp' ), + 'description' => __('The email address of the current visitor (if known).', 'newsletter-for-wp'), 'callback' => array( $this, 'get_email' ), ); $tags['current_url'] = array( - 'description' => __( 'The URL of the page.', 'newsletter-for-wp' ), + 'description' => __('The URL of the page.', 'newsletter-for-wp'), 'callback' => 'nl4wp_get_request_url', ); $tags['current_path'] = array( - 'description' => __( 'The path of the page.', 'newsletter-for-wp' ), + 'description' => __('The path of the page.', 'newsletter-for-wp'), 'callback' => 'nl4wp_get_request_path', ); $tags['date'] = array( - 'description' => sprintf( __( 'The current date. Example: %s.', 'newsletter-for-wp' ), '' . date( 'Y/m/d' ) . '' ), - 'replacement' => date( 'Y/m/d' ) + 'description' => sprintf(__('The current date. Example: %s.', 'newsletter-for-wp'), '' . date('Y/m/d') . ''), + 'replacement' => date('Y/m/d') ); $tags['time'] = array( - 'description' => sprintf( __( 'The current time. Example: %s.', 'newsletter-for-wp' ), '' . date( 'H:i:s' ) . ''), - 'replacement' => date( 'H:i:s' ) + 'description' => sprintf(__('The current time. Example: %s.', 'newsletter-for-wp'), '' . date('H:i:s') . ''), + 'replacement' => date('H:i:s') ); $tags['language'] = array( - 'description' => sprintf( __( 'The site\'s language. Example: %s.', 'newsletter-for-wp' ), '' . get_locale() . '' ), + 'description' => sprintf(__('The site\'s language. Example: %s.', 'newsletter-for-wp'), '' . get_locale() . ''), 'callback' => 'get_locale', ); $tags['ip'] = array( - 'description' => sprintf( __( 'The visitor\'s IP address. Example: %s.', 'newsletter-for-wp' ), '' . nl4wp('request')->get_client_ip() . '' ), + 'description' => sprintf(__('The visitor\'s IP address. Example: %s.', 'newsletter-for-wp'), '' . nl4wp('request')->get_client_ip() . ''), 'callback' => 'nl4wp_get_request_ip_address', ); $tags['user'] = array( - 'description' => sprintf( __( "The property of the currently logged-in user.", 'newsletter-for-wp' ) ), + 'description' => sprintf(__("The property of the currently logged-in user.", 'newsletter-for-wp')), 'callback' => array( $this, 'get_user_property' ), 'example' => "user property='user_email'" ); $tags['post'] = array( - 'description' => sprintf( __( "Property of the current page or post.", 'newsletter-for-wp' ) ), + 'description' => sprintf(__("Property of the current page or post.", 'newsletter-for-wp')), 'callback' => array( $this, 'get_post_property' ), 'example' => "post property='ID'" ); @@ -134,10 +139,11 @@ public function register( array $tags ) { * * @return string */ - public function replace( $string, NL4WP_Form $form, NL4WP_Form_Element $element = null ) { + public function replace($string, NL4WP_Form $form, NL4WP_Form_Element $element = null) + { $this->form = $form; $this->form_element = $element; - $string = $this->tags->replace( $string ); + $string = $this->tags->replace($string); return $string; } @@ -149,9 +155,10 @@ public function replace( $string, NL4WP_Form $form, NL4WP_Form_Element $element * * @return string */ - public function replace_in_url( $string, NL4WP_Form $form ) { + public function replace_in_url($string, NL4WP_Form $form) + { $this->form = $form; - $string = $this->tags->replace_in_url( $string ); + $string = $this->tags->replace_in_url($string); return $string; } @@ -160,10 +167,11 @@ public function replace_in_url( $string, NL4WP_Form $form ) { * * @return int */ - public function get_subscriber_count() { + public function get_subscriber_count() + { $newsletter = new NL4WP_Newsletter(); - $count = $newsletter->get_subscriber_count( $this->form->get_lists() ); - return number_format( $count ); + $count = $newsletter->get_subscriber_count($this->form->get_lists()); + return number_format($count); } /** @@ -171,9 +179,9 @@ public function get_subscriber_count() { * * @return string */ - public function get_form_response() { - - if( $this->form_element instanceof NL4WP_Form_Element ) { + public function get_form_response() + { + if ($this->form_element instanceof NL4WP_Form_Element) { return $this->form_element->get_response_html(); } @@ -187,24 +195,25 @@ public function get_form_response() { * * @return string */ - public function get_data( $args = array() ) { - if( empty( $args['key'] ) ) { + public function get_data($args = array()) + { + if (empty($args['key'])) { return ''; } - $default = isset( $args['default'] ) ? $args['default'] : ''; + $default = isset($args['default']) ? $args['default'] : ''; $key = $args['key']; - $data = array_merge( $_GET, $_POST ); - $value = isset( $data[$key] ) ? $data[$key] : $default; + $data = array_merge($_GET, $_POST); + $value = isset($data[$key]) ? $data[$key] : $default; // turn array into readable value - if( is_array( $value ) ) { - $value = array_filter( $value ); - $value = join( ', ', $value ); + if (is_array($value)) { + $value = array_filter($value); + $value = join(', ', $value); } - return esc_html( $value ); + return esc_html($value); } /** @@ -214,16 +223,17 @@ public function get_data( $args = array() ) { * * @return string */ - public function get_cookie( $args = array() ) { - if( empty( $args['name'] ) ) { + public function get_cookie($args = array()) + { + if (empty($args['name'])) { return ''; } $name = $args['name']; - $default = isset( $args['default'] ) ? $args['default'] : ''; + $default = isset($args['default']) ? $args['default'] : ''; - if( isset( $_COOKIE[ $name ] ) ) { - return esc_html( stripslashes( $_COOKIE[ $name ] ) ); + if (isset($_COOKIE[ $name ])) { + return esc_html(stripslashes($_COOKIE[ $name ])); } return $default; @@ -236,13 +246,14 @@ public function get_cookie( $args = array() ) { * * @return string */ - public function get_user_property( $args = array() ) { - $property = empty( $args['property'] ) ? 'user_email' : $args['property']; - $default = isset( $args['default'] ) ? $args['default'] : ''; + public function get_user_property($args = array()) + { + $property = empty($args['property']) ? 'user_email' : $args['property']; + $default = isset($args['default']) ? $args['default'] : ''; $user = wp_get_current_user(); - if( $user instanceof WP_User && isset( $user->{$property} ) ) { - return esc_html( $user->{$property} ); + if ($user instanceof WP_User && isset($user->{$property})) { + return esc_html($user->{$property}); } return $default; @@ -255,13 +266,14 @@ public function get_user_property( $args = array() ) { * * @return string */ - public function get_post_property( $args = array() ) { + public function get_post_property($args = array()) + { global $post; - $property = empty( $args['property'] ) ? 'ID' : $args['property']; - $default = isset( $args['default'] ) ? $args['default'] : ''; + $property = empty($args['property']) ? 'ID' : $args['property']; + $default = isset($args['default']) ? $args['default'] : ''; - if( $post instanceof WP_Post && isset( $post->{$property} ) ) { + if ($post instanceof WP_Post && isset($post->{$property})) { return $post->{$property}; } @@ -271,17 +283,18 @@ public function get_post_property( $args = array() ) { /** * @return string */ - public function get_email() { + public function get_email() + { // first, try request $request = nl4wp('request'); - $email = $request->params->get( 'EMAIL', '' ); - if( $email ) { + $email = $request->params->get('EMAIL', ''); + if ($email) { return $email; } // then , try logged-in user - if( is_user_logged_in() ) { + if (is_user_logged_in()) { $user = wp_get_current_user(); return $user->user_email; } @@ -289,5 +302,4 @@ public function get_email() { // TODO: Read from cookie? Or add $_COOKIE support to {data} tag? return ''; } - } diff --git a/includes/forms/class-form.php b/includes/forms/class-form.php index e26c196..368cd1a 100755 --- a/includes/forms/class-form.php +++ b/includes/forms/class-form.php @@ -10,7 +10,8 @@ * @access public * @since 3.0 */ -class NL4WP_Form { +class NL4WP_Form +{ /** * @var array Array of instantiated form objects. @@ -24,35 +25,35 @@ class NL4WP_Form { * @return NL4WP_Form * @throws Exception */ - public static function get_instance( $post = 0 ) { - - if( $post instanceof WP_Post ) { + public static function get_instance($post = 0) + { + if ($post instanceof WP_Post) { $post_id = $post->ID; } else { $post_id = (int) $post; - if( empty( $post_id ) ) { - $post_id = (int) get_option( 'nl4wp_default_form_id', 0 ); + if (empty($post_id)) { + $post_id = (int) get_option('nl4wp_default_form_id', 0); } } - if( isset( self::$instances[ $post_id ] ) ) { + if (isset(self::$instances[ $post_id ])) { return self::$instances[ $post_id ]; } // get post object if we don't have it by now - if( ! $post instanceof WP_Post ) { - $post = get_post( $post_id ); + if (! $post instanceof WP_Post) { + $post = get_post($post_id); } // check post object - if( ! is_object( $post ) || ! isset( $post->post_type ) || $post->post_type !== 'nl4wp-form' ) { - $message = sprintf( __( 'There is no form with ID %d, perhaps it was deleted?', 'newsletter-for-wp' ), $post_id ); - throw new Exception( $message ); + if (! is_object($post) || ! isset($post->post_type) || $post->post_type !== 'nl4wp-form') { + $message = sprintf(__('There is no form with ID %d, perhaps it was deleted?', 'newsletter-for-wp'), $post_id); + throw new Exception($message); } - $post_meta = get_post_meta( $post_id ); - $form = new NL4WP_Form( $post_id, $post, $post_meta ); + $post_meta = get_post_meta($post_id); + $form = new NL4WP_Form($post_id, $post, $post_meta); // store instance self::$instances[ $post_id ] = $form; @@ -98,7 +99,7 @@ public static function get_instance( $post = 0 ) { /** * @var bool Was this form submitted? */ - public $is_submitted = false; + public $is_submitted = false; /** * @var array Array of the data that was submitted, in name => value pairs. @@ -137,13 +138,14 @@ public static function get_instance( $post = 0 ) { * @param WP_Post $post * @param array $post_meta */ - public function __construct( $id, $post, $post_meta = array() ) { + public function __construct($id, $post, $post_meta = array()) + { $this->ID = $id = (int) $id; $this->name = $post->post_title; $this->content = $post->post_content; $this->status = $post->post_status; - $this->settings = $this->load_settings( $post_meta ); - $this->messages = $this->load_messages( $post_meta ); + $this->settings = $this->load_settings($post_meta); + $this->messages = $this->load_messages($post_meta); // update config from settings $this->config['lists'] = $this->settings['lists']; @@ -154,9 +156,10 @@ public function __construct( $id, $post, $post_meta = array() ) { * * @return mixed */ - public function __get( $name ) { - $method_name = sprintf( "get_%s", $name ); - if( method_exists( $this, $method_name ) ) { + public function __get($name) + { + $method_name = sprintf("get_%s", $name); + if (method_exists($this, $method_name)) { return $this->$method_name(); } } @@ -171,8 +174,9 @@ public function __get( $name ) { * * @return string */ - public function get_response_html() { - return $this->get_element()->get_response_html( true ); + public function get_response_html() + { + return $this->get_element()->get_response_html(true); } /** @@ -180,8 +184,9 @@ public function get_response_html() { * @param array $config * @return NL4WP_Form_element */ - public function get_element( $element_id = 'nl4wp-form', $config = array() ) { - return new NL4WP_Form_Element( $this, $element_id, $config ); + public function get_element($element_id = 'nl4wp-form', $config = array()) + { + return new NL4WP_Form_Element($this, $element_id, $config); } /** @@ -194,8 +199,9 @@ public function get_element( $element_id = 'nl4wp-form', $config = array() ) { * * @return string */ - public function get_html( $element_id = 'nl4wp-form', array $config = array() ) { - $element = $this->get_element( $element_id, $config ); + public function get_html($element_id = 'nl4wp-form', array $config = array()) + { + $element = $this->get_element($element_id, $config); $html = $element->generate_html(); return $html; } @@ -205,13 +211,13 @@ public function get_html( $element_id = 'nl4wp-form', array $config = array() ) * @staticvar $defaults * @return array */ - protected function load_settings( $post_meta = array() ) { - + protected function load_settings($post_meta = array()) + { $form = $this; static $default_settings; // get default settings - if( ! $default_settings ) { + if (! $default_settings) { $default_settings = include NL4WP_PLUGIN_DIR . 'config/default-form-settings.php'; } @@ -219,17 +225,17 @@ protected function load_settings( $post_meta = array() ) { $settings = $default_settings; // get custom settings from meta - if( ! empty( $post_meta['_nl4wp_settings'] ) ) { + if (! empty($post_meta['_nl4wp_settings'])) { $meta = $post_meta['_nl4wp_settings'][0]; - $meta = (array) maybe_unserialize( $meta ); + $meta = (array) maybe_unserialize($meta); // ensure lists is an array - if( empty( $meta['lists'] ) ) { + if (empty($meta['lists'])) { $meta['lists'] = array(); } // merge with current settings (defaults) - $settings = array_merge( $settings, $meta ); + $settings = array_merge($settings, $meta); } /** @@ -240,7 +246,7 @@ protected function load_settings( $post_meta = array() ) { * @param array $settings * @param NL4WP_Form $form */ - $settings = (array) apply_filters( 'nl4wp_form_settings', $settings, $form ); + $settings = (array) apply_filters('nl4wp_form_settings', $settings, $form); return $settings; } @@ -249,8 +255,8 @@ protected function load_settings( $post_meta = array() ) { * @staticvar $default_messages * @return array */ - protected function load_messages( $post_meta = array() ) { - + protected function load_messages($post_meta = array()) + { $form = $this; // get default messages @@ -267,19 +273,19 @@ protected function load_messages( $post_meta = array() ) { * @param array $registered_messages * @param NL4WP_Form $form */ - $messages = (array) apply_filters( 'nl4wp_form_messages', $messages, $form ); + $messages = (array) apply_filters('nl4wp_form_messages', $messages, $form); // for backwards compatiblity, grab text of each message (if is array) - foreach( $messages as $key => $message ) { - if( is_array( $message ) && isset( $message['text'] ) ) { + foreach ($messages as $key => $message) { + if (is_array($message) && isset($message['text'])) { $messages[$key] = $message['text']; } } - foreach( $messages as $key => $message_text ) { + foreach ($messages as $key => $message_text) { // overwrite default text with text in form meta. - if( isset( $post_meta[ 'text_' . $key ][0] ) ) { + if (isset($post_meta[ 'text_' . $key ][0])) { $message_text = $post_meta[ 'text_' . $key ][0]; } @@ -296,8 +302,9 @@ protected function load_messages( $post_meta = array() ) { * * @return bool */ - public function has_field_type( $type ) { - return in_array( strtolower( $type ), $this->get_field_types() ); + public function has_field_type($type) + { + return in_array(strtolower($type), $this->get_field_types()); } /** @@ -305,8 +312,9 @@ public function has_field_type( $type ) { * * @return array */ - public function get_field_types() { - preg_match_all( '/type=\"(\w+)?\"/', strtolower( $this->content ), $result ); + public function get_field_types() + { + preg_match_all('/type=\"(\w+)?\"/', strtolower($this->content), $result); $field_types = $result[1]; return $field_types; } @@ -316,8 +324,9 @@ public function get_field_types() { * @param string $text * @param string $type */ - public function add_notice( $text, $type = 'notice' ) { - $this->notices[] = new NL4WP_Form_Notice( $text, $type ); + public function add_notice($text, $type = 'notice') + { + $this->notices[] = new NL4WP_Form_Notice($text, $type); } /** @@ -325,8 +334,9 @@ public function add_notice( $text, $type = 'notice' ) { * * @return string */ - public function __toString() { - return nl4wp_show_form( $this->ID, array(), false ); + public function __toString() + { + return nl4wp_show_form($this->ID, array(), false); } /** @@ -334,9 +344,10 @@ public function __toString() { * * @return string */ - public function get_redirect_url() { + public function get_redirect_url() + { $form = $this; - $url = trim( $this->settings['redirect'] ); + $url = trim($this->settings['redirect']); /** * Filters the redirect URL setting @@ -346,7 +357,7 @@ public function get_redirect_url() { * @param string $url * @param NL4WP_Form $form */ - $url = (string) apply_filters( 'nl4wp_form_redirect_url', $url, $form ); + $url = (string) apply_filters('nl4wp_form_redirect_url', $url, $form); return $url; } @@ -358,42 +369,42 @@ public function get_redirect_url() { * * @return bool */ - public function validate() { - - if( ! $this->is_submitted ) { + public function validate() + { + if (! $this->is_submitted) { return true; } $form = $this; $errors = array(); - if( empty( $this->config['lists'] ) ) { + if (empty($this->config['lists'])) { $errors[] = 'no_lists_selected'; } - if( ! isset( $this->raw_data['_nl4wp_timestamp'] ) || $this->raw_data['_nl4wp_timestamp'] > ( time() - 2 ) ) { + if (! isset($this->raw_data['_nl4wp_timestamp']) || $this->raw_data['_nl4wp_timestamp'] > (time() - 2)) { $errors[] = 'spam'; - } else if( ! isset( $this->raw_data['_nl4wp_honeypot'] ) || ! empty( $this->raw_data['_nl4wp_honeypot'] ) ) { + } elseif (! isset($this->raw_data['_nl4wp_honeypot']) || ! empty($this->raw_data['_nl4wp_honeypot'])) { $errors[] = 'spam'; } - if( empty( $errors ) ) { + if (empty($errors)) { // validate email field - if( empty( $this->data['EMAIL'] ) || ! is_email( $this->data['EMAIL'] ) ) { + if (empty($this->data['EMAIL']) || ! is_email($this->data['EMAIL'])) { $errors[] = 'invalid_email'; } // validate other required fields - foreach( $this->get_required_fields() as $field ) { - $value = nl4wp_array_get( $this->data, $field ); + foreach ($this->get_required_fields() as $field) { + $value = nl4wp_array_get($this->data, $field); // check for empty string or array here instead of empty() since we want to allow for "0" values. - if( $value === "" || $value === array() ) { + if ($value === "" || $value === array()) { $errors[] = 'required_field_missing'; break; } } - } + } /** * Filters whether this form has errors. Runs only when a form is submitted. @@ -406,19 +417,19 @@ public function validate() { * @param array $errors * @param NL4WP_Form $form */ - $errors = (array) apply_filters( 'nl4wp_form_errors', $errors, $form ); + $errors = (array) apply_filters('nl4wp_form_errors', $errors, $form); /** * @ignore * @deprecated 3.0 Use `nl4wp_form_errors` instead */ - $form_validity = apply_filters( 'nl4wp_valid_form_request', true, $this->data ); - if( is_string( $form_validity ) ) { + $form_validity = apply_filters('nl4wp_valid_form_request', true, $this->data); + if (is_string($form_validity)) { $errors[] = $form_validity; } // filter out all non-string values - $errors = array_filter( $errors, 'is_string' ); + $errors = array_filter($errors, 'is_string'); // set property on self $this->errors = $errors; @@ -434,10 +445,11 @@ public function validate() { * @param array $data * @return void */ - public function handle_request( array $data ) { + public function handle_request(array $data) + { $this->is_submitted = true; $this->raw_data = $data; - $this->data = $this->parse_request_data( $data ); + $this->data = $this->parse_request_data($data); $this->last_event = ''; // update form configuration from given data @@ -450,19 +462,19 @@ public function handle_request( array $data ) { ); // use isset here to allow empty lists (which should show a notice) - foreach( $map as $param_key => $config_key ) { - if( isset( $this->raw_data[ $param_key ] ) ) { + foreach ($map as $param_key => $config_key) { + if (isset($this->raw_data[ $param_key ])) { $value = $this->raw_data[ $param_key ]; - if( is_array( $value ) ) { - $value = array_filter( $value ); + if (is_array($value)) { + $value = array_filter($value); } $config[ $config_key ] = $value; } } - if( ! empty( $config ) ) { - $this->set_config( $config ); + if (! empty($config)) { + $this->set_config($config); } } @@ -479,33 +491,34 @@ public function handle_request( array $data ) { * * @return array */ - protected function parse_request_data( array $data ) { + protected function parse_request_data(array $data) + { $form = $this; $filtered = array(); $ignored_field_names = array(); - /** - * Filters field names which should be ignored when showing data. - * - * @since 3.0 - * - * @param array $ignored_field_names Array of ignored field names - * @param NL4WP_Form $form The form instance. - */ - $ignored_field_names = apply_filters( 'nl4wp_form_ignored_field_names', $ignored_field_names, $form ); - - foreach( $data as $key => $value ) { + /** + * Filters field names which should be ignored when showing data. + * + * @since 3.0 + * + * @param array $ignored_field_names Array of ignored field names + * @param NL4WP_Form $form The form instance. + */ + $ignored_field_names = apply_filters('nl4wp_form_ignored_field_names', $ignored_field_names, $form); + + foreach ($data as $key => $value) { // skip fields in ignored field names - if( $key[0] === '_' || in_array( $key, $ignored_field_names) ) { + if ($key[0] === '_' || in_array($key, $ignored_field_names)) { continue; } // uppercase key - $key = strtoupper( $key ); + $key = strtoupper($key); // filter empty array values - if( is_array( $value ) ) { - $value = array_filter( $value ); + if (is_array($value)) { + $value = array_filter($value); } $filtered[$key] = $value; @@ -520,21 +533,22 @@ protected function parse_request_data( array $data ) { * @param array $config * @return array */ - public function set_config( array $config ) { - $this->config = array_merge( $this->config, $config ); + public function set_config(array $config) + { + $this->config = array_merge($this->config, $config); // make sure lists is an array - if( ! is_array( $this->config['lists'] ) ) { - $this->config['lists'] = array_map( 'trim', explode(',', $this->config['lists'] ) ); + if (! is_array($this->config['lists'])) { + $this->config['lists'] = array_map('trim', explode(',', $this->config['lists'])); } // make sure action is valid - if( ! in_array( $this->config['action'], array( 'subscribe', 'unsubscribe' ) ) ) { + if (! in_array($this->config['action'], array( 'subscribe', 'unsubscribe' ))) { $this->config['action'] = 'subscribe'; } // email_type should be a valid value - if( ! in_array( $this->config['email_type'], array( 'html', 'text' ) ) ) { + if (! in_array($this->config['email_type'], array( 'html', 'text' ))) { $this->config['email_type'] = ''; } @@ -546,8 +560,8 @@ public function set_config( array $config ) { * * @return array */ - public function get_lists() { - + public function get_lists() + { $lists = $this->config['lists']; $form = $this; @@ -556,7 +570,7 @@ public function get_lists() { * * @param array $lists */ - $lists = (array) apply_filters( 'nl4wp_lists', $lists ); + $lists = (array) apply_filters('nl4wp_lists', $lists); /** * Filters Newsletter lists new subscribers coming from this form should be added to. @@ -564,10 +578,10 @@ public function get_lists() { * @param array $lists * @param NL4WP_Form $form */ - $lists = (array) apply_filters( 'nl4wp_form_lists', $lists, $form ); + $lists = (array) apply_filters('nl4wp_form_lists', $lists, $form); // filter out empty array elements - $lists = array_filter( $lists ); + $lists = array_filter($lists); return $lists; } @@ -580,8 +594,9 @@ public function get_lists() { * @see `nl4wp_form_errors` filter. * @return bool */ - public function has_errors() { - return count( $this->errors ) > 0; + public function has_errors() + { + return count($this->errors) > 0; } /** @@ -589,9 +604,10 @@ public function has_errors() { * * @param string $error_code */ - public function add_error( $error_code ) { + public function add_error($error_code) + { // only add each error once - if( ! in_array( $error_code, $this->errors ) ) { + if (! in_array($error_code, $this->errors)) { $this->errors[] = $error_code; } } @@ -603,14 +619,16 @@ public function add_error( $error_code ) { * * @return string */ - public function get_action() { + public function get_action() + { return $this->config['action']; } /** * @return array */ - public function get_data() { + public function get_data() + { $data = $this->data; $form = $this; @@ -620,7 +638,7 @@ public function get_data() { * @param array $data * @param NL4WP_Form $form */ - $data = apply_filters( 'nl4wp_form_data', $data, $form ); + $data = apply_filters('nl4wp_form_data', $data, $form); return $data; } @@ -630,31 +648,32 @@ public function get_data() { * * @return array */ - public function get_required_fields() { + public function get_required_fields() + { $form = $this; // explode required fields (generated in JS) to an array (uppercased) - $required_fields_string = strtoupper( $this->settings['required_fields'] ); + $required_fields_string = strtoupper($this->settings['required_fields']); // remove array-formatted fields // workaround for #261 (https://github.com/ibericode/newsletter-for-wordpress/issues/261) - $required_fields_string = preg_replace( '/\[\w+\]/', '', $required_fields_string ); + $required_fields_string = preg_replace('/\[\w+\]/', '', $required_fields_string); // turn into an array - $required_fields = explode( ',', $required_fields_string ); + $required_fields = explode(',', $required_fields_string); // EMAIL is not a required field as it has its own validation rules - $required_fields = array_diff( $required_fields, array( 'EMAIL' ) ); + $required_fields = array_diff($required_fields, array( 'EMAIL' )); // filter duplicate & empty values - $required_fields = array_unique( $required_fields ); - $required_fields = array_filter( $required_fields ); + $required_fields = array_unique($required_fields); + $required_fields = array_filter($required_fields); // fix uppercased subkeys, see https://github.com/ibericode/newsletter-for-wordpress/issues/516 - foreach( $required_fields as $key => $value ) { - $pos = strpos( $value, '.'); - if($pos > 0) { - $required_fields[$key] = substr( $value, 0, $pos) . strtolower( substr( $value, $pos ) ); + foreach ($required_fields as $key => $value) { + $pos = strpos($value, '.'); + if ($pos > 0) { + $required_fields[$key] = substr($value, 0, $pos) . strtolower(substr($value, $pos)); } } @@ -669,7 +688,7 @@ public function get_required_fields() { * @param array $required_fields * @param NL4WP_Form $form */ - $required_fields = (array) apply_filters( 'nl4wp_form_required_fields', $required_fields, $form ); + $required_fields = (array) apply_filters('nl4wp_form_required_fields', $required_fields, $form); return $required_fields; } @@ -679,10 +698,11 @@ public function get_required_fields() { * * @return string */ - public function get_email_type() { + public function get_email_type() + { $email_type = $this->config['email_type']; - if( empty( $email_type ) ) { + if (empty($email_type)) { $email_type = nl4wp_get_email_type(); } @@ -694,15 +714,16 @@ public function get_email_type() { * * @return string */ - public function get_stylesheet() { + public function get_stylesheet() + { $stylesheet = $this->settings['css']; - if( empty( $stylesheet ) ) { + if (empty($stylesheet)) { return ''; } // form themes live in the same stylesheet - if( strpos( $stylesheet, 'theme-' ) !== false ) { + if (strpos($stylesheet, 'theme-') !== false) { $stylesheet = 'themes'; } @@ -713,11 +734,12 @@ public function get_stylesheet() { * @param string $key * @return string */ - public function get_message( $key ) { - $message = isset( $this->messages[ $key] ) ? $this->messages[ $key ] : $this->messages['error'] ; + public function get_message($key) + { + $message = isset($this->messages[ $key]) ? $this->messages[ $key ] : $this->messages['error'] ; - if( $key === 'no_lists_selected' && current_user_can( 'manage_options' ) ) { - $message .= sprintf( ' (%s)', nl4wp_get_edit_form_url( $this->ID, 'settings' ), 'edit form settings' ); + if ($key === 'no_lists_selected' && current_user_can('manage_options')) { + $message .= sprintf(' (%s)', nl4wp_get_edit_form_url($this->ID, 'settings'), 'edit form settings'); } return $message; @@ -732,17 +754,33 @@ public function get_message( $key ) { * * @return string */ - public function get_message_html( $key ) { - _deprecated_function( __METHOD__, '3.2' ); + public function get_message_html($key) + { + _deprecated_function(__METHOD__, '3.2'); return ''; } /** * Add a notice to this form */ - public function add_message( $key ) { - _deprecated_function( __METHOD__, '3.3' ); - $this->add_notice( $this->get_message( $key ) ); + public function add_message($key) + { + _deprecated_function(__METHOD__, '3.3'); + $this->add_notice($this->get_message($key)); } + /** + * @since 4.4 + * @return array + */ + public function get_subscriber_tags() + { + if (empty($this->settings['subscriber_tags'])) { + return array(); + } + + $tags = explode(',', $this->settings['subscriber_tags']); + $tags = array_map('trim', $tags); + return $tags; + } } diff --git a/includes/forms/class-output-manager.php b/includes/forms/class-output-manager.php index 643fe38..2591a76 100755 --- a/includes/forms/class-output-manager.php +++ b/includes/forms/class-output-manager.php @@ -7,132 +7,136 @@ * @ignore * @access private */ -class NL4WP_Form_Output_Manager { - - /** - * @var int The # of forms outputted - */ - public $count = 0; - - /** - * @const string - */ - const SHORTCODE = 'nl4wp_form'; - - /** - * Constructor - */ - public function __construct() {} - - /** - * Add hooks - */ - public function add_hooks() { - // enable shortcodes in text widgets - add_filter( 'widget_text', 'shortcode_unautop' ); - add_filter( 'widget_text', 'do_shortcode', 11 ); - - // enable shortcodes in form content - add_filter( 'nl4wp_form_content', 'do_shortcode' ); - - add_action( 'init', array( $this, 'register_shortcode' ) ); - } - - /** - * Registers the [nl4wp_form] shortcode - */ - public function register_shortcode() { - // register shortcodes - add_shortcode( self::SHORTCODE, array( $this, 'shortcode' ) ); - } - - /** - * @param array $attributes - * @param string $content - * @return string - */ - public function shortcode( $attributes = array(), $content = '' ) { - $default_attributes = array( - 'id' => '', - 'lists' => '', - 'email_type' => '', - 'element_id' => '', - 'element_class' => '', - ); - - $attributes = shortcode_atts( - $default_attributes, - $attributes, - self::SHORTCODE - ); - - $config = array( - 'element_id' => $attributes['element_id'], - 'lists' => $attributes['lists'], - 'email_type' => $attributes['email_type'], - 'element_class' => $attributes['element_class'], - ); - - return $this->output_form( $attributes['id'], $config, false ); - } - - /** - * @param int $id - * @param array $config - * @param bool $echo - * - * @return string - */ - public function output_form( $id = 0, $config = array(), $echo = true ) { - - try { - $form = nl4wp_get_form( $id ); - } catch( Exception $e ) { - - if( current_user_can( 'manage_options' ) ) { - return sprintf( 'Newsletter for WordPress error: %s', $e->getMessage() ); - } - - return ''; - } - - $this->count++; +class NL4WP_Form_Output_Manager +{ + + /** + * @var int The # of forms outputted + */ + public $count = 0; + + /** + * @const string + */ + const SHORTCODE = 'nl4wp_form'; + + /** + * Constructor + */ + public function __construct() + { + } + + /** + * Add hooks + */ + public function add_hooks() + { + // enable shortcodes in text widgets + add_filter('widget_text', 'shortcode_unautop'); + add_filter('widget_text', 'do_shortcode', 11); + + // enable shortcodes in form content + add_filter('nl4wp_form_content', 'do_shortcode'); + + add_action('init', array( $this, 'register_shortcode' )); + } + + /** + * Registers the [nl4wp_form] shortcode + */ + public function register_shortcode() + { + // register shortcodes + add_shortcode(self::SHORTCODE, array( $this, 'shortcode' )); + } + + /** + * @param array $attributes + * @param string $content + * @return string + */ + public function shortcode($attributes = array(), $content = '') + { + $default_attributes = array( + 'id' => '', + 'lists' => '', + 'email_type' => '', + 'element_id' => '', + 'element_class' => '', + ); + + $attributes = shortcode_atts( + $default_attributes, + $attributes, + self::SHORTCODE + ); + + $config = array( + 'element_id' => $attributes['element_id'], + 'lists' => $attributes['lists'], + 'email_type' => $attributes['email_type'], + 'element_class' => $attributes['element_class'], + ); + + return $this->output_form($attributes['id'], $config, false); + } + + /** + * @param int $id + * @param array $config + * @param bool $echo + * + * @return string + */ + public function output_form($id = 0, $config = array(), $echo = true) + { + try { + $form = nl4wp_get_form($id); + } catch (Exception $e) { + if (current_user_can('manage_options')) { + return sprintf('Newsletter for WordPress error: %s', $e->getMessage()); + } + + return ''; + } + + $this->count++; // set a default element_id if none is given - if( empty( $config['element_id'] ) ) { - $config['element_id'] = 'nl4wp-form-' . $this->count; - } - - $form_html = $form->get_html( $config['element_id'], $config ); - - try { - // start new output buffer - ob_start(); - - /** - * Runs just before a form element is outputted. - * - * @since 3.0 - * - * @param NL4WP_Form $form - */ - do_action( 'nl4wp_output_form', $form ); - - // output the form (in output buffer) - echo $form_html; - - // grab all contents in current output buffer & then clean + end it. - $html = ob_get_clean(); - } catch( Error $e ) { - $html = $form_html; - } - - // echo content if necessary - if( $echo ) { - echo $html; - } - - return $html; - } - + if (empty($config['element_id'])) { + $config['element_id'] = 'nl4wp-form-' . $this->count; + } + + $form_html = $form->get_html($config['element_id'], $config); + + try { + // start new output buffer + ob_start(); + + /** + * Runs just before a form element is outputted. + * + * @since 3.0 + * + * @param NL4WP_Form $form + */ + do_action('nl4wp_output_form', $form); + + // output the form (in output buffer) + echo $form_html; + + // grab all contents in current output buffer & then clean + end it. + $html = ob_get_clean(); + } catch (Error $e) { + $html = $form_html; + } + + // echo content if necessary + if ($echo) { + echo $html; + } + + return $html; + } } diff --git a/includes/forms/class-widget.php b/includes/forms/class-widget.php index 1123954..559a288 100755 --- a/includes/forms/class-widget.php +++ b/includes/forms/class-widget.php @@ -1,131 +1,131 @@ '', - 'form_id' => '' - ); - - /** - * Register widget with WordPress. - */ - function __construct() { - - // translate default widget title - $this->default_instance_settings['title'] = __( 'Newsletter', 'newsletter-for-wp' ); - - parent::__construct( - 'nl4wp_form_widget', // Base ID - __( 'Newsletter Sign-Up Form', 'newsletter-for-wp' ), // Name - array( - 'description' => __( 'Displays your Newsletter for WordPress sign-up form', 'newsletter-for-wp' ), - ) - ); - } - - /** - * Front-end display of widget. - * - * @see WP_Widget::widget() - * - * @param array $args Widget arguments. - * @param array $instance_settings Saved values from database. - */ - public function widget( $args, $instance_settings ) { - - // ensure $instance_settings is an array - if( ! is_array( $instance_settings ) ) { +class NL4WP_Form_Widget extends WP_Widget +{ + + /** + * @var array + */ + private $default_instance_settings = array( + 'title' => '', + 'form_id' => '' + ); + + /** + * Register widget with WordPress. + */ + public function __construct() + { + + // translate default widget title + $this->default_instance_settings['title'] = __('Newsletter', 'newsletter-for-wp'); + + parent::__construct( + 'nl4wp_form_widget', // Base ID + __('Newsletter Sign-Up Form', 'newsletter-for-wp'), // Name + array( + 'description' => __('Displays your Newsletter for WordPress sign-up form', 'newsletter-for-wp'), + ) + ); + } + + /** + * Front-end display of widget. + * + * @see WP_Widget::widget() + * + * @param array $args Widget arguments. + * @param array $instance_settings Saved values from database. + */ + public function widget($args, $instance_settings) + { + + // ensure $instance_settings is an array + if (! is_array($instance_settings)) { $instance_settings = array(); } - $instance_settings = array_merge( $this->default_instance_settings, $instance_settings ); - $title = apply_filters( 'widget_title', $instance_settings['title'] ); + $instance_settings = array_merge($this->default_instance_settings, $instance_settings); + $title = apply_filters('widget_title', $instance_settings['title']); - echo $args['before_widget']; + echo $args['before_widget']; - if ( ! empty( $title ) ) { - echo $args['before_title'] . $title . $args['after_title']; - } - - nl4wp_show_form( $instance_settings['form_id'] ); - - echo $args['after_widget']; - } - - /** - * Back-end widget form. - * - * @see WP_Widget::form() - * - * @param array $settings Previously saved values from database. - * - * @return string|void - */ - public function form( $settings ) { - $settings = array_merge( $this->default_instance_settings, (array) $settings ); + if (! empty($title)) { + echo $args['before_title'] . $title . $args['after_title']; + } - ?> + nl4wp_show_form($instance_settings['form_id']); + + echo $args['after_widget']; + } + + /** + * Back-end widget form. + * + * @see WP_Widget::form() + * + * @param array $settings Previously saved values from database. + * + * @return string|void + */ + public function form($settings) + { + $settings = array_merge($this->default_instance_settings, (array) $settings); ?>

- - + +

+ /** + * Runs right after the widget settings form is outputted + * + * @param array $settings + * @param NL4WP_Form_Widget $this + * @ignore + */ + do_action('nl4wp_form_widget_form', $settings, $this); ?>

- Newsletter for WordPress form settings.', 'newsletter-for-wp' ), admin_url( 'admin.php?page=newsletter-for-wp-forms' ) ); ?> + Newsletter for WordPress form settings.', 'newsletter-for-wp'), admin_url('admin.php?page=newsletter-for-wp-forms')); ?>

'publish', 'numberposts' => -1, ); - $args = array_merge( $default_args, $args ); + $args = array_merge($default_args, $args); $args['post_type'] = 'nl4wp-form'; - $posts = get_posts( $args ); + $posts = get_posts($args); $forms = array(); - foreach( $posts as $post ) { + foreach ($posts as $post) { try { - $form = nl4wp_get_form( $post ); - } catch( Exception $e ) { + $form = nl4wp_get_form($post); + } catch (Exception $e) { continue; } @@ -56,10 +58,11 @@ function nl4wp_get_forms( array $args = array() ) { * * @return string */ -function nl4wp_show_form( $form_id = 0, $config = array(), $echo = true ) { +function nl4wp_show_form($form_id = 0, $config = array(), $echo = true) +{ /** @var NL4WP_Form_Manager $forms */ $forms = nl4wp('forms'); - return $forms->output_form( $form_id, $config, $echo ); + return $forms->output_form($form_id, $config, $echo); } /** @@ -75,16 +78,16 @@ function nl4wp_show_form( $form_id = 0, $config = array(), $echo = true ) { * * @return boolean */ -function nl4wp_form_is_submitted( $form_id = 0, $element_id = null ) { - +function nl4wp_form_is_submitted($form_id = 0, $element_id = null) +{ try { - $form = nl4wp_get_form( $form_id ); - } catch( Exception $e ) { + $form = nl4wp_get_form($form_id); + } catch (Exception $e) { return false; } - if( $element_id ) { - $form_element = new NL4WP_Form_Element( $form, array( 'element_id' => $element_id ) ); + if ($element_id) { + $form_element = new NL4WP_Form_Element($form, array( 'element_id' => $element_id )); return $form_element->is_submitted; } @@ -101,11 +104,11 @@ function nl4wp_form_is_submitted( $form_id = 0, $element_id = null ) { * * @return string */ -function nl4wp_form_get_response_html( $form_id = 0 ) { - +function nl4wp_form_get_response_html($form_id = 0) +{ try { - $form = nl4wp_get_form( $form_id ); - } catch( Exception $e ) { + $form = nl4wp_get_form($form_id); + } catch (Exception $e) { return ''; } @@ -119,6 +122,7 @@ function nl4wp_form_get_response_html( $form_id = 0 ) { * * @return NL4WP_Form|null */ -function nl4wp_get_submitted_form() { +function nl4wp_get_submitted_form() +{ return nl4wp('forms')->get_submitted_form(); -} \ No newline at end of file +} diff --git a/includes/forms/views/add-form.php b/includes/forms/views/add-form.php index 046026f..3fe0ea8 100755 --- a/includes/forms/views/add-form.php +++ b/includes/forms/views/add-form.php @@ -1,4 +1,4 @@ - +
@@ -7,10 +7,10 @@

- +

-

+

@@ -18,46 +18,52 @@ - +

- +

- +
    - +
  • - +
- +

- connect with Newsletter?', 'newsletter-for-wp' ), admin_url( 'admin.php?page=newsletter-for-wp' ) ); ?> + connect with Newsletter?', 'newsletter-for-wp'), admin_url('admin.php?page=newsletter-for-wp')); ?>

- +
- + diff --git a/includes/forms/views/edit-form.php b/includes/forms/views/edit-form.php index 9dd05cd..677efca 100755 --- a/includes/forms/views/edit-form.php +++ b/includes/forms/views/edit-form.php @@ -45,11 +45,11 @@ ?> -

+

- + @@ -66,7 +66,7 @@ style="line-height: initial;">
- ID ) ) .'" size="'. ( strlen( $form->ID ) + 18 ) .'">' ); ?> + ID)) .'" size="'. (strlen($form->ID) + 18) .'">'); ?>
@@ -74,9 +74,9 @@
@@ -104,7 +104,7 @@ // end of .tab echo '
'; - endforeach; // foreach tabs ?> + endforeach; // foreach tabs?>
diff --git a/includes/forms/views/parts/add-fields-help.php b/includes/forms/views/parts/add-fields-help.php index 281ce8e..7b9bd0a 100755 --- a/includes/forms/views/parts/add-fields-help.php +++ b/includes/forms/views/parts/add-fields-help.php @@ -1,46 +1,48 @@ - +
-

+

- +

-

+

  1. - +

  2. - - + +

  3. - +

    - - + +

  4. diff --git a/includes/forms/views/parts/dynamic-content-tags.php b/includes/forms/views/parts/dynamic-content-tags.php index 04dd363..7ae0d9e 100755 --- a/includes/forms/views/parts/dynamic-content-tags.php +++ b/includes/forms/views/parts/dynamic-content-tags.php @@ -1,21 +1,21 @@ get_tags(); ?> -

    +

    - add some dynamic content to your form or success and error messages.', 'newsletter-for-wp' ), 'https://kb.mc4wp.com/using-variables-in-your-form-or-messages/' ) . ' ' . __( 'This allows you to personalise your form or response messages.', 'newsletter-for-wp' ); ?> + add some dynamic content to your form or success and error messages.', 'newsletter-for-wp'), 'https://kb.mc4wp.com/using-variables-in-your-form-or-messages/') . ' ' . __('This allows you to personalise your form or response messages.', 'newsletter-for-wp'); ?>

    - $config ) { - $tag = ! empty( $config['example'] ) ? $config['example'] : $tag; - ?> + $config) { + $tag = ! empty($config['example']) ? $config['example'] : $tag; ?> - +
    - -

    ' ); ?>

    + +

    '); ?>

    diff --git a/includes/forms/views/preview.php b/includes/forms/views/preview.php index 1c50d3d..9123d8c 100644 --- a/includes/forms/views/preview.php +++ b/includes/forms/views/preview.php @@ -1,5 +1,5 @@ 'raw' )); @@ -9,9 +9,9 @@ - - " /> +
    - +
    diff --git a/includes/forms/views/tabs/form-appearance.php b/includes/forms/views/tabs/form-appearance.php index f6daf41..8267e00 100755 --- a/includes/forms/views/tabs/form-appearance.php +++ b/includes/forms/views/tabs/form-appearance.php @@ -2,15 +2,15 @@ $theme = wp_get_theme(); $css_options = array( - '0' => sprintf( __( 'Inherit from %s theme', 'newsletter-for-wp' ), $theme->Name ), - 'basic' => __( 'Basic', 'newsletter-for-wp' ), - __( 'Form Themes', 'newsletter-for-wp' ) => array( - 'theme-light' => __( 'Light Theme', 'newsletter-for-wp' ), - 'theme-dark' => __( 'Dark Theme', 'newsletter-for-wp' ), - 'theme-red' => __( 'Red Theme', 'newsletter-for-wp' ), - 'theme-green' => __( 'Green Theme', 'newsletter-for-wp' ), - 'theme-blue' => __( 'Blue Theme', 'newsletter-for-wp' ), - ) + '0' => sprintf(__('Inherit from %s theme', 'newsletter-for-wp'), $theme->Name), + 'basic' => __('Basic', 'newsletter-for-wp'), + __('Form Themes', 'newsletter-for-wp') => array( + 'theme-light' => __('Light Theme', 'newsletter-for-wp'), + 'theme-dark' => __('Dark Theme', 'newsletter-for-wp'), + 'theme-red' => __('Red Theme', 'newsletter-for-wp'), + 'theme-green' => __('Green Theme', 'newsletter-for-wp'), + 'theme-blue' => __('Blue Theme', 'newsletter-for-wp'), + ) ); /** @@ -18,42 +18,42 @@ * * @ignore */ -$css_options = apply_filters( 'nl4wp_admin_form_css_options', $css_options ); +$css_options = apply_filters('nl4wp_admin_form_css_options', $css_options); ?> -

    +

    - + + /** @ignore */ + do_action('nl4wp_admin_form_after_appearance_settings_rows', $opts, $form); + ?>

    - +

    diff --git a/includes/forms/views/tabs/form-fields.php b/includes/forms/views/tabs/form-fields.php index dca9e0e..5b98d50 100755 --- a/includes/forms/views/tabs/form-fields.php +++ b/includes/forms/views/tabs/form-fields.php @@ -3,48 +3,48 @@ -

    +

    -

    +

    - +

    -

    - +
    - + -

    ID ) ) .'" size="'. ( strlen( $form->ID ) + 18 ) .'">' ); ?>

    +

    ID)) .'" size="'. (strlen($form->ID) + 18) .'">'); ?>

    - + diff --git a/includes/forms/views/tabs/form-messages.php b/includes/forms/views/tabs/form-messages.php index cbc3b86..13abe0a 100755 --- a/includes/forms/views/tabs/form-messages.php +++ b/includes/forms/views/tabs/form-messages.php @@ -1,92 +1,92 @@ - -

    +

    + /** @ignore */ + do_action('nl4wp_admin_form_before_messages_settings_rows', $opts, $form); + ?> - + - + - + - + - + - + - + - + 'nl4wp_form[settings][update_existing]', 'value' => 1 ); ?> - - + + + /** @ignore */ + do_action('nl4wp_admin_form_after_messages_settings_rows', array(), $form); + ?> diff --git a/includes/forms/views/tabs/form-settings.php b/includes/forms/views/tabs/form-settings.php index a45c5b2..c5e6c61 100755 --- a/includes/forms/views/tabs/form-settings.php +++ b/includes/forms/views/tabs/form-settings.php @@ -1,139 +1,155 @@ -

    +

    -

    +

    - -

    + +

    - -

    + +

    - -

    + +

    - -

    + +

    - -

    + +

    - -

    + +

    - -

    + +

    - -

    + +

    - -

    + +

    -

    ' . esc_html( '' ) . '' ); ?>

    +

    ' . esc_html('') . ''); ?>

    + /** @ignore */ + do_action('nl4wp_admin_form_after_newsletter_settings_rows', $opts, $form); + ?> - + + if (empty($lists)) { + ?> - + - + - + 'nl4wp_form[settings][update_existing]', 'value' => 1 ); ?> - - + + + + + + + + /** @ignore */ + do_action('nl4wp_admin_form_after_newsletter_settings_rows', $opts, $form); + ?>
    are you connected to Newsletter?', 'newsletter-for-wp' ), admin_url( 'admin.php?page=newsletter-for-wp' ) ); ?>are you connected to Newsletter?', 'newsletter-for-wp'), admin_url('admin.php?page=newsletter-for-wp')); ?>
      - +
    • - +
    -

    +

      -

    +

      -

    +

     

    - +

    + +

    + + +

    + +
    -

    +

    + /** @ignore */ + do_action('nl4wp_admin_form_before_behaviour_settings_rows', $opts, $form); + ?> - + - + + /** @ignore */ + do_action('nl4wp_admin_form_after_behaviour_settings_rows', $opts, $form); + ?>
     

    - +

    - +

    - 0 for no redirect. Otherwise, use complete (absolute) URLs, including http://.', 'newsletter-for-wp' ); ?> + 0 for no redirect. Otherwise, use complete (absolute) URLs, including http://.', 'newsletter-for-wp'); ?>

    - +

    diff --git a/includes/functions.php b/includes/functions.php index 19a5968..9766502 100755 --- a/includes/functions.php +++ b/includes/functions.php @@ -64,9 +64,10 @@ function nl4wp_get_options() * @since 4.2.6 * @return string */ -function nl4wp_get_api_key() { +function nl4wp_get_api_key() +{ // try to get from constant - if( defined( 'NL4WP_API_KEY' ) && constant( 'NL4WP_API_KEY' ) !== '' ) { + if (defined('NL4WP_API_KEY') && constant('NL4WP_API_KEY') !== '') { return NL4WP_API_KEY; } @@ -147,8 +148,9 @@ function nl4wp_get_debug_log() * * @return string */ -function nl4wp_get_request_url() { - global $wp; +function nl4wp_get_request_url() +{ + global $wp; // get requested url from global $wp object $site_request_uri = $wp->request; @@ -167,10 +169,10 @@ function nl4wp_get_request_url() { /** * Get current URL path. - * + * * @return string */ -function nl4wp_get_request_path() +function nl4wp_get_request_path() { return $_SERVER['REQUEST_URI']; } @@ -180,15 +182,15 @@ function nl4wp_get_request_path() * * @return string */ -function nl4wp_get_request_ip_address() +function nl4wp_get_request_ip_address() { - $headers = ( function_exists( 'apache_request_headers' ) ) ? apache_request_headers() : $_SERVER; + $headers = (function_exists('apache_request_headers')) ? apache_request_headers() : $_SERVER; - if ( array_key_exists( 'X-Forwarded-For', $headers ) && filter_var( $headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) { + if (array_key_exists('X-Forwarded-For', $headers) && filter_var($headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { return $headers['X-Forwarded-For']; } - if ( array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) && filter_var( $headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) { + if (array_key_exists('HTTP_X_FORWARDED_FOR', $headers) && filter_var($headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { return $headers['HTTP_X_FORWARDED_FOR']; } @@ -205,7 +207,6 @@ function nl4wp_get_request_ip_address() */ function nl4wp_sanitize_deep($value) { - if (is_scalar($value)) { // strip all HTML tags & whitespace $value = trim(strip_tags($value)); @@ -353,7 +354,6 @@ function nl4wp_add_name_data($data = array()) */ function nl4wp_get_email_type() { - $email_type = 'html'; /** @@ -450,17 +450,18 @@ function nl4wp_refresh_newsletter_lists() * @param mixed $default * @return mixed */ -function nl4wp_array_get( $array, $key, $default = null ) { - if ( is_null( $key ) ) { +function nl4wp_array_get($array, $key, $default = null) +{ + if (is_null($key)) { return $array; } - if ( isset( $array[$key] ) ) { + if (isset($array[$key])) { return $array[$key]; } - foreach (explode( '.', $key ) as $segment) { - if ( ! is_array( $array ) || ! array_key_exists( $segment, $array ) ) { + foreach (explode('.', $key) as $segment) { + if (! is_array($array) || ! array_key_exists($segment, $array)) { return $default; } diff --git a/includes/integrations/class-admin.php b/includes/integrations/class-admin.php index 4043e97..1eb6f60 100755 --- a/includes/integrations/class-admin.php +++ b/includes/integrations/class-admin.php @@ -6,191 +6,196 @@ * @ignore * @access private */ -class NL4WP_Integration_Admin { - - /** - * @var NL4WP_Integration_Manager - */ - protected $integrations; - - /** - * @var NL4WP_Newsletter - */ - protected $newsletter; - - /** - * @var NL4WP_Admin_Messages - */ - protected $messages; - - /** - * @param NL4WP_Integration_Manager $integrations - * @param NL4WP_Newsletter $newsletter - * @param NL4WP_Admin_Messages $messages - */ - public function __construct( NL4WP_Integration_Manager $integrations, NL4WP_Admin_Messages $messages, NL4WP_Newsletter $newsletter ) { - $this->integrations = $integrations; - $this->newsletter = $newsletter; - $this->messages = $messages; - } - - /** - * Add hooks - */ - public function add_hooks() { - add_action( 'admin_init', array( $this, 'register_setting' ) ); - add_action( 'nl4wp_admin_enqueue_assets', array( $this, 'enqueue_assets' ), 10, 2 ); - add_filter( 'nl4wp_admin_menu_items', array( $this, 'add_menu_item' ) ); - } - - /** - * Register settings - */ - public function register_setting() { - register_setting( 'nl4wp_integrations_settings', 'nl4wp_integrations', array( $this, 'save_integration_settings' ) ); - } - - /** - * Enqueue assets - * - * @param string $suffix - * @param string $page - * - * @return void - */ - public function enqueue_assets( $suffix, $page = '' ) { - - // only load on integrations pages - if( $page !== 'integrations' ) { - return; - } - - wp_register_script( 'nl4wp-integrations-admin', NL4WP_PLUGIN_URL . 'assets/js/integrations-admin' . $suffix . '.js', array( 'nl4wp-admin' ), NL4WP_VERSION, true ); - wp_enqueue_script( 'nl4wp-integrations-admin'); - } - - /** - * @param $items - * - * @return array - */ - public function add_menu_item( $items ) { - $items[] = array( - 'title' => __( 'Integrations', 'newsletter-for-wp' ), - 'text' => __( 'Integrations', 'newsletter-for-wp' ), - 'slug' => 'integrations', - 'callback' => array( $this, 'show_integrations_page' ), - 'position' => 20 - ); - - return $items; - } - - /** - * @param array $new_settings - * @return array - */ - public function save_integration_settings( array $new_settings ) { - - $integrations = $this->integrations->get_all(); - $current_settings = (array) get_option( 'nl4wp_integrations', array() ); - $settings = array(); - - foreach( $integrations as $slug => $integration ) { - $settings[ $slug ] = $this->parse_integration_settings( $slug, $current_settings, $new_settings ); - } - - return $settings; - } - - /** - * @since 3.0 - * @param $slug - * @param $current - * @param $new - * - * @return array - */ - protected function parse_integration_settings( $slug, $current, $new ) { - $settings = array(); - - // start with current settings - if( ! empty( $current[ $slug ] ) ) { - $settings = $current[ $slug ]; - } - - // if no new settings were given, return current settings. - if( empty( $new[ $slug ] ) ) { - return $settings; - } - - // merge new settings with currents (to allow passing partial setting arrays) - $settings = array_merge( $settings, $new[ $slug] ); - - // sanitize settings - $settings = $this->sanitize_integration_settings( $settings ); - - return $settings; - } - - /** - * @param array $settings - * - * @return array - */ - protected function sanitize_integration_settings( $settings ) { - - // filter null values from lists setting - if( ! empty( $settings['lists'] ) ) { - $settings['lists'] = array_filter( $settings['lists'] ); - } else { - $settings['lists'] = array(); - } - - return $settings; - } - - /** - * Show the Integration Settings page - * - * @internal - */ - public function show_integrations_page() { - - if( ! empty( $_GET['integration'] ) ) { - $this->show_integration_settings_page( $_GET['integration'] ); - return; - } - - // get all installed & enabled integrations - $enabled_integrations = $this->integrations->get_enabled_integrations(); - - // get all integrations but remove enabled integrations from the resulting array - $available_integrations = $this->integrations->get_all(); - $available_integrations = array_diff( $available_integrations, $enabled_integrations ); - - require dirname( __FILE__ ) . '/views/integrations.php'; - } - - /** - * @param string $slug - * - * @internal - */ - public function show_integration_settings_page( $slug ) { - - try { - $integration = $this->integrations->get( $slug ); - } catch( Exception $e ) { - echo sprintf( '

    Integration not found.

    No integration with slug %s was found.

    ', esc_html( $slug ) ); - return; - } - - $opts = $integration->options; - $lists = $this->newsletter->get_lists(); - - require dirname( __FILE__ ) . '/views/integration-settings.php'; - } - - +class NL4WP_Integration_Admin +{ + + /** + * @var NL4WP_Integration_Manager + */ + protected $integrations; + + /** + * @var NL4WP_Newsletter + */ + protected $newsletter; + + /** + * @var NL4WP_Admin_Messages + */ + protected $messages; + + /** + * @param NL4WP_Integration_Manager $integrations + * @param NL4WP_Newsletter $newsletter + * @param NL4WP_Admin_Messages $messages + */ + public function __construct(NL4WP_Integration_Manager $integrations, NL4WP_Admin_Messages $messages, NL4WP_Newsletter $newsletter) + { + $this->integrations = $integrations; + $this->newsletter = $newsletter; + $this->messages = $messages; + } + + /** + * Add hooks + */ + public function add_hooks() + { + add_action('admin_init', array( $this, 'register_setting' )); + add_action('nl4wp_admin_enqueue_assets', array( $this, 'enqueue_assets' ), 10, 2); + add_filter('nl4wp_admin_menu_items', array( $this, 'add_menu_item' )); + } + + /** + * Register settings + */ + public function register_setting() + { + register_setting('nl4wp_integrations_settings', 'nl4wp_integrations', array( $this, 'save_integration_settings' )); + } + + /** + * Enqueue assets + * + * @param string $suffix + * @param string $page + * + * @return void + */ + public function enqueue_assets($suffix, $page = '') + { + + // only load on integrations pages + if ($page !== 'integrations') { + return; + } + + wp_register_script('nl4wp-integrations-admin', NL4WP_PLUGIN_URL . 'assets/js/integrations-admin' . $suffix . '.js', array( 'nl4wp-admin' ), NL4WP_VERSION, true); + wp_enqueue_script('nl4wp-integrations-admin'); + } + + /** + * @param $items + * + * @return array + */ + public function add_menu_item($items) + { + $items[] = array( + 'title' => __('Integrations', 'newsletter-for-wp'), + 'text' => __('Integrations', 'newsletter-for-wp'), + 'slug' => 'integrations', + 'callback' => array( $this, 'show_integrations_page' ), + 'position' => 20 + ); + + return $items; + } + + /** + * @param array $new_settings + * @return array + */ + public function save_integration_settings(array $new_settings) + { + $integrations = $this->integrations->get_all(); + $current_settings = (array) get_option('nl4wp_integrations', array()); + $settings = array(); + + foreach ($integrations as $slug => $integration) { + $settings[ $slug ] = $this->parse_integration_settings($slug, $current_settings, $new_settings); + } + + return $settings; + } + + /** + * @since 3.0 + * @param $slug + * @param $current + * @param $new + * + * @return array + */ + protected function parse_integration_settings($slug, $current, $new) + { + $settings = array(); + + // start with current settings + if (! empty($current[ $slug ])) { + $settings = $current[ $slug ]; + } + + // if no new settings were given, return current settings. + if (empty($new[ $slug ])) { + return $settings; + } + + // merge new settings with currents (to allow passing partial setting arrays) + $settings = array_merge($settings, $new[ $slug]); + + // sanitize settings + $settings = $this->sanitize_integration_settings($settings); + + return $settings; + } + + /** + * @param array $settings + * + * @return array + */ + protected function sanitize_integration_settings($settings) + { + + // filter null values from lists setting + if (! empty($settings['lists'])) { + $settings['lists'] = array_filter($settings['lists']); + } else { + $settings['lists'] = array(); + } + + return $settings; + } + + /** + * Show the Integration Settings page + * + * @internal + */ + public function show_integrations_page() + { + if (! empty($_GET['integration'])) { + $this->show_integration_settings_page($_GET['integration']); + return; + } + + // get all installed & enabled integrations + $enabled_integrations = $this->integrations->get_enabled_integrations(); + + // get all integrations but remove enabled integrations from the resulting array + $integrations = $this->integrations->get_all(); + + require dirname(__FILE__) . '/views/integrations.php'; + } + + /** + * @param string $slug + * + * @internal + */ + public function show_integration_settings_page($slug) + { + try { + $integration = $this->integrations->get($slug); + } catch (Exception $e) { + echo sprintf('

    Integration not found.

    No integration with slug %s was found.

    ', esc_html($slug)); + return; + } + + $opts = $integration->options; + $lists = $this->newsletter->get_lists(); + + require dirname(__FILE__) . '/views/integration-settings.php'; + } } diff --git a/includes/integrations/class-integration-fixture.php b/includes/integrations/class-integration-fixture.php index 7260e6c..20268b6 100755 --- a/includes/integrations/class-integration-fixture.php +++ b/includes/integrations/class-integration-fixture.php @@ -6,93 +6,98 @@ * @since 3.0 * @ignore */ -class NL4WP_Integration_Fixture { +class NL4WP_Integration_Fixture +{ - /** - * @var string - */ - public $slug; + /** + * @var string + */ + public $slug; - /** - * @var string - */ - public $class; + /** + * @var string + */ + public $class; - /** - * @var bool - */ - public $enabled = false; + /** + * @var bool + */ + public $enabled = false; - /** - * @var bool - */ - public $enabled_by_default = true; + /** + * @var bool + */ + public $enabled_by_default = true; - /** - * @var NL4WP_Integration - */ - public $instance; + /** + * @var NL4WP_Integration + */ + public $instance; - /** - * @var array - */ - public $options; + /** + * @var array + */ + public $options; - /** - * @param string $slug - * @param string $class - * @param bool $enabled_by_default - * @param array $options - */ - public function __construct( $slug, $class, $enabled_by_default = false, $options = array() ) { - $this->slug = $slug; - $this->class = $class; - $this->enabled = $this->enabled_by_default = $enabled_by_default; - $this->options = $options; + /** + * @param string $slug + * @param string $class + * @param bool $enabled_by_default + * @param array $options + */ + public function __construct($slug, $class, $enabled_by_default = false, $options = array()) + { + $this->slug = $slug; + $this->class = $class; + $this->enabled = $this->enabled_by_default = $enabled_by_default; + $this->options = $options; - if( ! empty( $options['enabled'] ) ) { - $this->enabled = true; - } - } + if (! empty($options['enabled'])) { + $this->enabled = true; + } + } - /** - * Returns the actual instance - * - * @return NL4WP_Integration - */ - public function load() { - if( ! $this->instance instanceof NL4WP_Integration ) { - $this->instance = new $this->class( $this->slug, $this->options ); - } + /** + * Returns the actual instance + * + * @return NL4WP_Integration + */ + public function load() + { + if (! $this->instance instanceof NL4WP_Integration) { + $this->instance = new $this->class($this->slug, $this->options); + } - return $this->instance; - } + return $this->instance; + } - /** - * Tunnel everything to NL4WP_Integration class - * - * @param $name - * - * @return NL4WP_Integration - */ - public function __call( $name, $arguments ) { - return call_user_func_array( array( $this->load(), $name ), $arguments ); - } + /** + * Tunnel everything to NL4WP_Integration class + * + * @param $name + * + * @return NL4WP_Integration + */ + public function __call($name, $arguments) + { + return call_user_func_array(array( $this->load(), $name ), $arguments); + } - /** - * @param $name - * - * @return string - */ - public function __get( $name ) { - return $this->load()->$name; - } + /** + * @param $name + * + * @return string + */ + public function __get($name) + { + return $this->load()->$name; + } - /** - * @return string - */ - public function __toString() { - return $this->slug; - } - -} \ No newline at end of file + /** + * @return string + */ + public function __toString() + { + return $this->slug; + } +} diff --git a/includes/integrations/class-integration-manager.php b/includes/integrations/class-integration-manager.php index 65db634..2687a31 100755 --- a/includes/integrations/class-integration-manager.php +++ b/includes/integrations/class-integration-manager.php @@ -6,174 +6,185 @@ * @ignore * @access private */ -class NL4WP_Integration_Manager { - - /** - * @var NL4WP_Integration_Fixture[] - */ - protected $integrations = array(); - - /** - * @var NL4WP_Integration_Tags - */ - protected $tags; - - /** - * Constructor - */ - public function __construct() { - $this->tags = new NL4WP_Integration_Tags(); - } - - /** - * Add hooks - */ - public function add_hooks() { - add_action( 'after_setup_theme', array( $this, 'initialize' ) ); - - $this->tags->add_hooks(); - } - - - /** - * Add hooks - */ - public function initialize() { - /*** @var NL4WP_Integration_Fixture $integration */ - $enabled_integrations = $this->get_enabled_integrations(); - - foreach( $enabled_integrations as $integration ) { - $integration->load()->initialize(); - } - } - - /** - * Get an integration instance - * - * @return NL4WP_Integration_Fixture[] - * @throws Exception - */ - public function get_all() { - return $this->integrations; - } - - - /** - * Get an integration instance - * - * @param string $slug - * @return NL4WP_Integration - * @throws Exception - */ - public function get( $slug ) { - - if( ! isset( $this->integrations[ $slug ] ) ) { - throw new Exception( sprintf( "No integration with slug %s has been registered.", $slug ) ); - } - - return $this->integrations[ $slug ]->load(); - } - - /** - * Register a new integration class - * - * @param string $slug - * @param string $class - * @param bool $enabled - */ - public function register_integration( $slug, $class, $enabled = false ) { - $raw_options = $this->get_integration_options( $slug ); - $this->integrations[ $slug ] = new NL4WP_Integration_Fixture( $slug, $class, $enabled, $raw_options ); - } - - /** - * Deregister an integration class - * - * @param string $slug - */ - public function deregister_integration( $slug ) { - if( isset( $this->integrations[ $slug ] ) ) { - unset( $this->integrations[ $slug ] ); - } - } - - /** - * Checks whether a certain integration is enabled (in the settings) - * - * This is decoupled from the integration class itself as checking an array is way "cheaper" than instantiating an object - * - * @param NL4WP_Integration_Fixture $integration - * - * @return bool - */ - public function is_enabled( NL4WP_Integration_Fixture $integration ) { - return $integration->enabled; - } - - /** - * @param NL4WP_Integration $integration - * @return bool - */ - public function is_installed( $integration ) { - return $integration->is_installed(); - } - - /** - * Get the integrations which are enabled - * - * - Some integrations are always enabled because they need manual work - * - Other integrations can be enabled in the settings page - * - Only returns installed integrations - * - * @return array - */ - public function get_enabled_integrations() { - - // get all enabled integrations - $enabled_integrations = array_filter( $this->integrations, array( $this, 'is_enabled' ) ); - - // remove duplicate values, for whatever reason.. - $enabled_integrations = array_unique( $enabled_integrations ); - - // filter out integrations which are not installed - $installed_enabled_integrations = array_filter( $enabled_integrations, array( $this, 'is_installed' ) ); - - return $installed_enabled_integrations; - } - - /** +class NL4WP_Integration_Manager +{ + + /** + * @var NL4WP_Integration_Fixture[] + */ + protected $integrations = array(); + + /** + * @var NL4WP_Integration_Tags + */ + protected $tags; + + /** + * Constructor + */ + public function __construct() + { + $this->tags = new NL4WP_Integration_Tags(); + } + + /** + * Add hooks + */ + public function add_hooks() + { + add_action('after_setup_theme', array( $this, 'initialize' )); + + $this->tags->add_hooks(); + } + + + /** + * Add hooks + */ + public function initialize() + { + /*** @var NL4WP_Integration_Fixture $integration */ + $enabled_integrations = $this->get_enabled_integrations(); + + foreach ($enabled_integrations as $integration) { + $integration->load()->initialize(); + } + } + + /** + * Get an integration instance + * + * @return NL4WP_Integration_Fixture[] + * @throws Exception + */ + public function get_all() + { + return $this->integrations; + } + + + /** + * Get an integration instance + * + * @param string $slug + * @return NL4WP_Integration + * @throws Exception + */ + public function get($slug) + { + if (! isset($this->integrations[ $slug ])) { + throw new Exception(sprintf("No integration with slug %s has been registered.", $slug)); + } + + return $this->integrations[ $slug ]->load(); + } + + /** + * Register a new integration class + * + * @param string $slug + * @param string $class + * @param bool $enabled + */ + public function register_integration($slug, $class, $enabled = false) + { + $raw_options = $this->get_integration_options($slug); + $this->integrations[ $slug ] = new NL4WP_Integration_Fixture($slug, $class, $enabled, $raw_options); + } + + /** + * Deregister an integration class + * + * @param string $slug + */ + public function deregister_integration($slug) + { + if (isset($this->integrations[ $slug ])) { + unset($this->integrations[ $slug ]); + } + } + + /** + * Checks whether a certain integration is enabled (in the settings) + * + * This is decoupled from the integration class itself as checking an array is way "cheaper" than instantiating an object + * + * @param NL4WP_Integration_Fixture $integration + * + * @return bool + */ + public function is_enabled(NL4WP_Integration_Fixture $integration) + { + return $integration->enabled; + } + + /** + * @param NL4WP_Integration $integration + * @return bool + */ + public function is_installed($integration) + { + return $integration->is_installed(); + } + + /** + * Get the integrations which are enabled + * + * - Some integrations are always enabled because they need manual work + * - Other integrations can be enabled in the settings page + * - Only returns installed integrations + * + * @return array + */ + public function get_enabled_integrations() + { + + // get all enabled integrations + $enabled_integrations = array_filter($this->integrations, array( $this, 'is_enabled' )); + + // remove duplicate values, for whatever reason.. + $enabled_integrations = array_unique($enabled_integrations); + + // filter out integrations which are not installed + $installed_enabled_integrations = array_filter($enabled_integrations, array( $this, 'is_installed' )); + + return $installed_enabled_integrations; + } + + /** * Gets all integration options in a keyed array * - * @return array - */ - private function load_options() { - $options = (array) get_option( 'nl4wp_integrations', array() ); - - /** - * Filters global integration options - * - * This array holds ALL integration settings - * - * @since 3.0 - * @param array $options + * @return array + */ + private function load_options() + { + $options = (array) get_option('nl4wp_integrations', array()); + + /** + * Filters global integration options + * + * This array holds ALL integration settings + * + * @since 3.0 + * @param array $options * @ignore - */ - return (array) apply_filters( 'nl4wp_integration_options', $options ); - } - - /** - * Gets the raw options for an integration - * - * @param $slug - * @return array - */ - public function get_integration_options( $slug ) { - static $options; - if( $options === null ) { - $options = $this->load_options(); - } + */ + return (array) apply_filters('nl4wp_integration_options', $options); + } - return isset( $options[ $slug ] ) ? $options[ $slug ] : array(); - } + /** + * Gets the raw options for an integration + * + * @param $slug + * @return array + */ + public function get_integration_options($slug) + { + static $options; + if ($options === null) { + $options = $this->load_options(); + } -} \ No newline at end of file + return isset($options[ $slug ]) ? $options[ $slug ] : array(); + } +} diff --git a/includes/integrations/class-integration-tags.php b/includes/integrations/class-integration-tags.php index e4a448d..814d028 100755 --- a/includes/integrations/class-integration-tags.php +++ b/includes/integrations/class-integration-tags.php @@ -6,68 +6,74 @@ * @ignore * @access private */ -class NL4WP_Integration_Tags{ +class NL4WP_Integration_Tags +{ - /** - * @var NL4WP_Dynamic_Content_Tags - */ - protected $tags; + /** + * @var NL4WP_Dynamic_Content_Tags + */ + protected $tags; - /** - * @var NL4WP_Integration - */ - protected $integration; + /** + * @var NL4WP_Integration + */ + protected $integration; - /** - * Constructor - */ - public function __construct() { - $this->tags = new NL4WP_Dynamic_Content_Tags( 'integrations' ); - } + /** + * Constructor + */ + public function __construct() + { + $this->tags = new NL4WP_Dynamic_Content_Tags('integrations'); + } - /** - * Add hooks - */ - public function add_hooks() { - add_filter( 'nl4wp_dynamic_content_tags_integrations', array( $this, 'register' ) ); - add_filter( 'nl4wp_integration_checkbox_label', array( $this, 'replace' ), 10, 2 ); - } + /** + * Add hooks + */ + public function add_hooks() + { + add_filter('nl4wp_dynamic_content_tags_integrations', array( $this, 'register' )); + add_filter('nl4wp_integration_checkbox_label', array( $this, 'replace' ), 10, 2); + } - /** - * Register dynamic content tags for integrations - * - * @hooked `nl4wp_dynamic_content_tags_integrations` - * @param array $tags - * @return array - */ - public function register( array $tags ) { - $tags['subscriber_count'] = array( - 'description' => __( 'Replaced with the number of subscribers on the selected list(s)', 'newsletter-for-wp' ), - 'callback' => array( $this, 'get_subscriber_count' ) - ); - return $tags; - } + /** + * Register dynamic content tags for integrations + * + * @hooked `nl4wp_dynamic_content_tags_integrations` + * @param array $tags + * @return array + */ + public function register(array $tags) + { + $tags['subscriber_count'] = array( + 'description' => __('Replaced with the number of subscribers on the selected list(s)', 'newsletter-for-wp'), + 'callback' => array( $this, 'get_subscriber_count' ) + ); + return $tags; + } - /** - * @hooked `nl4wp_integration_checkbox_label` - * @param string $string - * @param NL4WP_Integration $integration - * @return string - */ - public function replace( $string, NL4WP_Integration $integration ) { - $this->integration = $integration; - $string = $this->tags->replace( $string ); - return $string; - } + /** + * @hooked `nl4wp_integration_checkbox_label` + * @param string $string + * @param NL4WP_Integration $integration + * @return string + */ + public function replace($string, NL4WP_Integration $integration) + { + $this->integration = $integration; + $string = $this->tags->replace($string); + return $string; + } /** * Returns the number of subscribers on the selected lists (for the form context) * * @return int */ - public function get_subscriber_count() { + public function get_subscriber_count() + { $newsletter = new NL4WP_Newsletter(); - $count = $newsletter->get_subscriber_count( $this->integration->get_lists() ); - return number_format( $count ); + $count = $newsletter->get_subscriber_count($this->integration->get_lists()); + return number_format($count); } -} \ No newline at end of file +} diff --git a/includes/integrations/class-integration.php b/includes/integrations/class-integration.php index b827784..fc8533a 100755 --- a/includes/integrations/class-integration.php +++ b/includes/integrations/class-integration.php @@ -11,235 +11,246 @@ * @since 3.0 * @abstract */ -abstract class NL4WP_Integration { - - /** - * @var string Name of this integration. - */ - public $name = ''; - - /** - * @var string Description - */ - public $description = ''; - - /** - * @var string Slug, used as an unique identifier for this integration. - */ - public $slug = ''; - - /** - * @var array Array of settings - */ - public $options = array(); - - /** - * @var string Name attribute for the checkbox element. Will be created from slug if empty. - */ - protected $checkbox_name = ''; - - /** - * Constructor - * - * @param string $slug - * @param array $options - */ - public function __construct( $slug, array $options ) { - $this->slug = $slug; - $this->options = $this->parse_options( $options ); - - // if checkbox name is not set, set a good custom value - if( empty( $this->checkbox_name ) ) { - $this->checkbox_name = '_nl4wp_subscribe_' . $this->slug; - } - } - - /** - * Return array of default options - * - * @return array - */ - protected function get_default_options() { - return array( - 'css' => 0, - 'double_optin' => 1, - 'enabled' => 0, - 'implicit' => 0, - 'label' => __( 'Sign me up for the newsletter!', 'newsletter-for-wp' ), - 'lists' => array(), - 'precheck' => 0, - 'replace_interests' => 0, - 'update_existing' => 0, - 'wrap_p' => 1 - ); - } - - /** - * @param array $options - * - * @return array - */ - protected function parse_options( array $options ) { - $slug = $this->slug; - - $default_options = $this->get_default_options(); - $options = array_merge( $default_options, $options ); - - /** - * @deprecated Use nl4wp_integration_{$slug}_options instead - */ - $options = (array) apply_filters( 'nl4wp_' . $slug . '_integration_options', $options ); - - /** - * Filters options for a specific integration - * - * The dynamic portion of the hook, `$slug`, refers to the slug of the ingration. - * - * @param array $integration_options - */ - return (array) apply_filters( 'nl4wp_integration_' . $slug . '_options', $options ); - } - - /** - * Initialize the integration - */ - public function initialize() { - $this->add_required_hooks(); - $this->add_hooks(); - } - - /** - * Adds the required hooks for core functionality, like adding checkbox reset CSS. - */ - protected function add_required_hooks() { - if( $this->options['css'] && ! $this->options['implicit'] ) { - add_action( 'wp_head', array( $this, 'print_css_reset' ) ); - } - } - - /** - * Was integration triggered? - * - * Will always return true when integration is implicit. Otherwise, will check value of checkbox. - * - * @param int $object_id Useful when overriding method. (optional) - * @return bool - */ - public function triggered( $object_id = null ) { - return $this->options['implicit'] || $this->checkbox_was_checked(); - } - - /** - * Adds the hooks which are specific to this integration - */ - abstract protected function add_hooks(); - - /** - * Print CSS reset - * - * @hooked `wp_head` - */ - public function print_css_reset() { - $suffix = defined( 'SCRIPT_DEBUG' ) ? '' : '.min'; - $css = file_get_contents( NL4WP_PLUGIN_DIR . 'assets/css/checkbox-reset' . $suffix . '.css' ); - - // replace selector by integration specific selector so the css affects just this checkbox - $css = str_ireplace( '__INTEGRATION_SLUG__', $this->slug, $css ); - - printf( '', $css ); - } - - /** - * Get the text for the label element - * - * @return string - */ - public function get_label_text() { - $integration = $this; - $label = $this->options['label']; - - /** - * Filters the checkbox label - * - * @since 3.0 - * - * @param string $label - * @param NL4WP_Integration $integration +abstract class NL4WP_Integration +{ + + /** + * @var string Name of this integration. + */ + public $name = ''; + + /** + * @var string Description + */ + public $description = ''; + + /** + * @var string Slug, used as an unique identifier for this integration. + */ + public $slug = ''; + + /** + * @var array Array of settings + */ + public $options = array(); + + /** + * @var string Name attribute for the checkbox element. Will be created from slug if empty. + */ + protected $checkbox_name = ''; + + /** + * Constructor + * + * @param string $slug + * @param array $options + */ + public function __construct($slug, array $options) + { + $this->slug = $slug; + $this->options = $this->parse_options($options); + + // if checkbox name is not set, set a good custom value + if (empty($this->checkbox_name)) { + $this->checkbox_name = '_nl4wp_subscribe_' . $this->slug; + } + } + + /** + * Return array of default options + * + * @return array + */ + protected function get_default_options() + { + return array( + 'css' => 0, + 'double_optin' => 1, + 'enabled' => 0, + 'implicit' => 0, + 'label' => __('Sign me up for the newsletter!', 'newsletter-for-wp'), + 'lists' => array(), + 'precheck' => 0, + 'replace_interests' => 0, + 'update_existing' => 0, + 'wrap_p' => 1 + ); + } + + /** + * @param array $options + * + * @return array + */ + protected function parse_options(array $options) + { + $slug = $this->slug; + + $default_options = $this->get_default_options(); + $options = array_merge($default_options, $options); + + /** + * @deprecated Use nl4wp_integration_{$slug}_options instead + */ + $options = (array) apply_filters('nl4wp_' . $slug . '_integration_options', $options); + + /** + * Filters options for a specific integration + * + * The dynamic portion of the hook, `$slug`, refers to the slug of the ingration. + * + * @param array $integration_options + */ + return (array) apply_filters('nl4wp_integration_' . $slug . '_options', $options); + } + + /** + * Initialize the integration + */ + public function initialize() + { + $this->add_required_hooks(); + $this->add_hooks(); + } + + /** + * Adds the required hooks for core functionality, like adding checkbox reset CSS. + */ + protected function add_required_hooks() + { + if ($this->options['css'] && ! $this->options['implicit']) { + add_action('wp_head', array( $this, 'print_css_reset' )); + } + } + + /** + * Was integration triggered? + * + * Will always return true when integration is implicit. Otherwise, will check value of checkbox. + * + * @param int $object_id Useful when overriding method. (optional) + * @return bool + */ + public function triggered($object_id = null) + { + return $this->options['implicit'] || $this->checkbox_was_checked(); + } + + /** + * Adds the hooks which are specific to this integration + */ + abstract protected function add_hooks(); + + /** + * Print CSS reset + * + * @hooked `wp_head` + */ + public function print_css_reset() + { + $suffix = defined('SCRIPT_DEBUG') ? '' : '.min'; + $css = file_get_contents(NL4WP_PLUGIN_DIR . 'assets/css/checkbox-reset' . $suffix . '.css'); + + // replace selector by integration specific selector so the css affects just this checkbox + $css = str_ireplace('__INTEGRATION_SLUG__', $this->slug, $css); + + printf('', $css); + } + + /** + * Get the text for the label element + * + * @return string + */ + public function get_label_text() + { + $integration = $this; + $label = $this->options['label']; + + /** + * Filters the checkbox label + * + * @since 3.0 + * + * @param string $label + * @param NL4WP_Integration $integration * @ignore - */ - $label = (string) apply_filters( 'nl4wp_integration_checkbox_label', $label, $integration ); - return $label; - } - - /** - * Was the integration checkbox checked? - * - * @return bool - */ - public function checkbox_was_checked() { - $data = $this->get_data(); - return ( isset( $data[ $this->checkbox_name ] ) && $data[ $this->checkbox_name ] == 1 ); - } - - /** - * Get a string of attributes for the checkbox element. - * - * @return string - */ - protected function get_checkbox_attributes() { - - $integration = $this; - $slug = $this->slug; - - $attributes = array(); - - if( $this->options['precheck'] ) { - $attributes['checked'] = 'checked'; - } - - /** - * Filters the attributes array. - * - * @param array $attributes - * @param NL4WP_Integration $integration + */ + $label = (string) apply_filters('nl4wp_integration_checkbox_label', $label, $integration); + return $label; + } + + /** + * Was the integration checkbox checked? + * + * @return bool + */ + public function checkbox_was_checked() + { + $data = $this->get_data(); + return (isset($data[ $this->checkbox_name ]) && $data[ $this->checkbox_name ] == 1); + } + + /** + * Get a string of attributes for the checkbox element. + * + * @return string + */ + protected function get_checkbox_attributes() + { + $integration = $this; + $slug = $this->slug; + + $attributes = array(); + + if ($this->options['precheck']) { + $attributes['checked'] = 'checked'; + } + + /** + * Filters the attributes array. + * + * @param array $attributes + * @param NL4WP_Integration $integration * @ignore - */ - $attributes = (array) apply_filters( 'nl4wp_integration_checkbox_attributes', $attributes, $integration ); - - /** - * Filters the attributes array. - * - * The dynamic portion of the hook, `$slug`, refers to the slug for this integration. - * - * @param array $attributes - * @param NL4WP_Integration $integration + */ + $attributes = (array) apply_filters('nl4wp_integration_checkbox_attributes', $attributes, $integration); + + /** + * Filters the attributes array. + * + * The dynamic portion of the hook, `$slug`, refers to the slug for this integration. + * + * @param array $attributes + * @param NL4WP_Integration $integration * @ignore - */ - $attributes = (array) apply_filters( 'nl4wp_integration_' . $slug . '_checkbox_attributes', $attributes, $integration ); + */ + $attributes = (array) apply_filters('nl4wp_integration_' . $slug . '_checkbox_attributes', $attributes, $integration); - $string = ''; - foreach( $attributes as $key => $value ) { - $string .= sprintf( '%s="%s"', $key, esc_attr( $value ) ); - } + $string = ''; + foreach ($attributes as $key => $value) { + $string .= sprintf('%s="%s"', $key, esc_attr($value)); + } - return $string; - } + return $string; + } - /** - * Outputs a checkbox - */ - public function output_checkbox() { + /** + * Outputs a checkbox + */ + public function output_checkbox() + { echo $this->get_checkbox_html(); - } - - /** - * Get HTML for the checkbox - * - * @return string - */ - public function get_checkbox_html() { - - $show_checkbox = empty( $this->options['implicit'] ); + } + + /** + * Get HTML for the checkbox + * + * @return string + */ + public function get_checkbox_html() + { + $show_checkbox = empty($this->options['implicit']); $integration_slug = $this->slug; /** @@ -248,305 +259,311 @@ public function get_checkbox_html() { * @param bool $show_checkbox * @param string $integration_slug */ - $show_checkbox = (bool) apply_filters( 'nl4wp_integration_show_checkbox', $show_checkbox, $integration_slug ); + $show_checkbox = (bool) apply_filters('nl4wp_integration_show_checkbox', $show_checkbox, $integration_slug); - if( ! $show_checkbox ) { + if (! $show_checkbox) { return ''; } - ob_start(); + ob_start(); - echo sprintf( '', NL4WP_VERSION ); + echo sprintf('', NL4WP_VERSION); /** @ignore */ - do_action( 'nl4wp_integration_before_checkbox_wrapper', $this ); + do_action('nl4wp_integration_before_checkbox_wrapper', $this); /** @ignore */ - do_action( 'nl4wp_integration_'. $this->slug .'_before_checkbox_wrapper', $this ); + do_action('nl4wp_integration_'. $this->slug .'_before_checkbox_wrapper', $this); $wrapper_tag = $this->options['wrap_p'] ? 'p' : 'span'; // Hidden field to make sure "0" is sent to server - echo sprintf( '', esc_attr( $this->checkbox_name ) ); + echo sprintf('', esc_attr($this->checkbox_name)); - echo sprintf( '<%s class="nl4wp-checkbox nl4wp-checkbox-%s">', $wrapper_tag, esc_attr( $this->slug ) ); + echo sprintf('<%s class="nl4wp-checkbox nl4wp-checkbox-%s">', $wrapper_tag, esc_attr($this->slug)); echo ''; - echo sprintf( '', $wrapper_tag ); + echo sprintf('', esc_attr($this->checkbox_name), $this->get_checkbox_attributes()); + echo sprintf('%s', $this->get_label_text()); + echo ''; + echo sprintf('', $wrapper_tag); /** @ignore */ - do_action( 'nl4wp_integration_after_checkbox_wrapper', $this ); + do_action('nl4wp_integration_after_checkbox_wrapper', $this); /** @ignore */ - do_action( 'nl4wp_integration_'. $this->slug .'_after_checkbox_wrapper', $this ); - echo ''; - - $html = ob_get_clean(); - return $html; - } - - /** - * Get the selected Newsletter lists - * - * @return array Array of List ID's - */ - public function get_lists() { - - $data = $this->get_data(); - $integration = $this; - $slug = $this->slug; - - // get checkbox lists options - $lists = $this->options['lists']; - - // get lists from request, if set. - if( ! empty( $data['_nl4wp_lists'] ) ) { - - $lists = $data['_nl4wp_lists']; - - // ensure lists is an array - if( ! is_array( $lists ) ) { - $lists = explode( ',', $lists ); - $lists = array_map( 'trim', $lists ); - } - } - - // allow plugins to filter final lists value - - /** - * This filter is documented elsewhere. - * - * @since 2.0 - * @see NL4WP_Form::get_lists - * @ignore - */ - $lists = (array) apply_filters( 'nl4wp_lists', $lists ); - - /** - * Filters the Newsletter lists this integration should subscribe to - * - * @since 3.0 - * - * @param array $lists - * @param NL4WP_Integration $integration - */ - $lists = (array) apply_filters( 'nl4wp_integration_lists', $lists, $integration ); - - /** - * Filters the Newsletter lists a specific integration should subscribe to - * - * The dynamic portion of the hook, `$slug`, refers to the slug of the integration. - * - * @since 3.0 - * - * @param array $lists - * @param NL4WP_Integration $integration - */ - $lists = (array) apply_filters( 'nl4wp_integration_' . $slug . '_lists', $lists, $integration ); - - return $lists; - } - - /** - * Makes a subscription request - * - * @param array $data - * @param int $related_object_id - * - * @return boolean - */ - protected function subscribe( array $data, $related_object_id = 0 ) { - - $integration = $this; - $slug = $this->slug; - $newsletter = new NL4WP_Newsletter(); - $log = $this->get_log(); - $list_ids = $this->get_lists(); - - /** @var NL4WP_Newsletter_Subscriber $subscriber */ - $subscriber = null; - $result = false; - - // validate lists - if( empty( $list_ids ) ) { - $log->warning( sprintf( '%s > No Newsletter lists were selected', $this->name ) ); - return false; - } - - /** - * Filters data for integration requests. - * - * @param array $data - */ - $data = apply_filters( 'nl4wp_integration_data', $data ); - - /** - * Filters data for a specific integration request. - * - * The dynamic portion of the hook, `$slug`, refers to the integration slug. - * - * @param array $data - * @param int $related_object_id - */ - $data = apply_filters( "nl4wp_integration_{$slug}_data", $data, $related_object_id ); - - /** - * @ignore - * @deprecated 4.0 - */ - $data = apply_filters( 'nl4wp_merge_vars', $data ); - - /** - * @deprecated 4.0 - * @ignore - */ - $data = apply_filters( 'nl4wp_integration_merge_vars', $data, $integration ); - - /** - * @deprecated 4.0 - * @ignore - */ - $data = apply_filters( "nl4wp_integration_{$slug}_merge_vars", $data, $integration ); - - $email_type = nl4wp_get_email_type(); - - $mapper = new NL4WP_List_Data_Mapper( $data, $list_ids ); - - /** @var NL4WP_Newsletter_Subscriber[] $map */ - $map = $mapper->map(); - - foreach( $map as $list_id => $subscriber ) { - $subscriber->status = $this->options['double_optin'] ? 'pending' : 'subscribed'; - $subscriber->email_type = $email_type; - $subscriber->ip_signup = nl4wp_get_request_ip_address(); - - /** @ignore (documented elsewhere) */ - $subscriber = apply_filters( 'nl4wp_subscriber_data', $subscriber ); - - /** - * Filters subscriber data before it is sent to Newsletter. Only fires for integration requests. - * - * @param NL4WP_Newsletter_Subscriber $subscriber - */ - $subscriber = apply_filters( 'nl4wp_integration_subscriber_data', $subscriber ); - - /** - * Filters subscriber data before it is sent to Newsletter. Only fires for integration requests. - * - * The dynamic portion of the hook, `$slug`, refers to the integration slug. - * - * @param NL4WP_Newsletter_Subscriber $subscriber - * @param int $related_object_id - */ - $subscriber = apply_filters( "nl4wp_integration_{$slug}_subscriber_data", $subscriber, $related_object_id ); - - $result = $newsletter->list_subscribe( $list_id, $subscriber->email_address, $subscriber->to_array(), $this->options['update_existing'], $this->options['replace_interests'] ); - } - - // if result failed, show error message - if( ! $result ) { - - // log error - if( $newsletter->get_error_code() == 214 ) { - $log->warning( sprintf( "%s > %s is already subscribed to the selected list(s)", $this->name, $subscriber->email_address ) ); - } else { - $log->error( sprintf( '%s > Newsletter API Error: %s', $this->name, $newsletter->get_error_message() ) ); - } - - // bail - return false; - } - - $log->info( sprintf( '%s > Successfully subscribed %s', $this->name, $subscriber->email_address ) ); - - /** - * Runs right after someone is subscribed using an integration - * - * @since 3.0 - * - * @param NL4WP_Integration $integration - * @param string $email_address - * @param array $merge_vars - * @param NL4WP_Newsletter_Subscriber[] $subscriber_data - * @param int $related_object_id - */ - do_action( 'nl4wp_integration_subscribed', $integration, $subscriber->email_address, $subscriber->merge_fields, $map, $related_object_id ); - - return $result; - } - - /** - * Are the required dependencies for this integration installed? - * - * @return bool - */ - public function is_installed() { - return false; - } - - /** - * Which UI elements should we show on the settings page for this integration? - * - * @return array - */ - public function get_ui_elements() { - return array_keys( $this->options ); - } - - /** - * Does integration have the given UI element? - * - * @param $element - * @return bool - */ - public function has_ui_element( $element ) { - $elements = $this->get_ui_elements(); - return in_array( $element, $elements ); - } - - /** - * Return a string to the admin settings page for this object (if any) - * - * @param int $object_id - * @return string - */ - public function get_object_link( $object_id ) { - return ''; - } - - /** - * Get the data for this integration request - * - * By default, this will return a combination of all $_GET and $_POST parameters. - * Override this method if you need data from somewhere else. - * - * This data should contain the value of the checkbox (required) - * and the lists to which should be subscribed (optional) - * - * @see NL4WP_Integration::$checkbox_name - * @see NL4WP_Integration::get_lists - * @see NL4WP_Integration::checkbox_was_checked - * - * @return array - */ - public function get_data() { - $data = array_merge( (array) $_GET, (array) $_POST ); - return $data; - } - - /** - * @return NL4WP_Debug_Log - */ - protected function get_log() { - return nl4wp('log'); - } - - /** - * @return NL4WP_API_v3 - */ - protected function get_api() { - return nl4wp('api'); - } + do_action('nl4wp_integration_'. $this->slug .'_after_checkbox_wrapper', $this); + echo ''; + + $html = ob_get_clean(); + return $html; + } + + /** + * Get the selected Newsletter lists + * + * @return array Array of List ID's + */ + public function get_lists() + { + $data = $this->get_data(); + $integration = $this; + $slug = $this->slug; + + // get checkbox lists options + $lists = $this->options['lists']; + + // get lists from request, if set. + if (! empty($data['_nl4wp_lists'])) { + $lists = $data['_nl4wp_lists']; + + // ensure lists is an array + if (! is_array($lists)) { + $lists = explode(',', $lists); + $lists = array_map('trim', $lists); + } + } + + // allow plugins to filter final lists value + + /** + * This filter is documented elsewhere. + * + * @since 2.0 + * @see NL4WP_Form::get_lists + * @ignore + */ + $lists = (array) apply_filters('nl4wp_lists', $lists); + + /** + * Filters the Newsletter lists this integration should subscribe to + * + * @since 3.0 + * + * @param array $lists + * @param NL4WP_Integration $integration + */ + $lists = (array) apply_filters('nl4wp_integration_lists', $lists, $integration); + + /** + * Filters the Newsletter lists a specific integration should subscribe to + * + * The dynamic portion of the hook, `$slug`, refers to the slug of the integration. + * + * @since 3.0 + * + * @param array $lists + * @param NL4WP_Integration $integration + */ + $lists = (array) apply_filters('nl4wp_integration_' . $slug . '_lists', $lists, $integration); + + return $lists; + } + + /** + * Makes a subscription request + * + * @param array $data + * @param int $related_object_id + * + * @return boolean + */ + protected function subscribe(array $data, $related_object_id = 0) + { + $integration = $this; + $slug = $this->slug; + $newsletter = new NL4WP_Newsletter(); + $log = $this->get_log(); + $list_ids = $this->get_lists(); + + /** @var NL4WP_Newsletter_Subscriber $subscriber */ + $subscriber = null; + $result = false; + + // validate lists + if (empty($list_ids)) { + $log->warning(sprintf('%s > No Newsletter lists were selected', $this->name)); + return false; + } + + /** + * Filters data for integration requests. + * + * @param array $data + */ + $data = apply_filters('nl4wp_integration_data', $data); + + /** + * Filters data for a specific integration request. + * + * The dynamic portion of the hook, `$slug`, refers to the integration slug. + * + * @param array $data + * @param int $related_object_id + */ + $data = apply_filters("nl4wp_integration_{$slug}_data", $data, $related_object_id); + + /** + * @ignore + * @deprecated 4.0 + */ + $data = apply_filters('nl4wp_merge_vars', $data); + + /** + * @deprecated 4.0 + * @ignore + */ + $data = apply_filters('nl4wp_integration_merge_vars', $data, $integration); + + /** + * @deprecated 4.0 + * @ignore + */ + $data = apply_filters("nl4wp_integration_{$slug}_merge_vars", $data, $integration); + + $email_type = nl4wp_get_email_type(); + + $mapper = new NL4WP_List_Data_Mapper($data, $list_ids); + + /** @var NL4WP_Newsletter_Subscriber[] $map */ + $map = $mapper->map(); + + foreach ($map as $list_id => $subscriber) { + $subscriber->status = $this->options['double_optin'] ? 'pending' : 'subscribed'; + $subscriber->email_type = $email_type; + $subscriber->ip_signup = nl4wp_get_request_ip_address(); + + /** @ignore (documented elsewhere) */ + $subscriber = apply_filters('nl4wp_subscriber_data', $subscriber); + + /** + * Filters subscriber data before it is sent to Newsletter. Only fires for integration requests. + * + * @param NL4WP_Newsletter_Subscriber $subscriber + */ + $subscriber = apply_filters('nl4wp_integration_subscriber_data', $subscriber); + + /** + * Filters subscriber data before it is sent to Newsletter. Only fires for integration requests. + * + * The dynamic portion of the hook, `$slug`, refers to the integration slug. + * + * @param NL4WP_Newsletter_Subscriber $subscriber + * @param int $related_object_id + */ + $subscriber = apply_filters("nl4wp_integration_{$slug}_subscriber_data", $subscriber, $related_object_id); + + $result = $newsletter->list_subscribe($list_id, $subscriber->email_address, $subscriber->to_array(), $this->options['update_existing'], $this->options['replace_interests']); + } + + // if result failed, show error message + if (! $result) { + + // log error + if ($newsletter->get_error_code() == 214) { + $log->warning(sprintf("%s > %s is already subscribed to the selected list(s)", $this->name, $subscriber->email_address)); + } else { + $log->error(sprintf('%s > Newsletter API Error: %s', $this->name, $newsletter->get_error_message())); + } + + // bail + return false; + } + + $log->info(sprintf('%s > Successfully subscribed %s', $this->name, $subscriber->email_address)); + + /** + * Runs right after someone is subscribed using an integration + * + * @since 3.0 + * + * @param NL4WP_Integration $integration + * @param string $email_address + * @param array $merge_vars + * @param NL4WP_Newsletter_Subscriber[] $subscriber_data + * @param int $related_object_id + */ + do_action('nl4wp_integration_subscribed', $integration, $subscriber->email_address, $subscriber->merge_fields, $map, $related_object_id); + + return $result; + } + + /** + * Are the required dependencies for this integration installed? + * + * @return bool + */ + public function is_installed() + { + return false; + } + + /** + * Which UI elements should we show on the settings page for this integration? + * + * @return array + */ + public function get_ui_elements() + { + return array_keys($this->options); + } + + /** + * Does integration have the given UI element? + * + * @param $element + * @return bool + */ + public function has_ui_element($element) + { + $elements = $this->get_ui_elements(); + return in_array($element, $elements); + } + + /** + * Return a string to the admin settings page for this object (if any) + * + * @param int $object_id + * @return string + */ + public function get_object_link($object_id) + { + return ''; + } + + /** + * Get the data for this integration request + * + * By default, this will return a combination of all $_GET and $_POST parameters. + * Override this method if you need data from somewhere else. + * + * This data should contain the value of the checkbox (required) + * and the lists to which should be subscribed (optional) + * + * @see NL4WP_Integration::$checkbox_name + * @see NL4WP_Integration::get_lists + * @see NL4WP_Integration::checkbox_was_checked + * + * @return array + */ + public function get_data() + { + $data = array_merge((array) $_GET, (array) $_POST); + return $data; + } + + /** + * @return NL4WP_Debug_Log + */ + protected function get_log() + { + return nl4wp('log'); + } + + /** + * @return NL4WP_API_v3 + */ + protected function get_api() + { + return nl4wp('api'); + } } diff --git a/includes/integrations/class-user-integration.php b/includes/integrations/class-user-integration.php index 5c762dc..6ea4fa6 100755 --- a/includes/integrations/class-user-integration.php +++ b/includes/integrations/class-user-integration.php @@ -1,6 +1,6 @@ $user->user_email, - 'NAME' => $user->user_login, - ); + 'EMAIL' => $user->user_email, + 'NAME' => $user->user_login, + ); - if( '' !== $user->first_name ) { + if ('' !== $user->first_name) { $data['NAME'] = $user->first_name; $data['FNAME'] = $user->first_name; - } + } - if( '' !== $user->last_name ) { + if ('' !== $user->last_name) { $data['LNAME'] = $user->last_name; - } + } - if( '' !== $user->first_name && '' !== $user->last_name ) { - $data['NAME'] = sprintf( '%s %s', $user->first_name, $user->last_name ); - } + if ('' !== $user->first_name && '' !== $user->last_name) { + $data['NAME'] = sprintf('%s %s', $user->first_name, $user->last_name); + } - /** - * @since 3.0 - * @deprecated 4.0 + /** + * @since 3.0 + * @deprecated 4.0 * @ignore - */ - $data = (array) apply_filters( 'nl4wp_user_merge_vars', $data, $user ); - - return $data; - } + */ + $data = (array) apply_filters('nl4wp_user_merge_vars', $data, $user); -} \ No newline at end of file + return $data; + } +} diff --git a/includes/integrations/functions.php b/includes/integrations/functions.php index 8b7a408..3ca3862 100755 --- a/includes/integrations/functions.php +++ b/includes/integrations/functions.php @@ -8,8 +8,9 @@ * * @return NL4WP_Integration[] */ -function nl4wp_get_integrations() { - return nl4wp('integrations')->get_all(); +function nl4wp_get_integrations() +{ + return nl4wp('integrations')->get_all(); } /** @@ -22,8 +23,9 @@ function nl4wp_get_integrations() { * * @return NL4WP_Integration */ -function nl4wp_get_integration( $slug ) { - return nl4wp('integrations')->get( $slug ); +function nl4wp_get_integration($slug) +{ + return nl4wp('integrations')->get($slug); } /** @@ -37,8 +39,9 @@ function nl4wp_get_integration( $slug ) { * * @param bool $always_enabled */ -function nl4wp_register_integration( $slug, $class, $always_enabled = false ) { - return nl4wp('integrations')->register_integration( $slug, $class, $always_enabled ); +function nl4wp_register_integration($slug, $class, $always_enabled = false) +{ + return nl4wp('integrations')->register_integration($slug, $class, $always_enabled); } /** @@ -48,6 +51,7 @@ function nl4wp_register_integration( $slug, $class, $always_enabled = false ) { * @access public * @param string $slug */ -function nl4wp_deregister_integration( $slug ) { - nl4wp('integrations')->deregister_integration( $slug ); -} \ No newline at end of file +function nl4wp_deregister_integration($slug) +{ + nl4wp('integrations')->deregister_integration($slug); +} diff --git a/includes/integrations/views/integration-settings.php b/includes/integrations/views/integration-settings.php index 2f226f4..d08cfdb 100755 --- a/includes/integrations/views/integration-settings.php +++ b/includes/integrations/views/integration-settings.php @@ -1,14 +1,14 @@ -
    @@ -17,14 +17,14 @@

    - name ) ); ?> + name)); ?>

    @@ -33,209 +33,220 @@

    - - + + slug . '_integration_settings', $integration, $opts ); - ?> + /** + * Runs just before integration settings are outputted in admin. + * + * @since 3.0 + * + * @param NL4WP_Integration $integration + * @param array $opts + * @ignore + */ + do_action('nl4wp_admin_before_integration_settings', $integration, $opts); + + /** + * @ignore + */ + do_action('nl4wp_admin_before_' . $integration->slug . '_integration_settings', $integration, $opts); + ?> - has_ui_element( 'enabled' ) ) { ?> + has_ui_element('enabled')) { + ?> - + - + 'nl4wp_integrations['. $integration->slug .'][enabled]', 'value' => '1', 'hide' => false ); ?> - + - has_ui_element( 'implicit' ) ) { ?> + has_ui_element('implicit')) { + ?> - + - + - has_ui_element( 'lists' ) ) { - ?> - + has_ui_element('lists')) { + ?> + - - '; - echo '
      '; - foreach( $lists as $list ) { - echo '
    • '; - } - echo '
    '; - - echo '

    '; - _e( 'Select the list(s) to which people who check the checkbox should be subscribed.' ,'newsletter-for-wp' ); - echo '

    '; - echo ''; - } else { - echo ''; - } ?> + + '; + echo '
      '; + foreach ($lists as $list) { + echo '
    • '; + } + echo '
    '; + + echo '

    '; + _e('Select the list(s) to which people who check the checkbox should be subscribed.', 'newsletter-for-wp'); + echo '

    '; + echo ''; + } else { + echo ''; + } ?> - + - has_ui_element( 'label' ) ) { - $config = array( 'element' => 'nl4wp_integrations['. $integration->slug .'][implicit]', 'value' => 0 ); - ?> - - + has_ui_element('label')) { + $config = array( 'element' => 'nl4wp_integrations['. $integration->slug .'][implicit]', 'value' => 0 ); ?> + + - + - has_ui_element( 'precheck' ) ) { - $config = array( 'element' => 'nl4wp_integrations['. $integration->slug .'][implicit]', 'value' => 0 ); - ?> - - + has_ui_element('precheck')) { + $config = array( 'element' => 'nl4wp_integrations['. $integration->slug .'][implicit]', 'value' => 0 ); ?> + + - + - has_ui_element( 'css' ) ) { - $config = array( 'element' => 'nl4wp_integrations['. $integration->slug .'][implicit]', 'value' => 0 ); - ?> - - + has_ui_element('css')) { + $config = array( 'element' => 'nl4wp_integrations['. $integration->slug .'][implicit]', 'value' => 0 ); ?> + + - + - has_ui_element( 'double_optin' ) ) { ?> + has_ui_element('double_optin')) { + ?> - + - + - has_ui_element( 'update_existing' ) ) { ?> + has_ui_element('update_existing')) { + ?> - + - + - has_ui_element( 'replace_interests' ) ) { - $config = array( 'element' => 'nl4wp_integrations['. $integration->slug .'][update_existing]', 'value' => 1 ); - ?> - - + has_ui_element('replace_interests')) { + $config = array( 'element' => 'nl4wp_integrations['. $integration->slug .'][update_existing]', 'value' => 1 ); ?> + + - +
    -   - -

    name ); ?>

    +   + +

    name); ?>

    -   -
    ' . sprintf( __( 'No lists found, are you connected to Newsletter?', 'newsletter-for-wp' ), admin_url( 'admin.php?page=newsletter-for-wp' ) ) . '' . sprintf(__('No lists found, are you connected to Newsletter?', 'newsletter-for-wp'), admin_url('admin.php?page=newsletter-for-wp')) . '
    - -

    ' . esc_html( '' ) . '' ); ?>

    + +

    ' . esc_html('') . ''); ?>

    -   - +   +

    - '; - printf( __( 'Warning: enabling this may affect your GDPR compliance.', 'newsletter-for-wp' ), 'https://kb.mc4wp.com/gdpr-compliance/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=integrations-page' ); ?> + '; + printf(__('Warning: enabling this may affect your GDPR compliance.', 'newsletter-for-wp'), 'https://kb.mc4wp.com/gdpr-compliance/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=integrations-page'); ?>

    -   - -

    +   + +

     

    - +

      -

    +

     

    - - ' . __( 'What does this do?', 'newsletter-for-wp' ) . '', 'https://kb.mc4wp.com/what-does-replace-groupings-mean/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=integrations-page' ); ?> + + ' . __('What does this do?', 'newsletter-for-wp') . '', 'https://kb.mc4wp.com/what-does-replace-groupings-mean/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=integrations-page'); ?>

    slug . '_integration_settings', $integration, $opts ); - ?> - - get_ui_elements() ) > 0 ) { submit_button(); } ?> + /** + * Runs right after integration settings are outputted (before the submit button). + * + * @param NL4WP_Integration $integration + * @param array $opts + * @ignore + */ + do_action('nl4wp_admin_after_integration_settings', $integration, $opts); + + /** + * @ignore + */ + do_action('nl4wp_admin_after_' . $integration->slug . '_integration_settings', $integration, $opts); + ?> + + get_ui_elements()) > 0) { + submit_button(); + } ?> diff --git a/includes/integrations/views/integrations.php b/includes/integrations/views/integrations.php index d2b9c71..ac5be82 100755 --- a/includes/integrations/views/integrations.php +++ b/includes/integrations/views/integrations.php @@ -1,51 +1,87 @@ - + + + + + + is_installed()) { + printf('%s', esc_attr(add_query_arg(array( 'integration' => $integration->slug ))), __('Configure this integration', 'newsletter-for-wp'), $integration->name); + } else { + echo $integration->name; + } ?> + + + + + description, 'newsletter-for-wp'); ?> + + + enabled && $integration->is_installed()) { + echo '' . __('Active', 'newsletter-for-wp') . ''; + } elseif( $integration->is_installed()) { + echo '' . __('Inactive', 'newsletter-for-wp') . ''; + } else { + echo '' . __('Not installed', 'newsletter-for-wp') . ''; + } + ?> + + + +function _nl4wp_integrations_table($integrations) +{ + ?> - - + + + - is_installed(); - ?> - - - - - - - + is_installed() && $integration->enabled) { + _nl4wp_integrations_table_row($integration); + } + } + + // active & disabled integrations next + foreach ($integrations as $integration) { + if( $integration->is_installed() && ! $integration->enabled) { + _nl4wp_integrations_table_row($integration); + } + } + + // rest + foreach ($integrations as $integration) { + if( ! $integration->is_installed() && ! $integration->enabled) { + _nl4wp_integrations_table_row($integration); + } + } + ?>
    - - %s', esc_attr( add_query_arg( array( 'integration' => $integration->slug ) ) ), __( 'Configure this integration', 'newsletter-for-wp' ), $integration->name ); - } else { - echo $integration->name; - } ?> - - - - description, 'newsletter-for-wp'); - ?> -
    @@ -64,28 +100,24 @@ function _nl4wp_integrations_table( $integrations ) {
    -

    +

    - - + +

    -
    - - + -

    - + -
    +

    + -

    - -

    +

    diff --git a/includes/newsletter/class-interest-category.php b/includes/newsletter/class-interest-category.php index 5f90d89..0b13fd1 100755 --- a/includes/newsletter/class-interest-category.php +++ b/includes/newsletter/class-interest-category.php @@ -1,87 +1,90 @@ id = $id; - $this->name = $name; - $this->field_type = $field_type; - $this->interests = $interests; - } + /** + * @param int $id + * @param string $name + * @param string $field_type + * @param array $interests + */ + public function __construct($id, $name, $field_type, $interests = array()) + { + $this->id = $id; + $this->name = $name; + $this->field_type = $field_type; + $this->interests = $interests; + } - /** - * @param string $name - * - * @return array|string[] - */ - public function __get( $name ) { - // for backwards compatibility with v3.x, channel these properties to their new names - if( $name === 'groups' ) { - return $this->interests; - } - } + /** + * @param string $name + * + * @return array|string[] + */ + public function __get($name) + { + // for backwards compatibility with v3.x, channel these properties to their new names + if ($name === 'groups') { + return $this->interests; + } + } - /** - * @param object $data - * - * @return NL4WP_Newsletter_Interest_Category - */ - public static function from_data( $data ) { - $instance = new self( $data->id, $data->title, $data->type ); - return $instance; - } + /** + * @param object $data + * + * @return NL4WP_Newsletter_Interest_Category + */ + public static function from_data($data) + { + $instance = new self($data->id, $data->title, $data->type); + return $instance; + } - /** - * @since 4.0 - * - * @param string $interest_id - * @return string - * - * @throws Exception - */ - public function get_interest_name_by_id( $interest_id ) { - foreach( $this->interests as $id => $name ) { - if( $id != $interest_id ) { - continue; - } + /** + * @since 4.0 + * + * @param string $interest_id + * @return string + * + * @throws Exception + */ + public function get_interest_name_by_id($interest_id) + { + foreach ($this->interests as $id => $name) { + if ($id != $interest_id) { + continue; + } - return $name; - } + return $name; + } - throw new Exception( sprintf( 'No interest with ID %s', $interest_id ) ); - } -} \ No newline at end of file + throw new Exception(sprintf('No interest with ID %s', $interest_id)); + } +} diff --git a/includes/newsletter/class-list.php b/includes/newsletter/class-list.php index 76280f1..e5597fc 100755 --- a/includes/newsletter/class-list.php +++ b/includes/newsletter/class-list.php @@ -1,183 +1,186 @@ id = $id; - $this->name = $name; - $this->web_id = $web_id; - - // add email field - $email_field = new NL4WP_Newsletter_Merge_Field( 'Email Address', 'email', 'EMAIL', true ); - $this->merge_fields[] = $email_field; - } - - /** - * @param string $name - * - * @return mixed - */ - public function __get( $name ) { - // for backwards compatibility with 3.x, channel these properties to their new names - if( $name === 'merge_vars' ) { - return $this->merge_fields; - } elseif( $name === 'groupings' ) { - return $this->interest_categories; - } - } - - /** - * @param string $tag - * @return NL4WP_Newsletter_Merge_Field - * - * @throws Exception - */ - public function get_field_by_tag( $tag ) { - // ensure uppercase tagname - $tag = strtoupper( $tag ); - - // search merge vars - foreach( $this->merge_fields as $field ) { - - if( $field->tag !== $tag ) { - continue; - } - - return $field; - } - - throw new Exception( 'Field tag not found.' ); - } - - /** - * - * @since 4.0 - * - * @param string $interest_id - * @return NL4WP_Newsletter_Interest_Category - * - * @throws Exception - */ - public function get_interest_category_by_interest_id( $interest_id ) { - - foreach( $this->interest_categories as $category ) { - foreach( $category->interests as $id => $name ) { - if( $id != $interest_id ) { - continue; - } - - return $category; - } - } - - throw new Exception( sprintf( 'No interest with ID %s', $interest_id ) ); - } - - /** - * Get the interest grouping object for a given list. - * - * @param string $category_id ID of the Interest Grouping - * - * @return NL4WP_Newsletter_Interest_Category - * - * @throws Exception - */ - public function get_interest_category( $category_id ) { - - foreach( $this->interest_categories as $category ) { - - if( $category->id !== $category_id ) { - continue; - } - - return $category; - } - - throw new Exception( sprintf( 'No interest category with ID %s', $category_id ) ); - } - - /** - * Get link to this list in Newsletter - * - * @return string - */ - public function get_web_url() { - return 'https://admin.newsletter.com/lists/members/?id=' . $this->web_id; - } - - /** - * Get the name of an interest category by its ID - * - * @deprecated 4.0 - * @use NL4WP_Newsletter_List::get_interest_category - * - * @param string $category_id - * - * @return string - */ - public function get_interest_category_name( $category_id ) { - $category = $this->get_interest_category( $category_id ); - return $category->name; - } - - /** - * @deprecated 4.0 - * @use NL4WP_Newsletter_List::get_field_by_tag - * - * @param string $tag - * - * @return string - */ - public function get_field_name_by_tag( $tag ) { - $field = $this->get_field_by_tag( $tag ); - return $field->name; - } - +class NL4WP_Newsletter_List +{ + + /** + * @var string ID of this list for API usage + */ + public $id; + + /** + * @var string Web ID of this list in Newsletter.com + */ + public $web_id = ''; + + /** + * @var string Name of this list + */ + public $name; + + /** + * @var int Number of subscribers on this list + */ + public $subscriber_count = 0; + + /** + * @var NL4WP_Newsletter_Merge_Field[] + */ + public $merge_fields = array(); + + /** + * @var NL4WP_Newsletter_Interest_Category[] + */ + public $interest_categories = array(); + + /** + * @var object + */ + public $campaign_defaults; + + /** + * @param string $id + * @param string $name + * @param string $web_id (deprecated) + */ + public function __construct($id, $name, $web_id = '') + { + $this->id = $id; + $this->name = $name; + $this->web_id = $web_id; + + // add email field + $email_field = new NL4WP_Newsletter_Merge_Field('Email Address', 'email', 'EMAIL', true); + $this->merge_fields[] = $email_field; + } + + /** + * @param string $name + * + * @return mixed + */ + public function __get($name) + { + // for backwards compatibility with 3.x, channel these properties to their new names + if ($name === 'merge_vars') { + return $this->merge_fields; + } elseif ($name === 'groupings') { + return $this->interest_categories; + } + } + + /** + * @param string $tag + * @return NL4WP_Newsletter_Merge_Field + * + * @throws Exception + */ + public function get_field_by_tag($tag) + { + // ensure uppercase tagname + $tag = strtoupper($tag); + + // search merge vars + foreach ($this->merge_fields as $field) { + if ($field->tag !== $tag) { + continue; + } + + return $field; + } + + throw new Exception('Field tag not found.'); + } + + /** + * + * @since 4.0 + * + * @param string $interest_id + * @return NL4WP_Newsletter_Interest_Category + * + * @throws Exception + */ + public function get_interest_category_by_interest_id($interest_id) + { + foreach ($this->interest_categories as $category) { + foreach ($category->interests as $id => $name) { + if ($id != $interest_id) { + continue; + } + + return $category; + } + } + + throw new Exception(sprintf('No interest with ID %s', $interest_id)); + } + + /** + * Get the interest grouping object for a given list. + * + * @param string $category_id ID of the Interest Grouping + * + * @return NL4WP_Newsletter_Interest_Category + * + * @throws Exception + */ + public function get_interest_category($category_id) + { + foreach ($this->interest_categories as $category) { + if ($category->id !== $category_id) { + continue; + } + + return $category; + } + + throw new Exception(sprintf('No interest category with ID %s', $category_id)); + } + + /** + * Get link to this list in Newsletter + * + * @return string + */ + public function get_web_url() + { + return 'https://admin.newsletter.com/lists/members/?id=' . $this->web_id; + } + + /** + * Get the name of an interest category by its ID + * + * @deprecated 4.0 + * @use NL4WP_Newsletter_List::get_interest_category + * + * @param string $category_id + * + * @return string + */ + public function get_interest_category_name($category_id) + { + $category = $this->get_interest_category($category_id); + return $category->name; + } + + /** + * @deprecated 4.0 + * @use NL4WP_Newsletter_List::get_field_by_tag + * + * @param string $tag + * + * @return string + */ + public function get_field_name_by_tag($tag) + { + $field = $this->get_field_by_tag($tag); + return $field->name; + } } \ No newline at end of file diff --git a/includes/newsletter/class-merge-field.php b/includes/newsletter/class-merge-field.php index 0d7f87a..ceab34d 100755 --- a/includes/newsletter/class-merge-field.php +++ b/includes/newsletter/class-merge-field.php @@ -1,104 +1,105 @@ name = $name; - $this->field_type = $field_type; - $this->tag = strtoupper( $tag ); - $this->required = $required; - $this->choices = $choices; - } - - /** - * @param string $name - * - * @return string - */ - public function __get( $name ) { - - // for backwards compatibility with v3.x, channel these properties to their new names - if( $name === 'default' ) { - return $this->default_value; - } - } - - /** - * Creates our local object from Newsletter API data. - * - * @param object $data - * - * @return NL4WP_Newsletter_Merge_Field - */ - public static function from_data( $data ) { - - $instance = new self( $data->name, $data->type, $data->tag, $data->required ); - - if( ! empty( $data->options->choices ) ) { - $instance->choices = $data->options->choices; - } - - $optional = array( - 'public', - 'default_value' - ); - - foreach( $optional as $key ) { - if( isset( $data->$key ) ) { - $instance->$key = $data->$key; - } - } - - return $instance; - } - -} \ No newline at end of file +class NL4WP_Newsletter_Merge_Field +{ + + /** + * @var string + */ + public $name; + + /** + * @var string + */ + public $field_type; + + /** + * @var string + */ + public $tag; + + /** + * @var bool Is this a required field for the list it belongs to? + */ + public $required = false; + + /** + * @var array + */ + public $choices = array(); + + /** + * @var bool Is this field public? As in, should it show on forms? + */ + public $public = true; + + /** + * @var string Default value for the field. + */ + public $default_value = ''; + + /** + * @param string $name + * @param string $field_type + * @param string $tag + * @param bool $required + * @param array $choices + */ + public function __construct($name, $field_type, $tag, $required = false, $choices = array()) + { + $this->name = $name; + $this->field_type = $field_type; + $this->tag = strtoupper($tag); + $this->required = $required; + $this->choices = $choices; + } + + /** + * @param string $name + * + * @return string + */ + public function __get($name) + { + + // for backwards compatibility with v3.x, channel these properties to their new names + if ($name === 'default') { + return $this->default_value; + } + } + + /** + * Creates our local object from Newsletter API data. + * + * @param object $data + * + * @return NL4WP_Newsletter_Merge_Field + */ + public static function from_data($data) + { + $instance = new self($data->name, $data->type, $data->tag, $data->required); + + if (! empty($data->options->choices)) { + $instance->choices = $data->options->choices; + } + + $optional = array( + 'public', + 'default_value' + ); + + foreach ($optional as $key) { + if (isset($data->$key)) { + $instance->$key = $data->$key; + } + } + + return $instance; + } +} diff --git a/includes/newsletter/class-subscriber.php b/includes/newsletter/class-subscriber.php index 8b0e60d..fb37a5a 100755 --- a/includes/newsletter/class-subscriber.php +++ b/includes/newsletter/class-subscriber.php @@ -1,6 +1,7 @@ diff --git a/includes/views/general-settings.php b/includes/views/general-settings.php index 6ee86ac..59cb54a 100755 --- a/includes/views/general-settings.php +++ b/includes/views/general-settings.php @@ -1,10 +1,10 @@
    @@ -15,50 +15,54 @@

    - +

    messages->show(); - ?> + settings_errors(); + $this->messages->show(); + ?> -
    - + +

    - +

    - + @@ -71,27 +75,27 @@ '; - include dirname( __FILE__ ) . '/parts/lists-overview.php'; - } + if (! empty($opts['api_key'])) { + echo '
    '; + include dirname(__FILE__) . '/parts/lists-overview.php'; + } - include dirname( __FILE__ ) . '/parts/admin-footer.php'; + include dirname(__FILE__) . '/parts/admin-footer.php'; - ?> + ?> diff --git a/includes/views/other-settings.php b/includes/views/other-settings.php index 9af8553..ef7030c 100755 --- a/includes/views/other-settings.php +++ b/includes/views/other-settings.php @@ -1,5 +1,5 @@ +function _nl4wp_usage_tracking_setting($opts) +{ + ?>
    -

    +

    - + - - - - - + + + + +
    - /> + />

    - - + +

    - '. __( 'You defined your Newsletter API key using the NL4WP_API_KEY constant.', 'newsletter-for-wp' ) . '

    '; - } ?> + '. __('You defined your Newsletter API key using the NL4WP_API_KEY constant.', 'newsletter-for-wp') . '

    '; + } ?>
    - + @@ -41,14 +40,14 @@ function _nl4wp_usage_tracking_setting( $opts ) { */ ?> - + @@ -57,14 +56,14 @@ function _nl4wp_usage_tracking_setting( $opts ) {
    @@ -74,66 +73,65 @@ function _nl4wp_usage_tracking_setting( $opts ) {

    - +

    + /** + * @ignore + */ + do_action('nl4wp_admin_before_other_settings', $opts); + ?> - - + + + /** + * @ignore + */ + do_action('nl4wp_admin_other_settings', $opts); + ?>
    -

    +

    test() ) { - echo '

    '; - echo __( 'Log file is not writable.', 'newsletter-for-wp' ) . ' '; - echo sprintf( __( 'Please ensure %s has the proper file permissions.', 'newsletter-for-wp' ), '' . $log->file . '', 'https://codex.wordpress.org/Changing_File_Permissions' ); - echo '

    '; - - // hack to hide filter input - echo ''; - } else { - ?> + if (! $log->test()) { + echo '

    '; + echo __('Log file is not writable.', 'newsletter-for-wp') . ' '; + echo sprintf(__('Please ensure %s has the proper file permissions.', 'newsletter-for-wp'), '' . $log->file . '', 'https://codex.wordpress.org/Changing_File_Permissions'); + echo '

    '; + + // hack to hide filter input + echo ''; + } else { + ?>
    read_as_html(); - - if (!empty($line)) { - while( is_string( $line ) ) { - if( ! empty( $line ) ) { - echo '
    ' . $line . '
    '; - } - - $line = $log_reader->read_as_html(); - } - } else { - echo '
    '; - echo '-- ' . __('Nothing here. Which means there are no errors!', 'newsletter-for-wp'); - echo '
    '; - } - ?> + $line = $log_reader->read_as_html(); + + if (!empty($line)) { + while (is_string($line)) { + if (! empty($line)) { + echo '
    ' . $line . '
    '; + } + + $line = $log_reader->read_as_html(); + } + } else { + echo '
    '; + echo '-- ' . __('Nothing here. Which means there are no errors!', 'newsletter-for-wp'); + echo '
    '; + } ?>
    @@ -144,14 +142,14 @@ function _nl4wp_usage_tracking_setting( $opts ) {

    level >= 300 ) { - echo '

    '; - echo __( 'Right now, the plugin is configured to only log errors and warnings.', 'newsletter-for-wp' ); - echo '

    '; - } - ?> + if ($log->level >= 300) { + echo '

    '; + echo __('Right now, the plugin is configured to only log errors and warnings.', 'newsletter-for-wp'); + echo '

    '; + } + ?>
     

    - + - +

    - the debug log (see below).', 'newsletter-for-wp' ), 'https://kb.mc4wp.com/how-to-enable-log-debugging/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=settings-page' ); ?> + the debug log (see below).', 'newsletter-for-wp'), 'https://kb.mc4wp.com/how-to-enable-log-debugging/#utm_source=wp-plugin&utm_medium=newsletter-for-wp&utm_campaign=settings-page'); ?>