").addClass((i & 1) === 0 ? "odd" : "even");
- BI.each(rows, function (j, row) {
- if (!map[i]) {
- map[i] = {};
- }
- if (!TDs[i]) {
- TDs[i] = {};
- }
- if (!Ws[i]) {
- Ws[i] = {};
- }
- map[i][j] = row;
+ var lastStoppedKey = null;
+ function onKeyDown(e) {
+ var cm = this;
+ cm.curOp.focus = activeElt();
+ if (signalDOMEvent(cm, e)) return;
+ // IE does strange things with escape.
+ if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
+ var code = e.keyCode;
+ cm.display.shift = code == 16 || e.shiftKey;
+ var handled = handleKeyBinding(cm, e);
+ if (presto) {
+ lastStoppedKey = handled ? code : null;
+ // Opera has no cut event... we try to at least catch the key combo
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
+ cm.replaceSelection("", null, "cut");
+ }
- if (o.isNeedMerge && mergeCols.contains(j)) {
- if (i === 0 && j === 0) {
- createOneEl(0, 0);
- } else if (j === 0 && i > 0) {
- var isNeedMergeRow = o.mergeRule(map[i][j], map[i - 1][j]);
- if (isNeedMergeRow === true) {
- mergeRow(i, j);
- preRow[i] = preCol[j];
- preRW[i] = preCW[j];
- } else {
- createOneEl(i, j);
- }
- } else if (i === 0 && j > 0) {
- var isNeedMergeCol = o.mergeRule(map[i][j], map[i][j - 1]);
- if (isNeedMergeCol === true) {
- mergeCol(i, j);
- preCol[j] = preRow[j - 1];
- preCW[j] = preRW[j - 1];
- } else {
- createOneEl(i, j);
- }
- } else {
- var isNeedMergeRow = o.mergeRule(map[i][j], map[i - 1][j]);
- var isNeedMergeCol = o.mergeRule(map[i][j], map[i][j - 1]);
- if (isNeedMergeCol && isNeedMergeRow) {
- return;
- }
- if (isNeedMergeCol) {
- mergeCol(i, j);
- }
- if (isNeedMergeRow) {
- mergeRow(i, j);
- }
- if (!isNeedMergeCol && !isNeedMergeRow) {
- createOneEl(i, j);
- }
- }
- } else {
- createOneEl(i, j);
- }
- });
- function mergeRow(i, j) {
- var height = (preCol[j].attr("height") | 0) + rowSize + 1;
- preCol[j].attr("height", height).css("height", height);
- //preCW[j].element.css("height", height);
- var rowspan = ((preCol[j].attr("rowspan") || 1) | 0) + 1;
- preCol[j].attr("rowspan", rowspan);
- preCol[j].__mergeRows.pushDistinct(i);
- TDs[i][j] = preCol[j];
- Ws[i][j] = preCW[j];
- }
+ // Turn mouse into crosshair when Alt is held on Mac.
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
+ showCrossHair(cm);
+ }
- function mergeCol(i, j) {
- if (columnSize[j]) {
- var width = preRow[i].attr("width") | 0;
- if (width > 1.05 && columnSize[j]) {
- width = width + columnSize[j] + 1;
- if (j === columnSize.length - 1) {
- width--;
- }
- } else {
- width = width + columnSize[j]
- }
- width = self._calculateWidth(width);
- preRow[i].attr("width", width).css("width", width);
- preRW[i].element.width(width);
- }
- var colspan = ((preRow[i].attr("colspan") || 1) | 0) + 1;
- preRow[i].attr("colspan", colspan);
- preRow[i].__mergeCols.pushDistinct(j);
- TDs[i][j] = preRow[i];
- Ws[i][j] = preRW[i];
- }
+ function showCrossHair(cm) {
+ var lineDiv = cm.display.lineDiv;
+ addClass(lineDiv, "CodeMirror-crosshair");
- function createOneEl(r, c) {
- var width = self._calculateWidth(columnSize[c]);
- if (width > 1.05 && c === columnSize.length - 1) {
- width--;
- }
- var height = self._calculateHeight(rowSize);
- var td = $("").attr("height", height)
- .attr("width", width).css({"width": width, "height": height, "position": "relative"})
- .addClass((c & 1) === 0 ? "odd-col" : "even-col")
- .addClass(r === 0 ? "first-row" : "")
- .addClass(c === 0 ? "first-col" : "")
- .addClass(c === rows.length - 1 ? "last-col" : "");
- var w = BI.createWidget(map[r][c], {
- type: "bi.table_cell",
- textAlign: "left",
- width: BI.isNumeric(width) ? width : "",
- height: BI.isNumeric(height) ? height : "",
- _row: r,
- _col: c + start
- });
- w.element.css("position", "relative");
- td.append(w.element);
- tr.append(td);
- preCol[c] = td;
- preCol[c].__mergeRows = [r];
- preCW[c] = w;
- preRow[r] = td;
- preRow[r].__mergeCols = [c];
- preRW[r] = w;
- TDs[r][c] = td;
- Ws[r][c] = w;
- }
+ function up(e) {
+ if (e.keyCode == 18 || !e.altKey) {
+ rmClass(lineDiv, "CodeMirror-crosshair");
+ off(document, "keyup", up);
+ off(document, "mouseover", up);
+ }
+ }
+ on(document, "keyup", up);
+ on(document, "mouseover", up);
+ }
- frag.appendChild(tr[0]);
- });
- return frag;
- },
+ function onKeyUp(e) {
+ if (e.keyCode == 16) this.doc.sel.shift = false;
+ signalDOMEvent(this, e);
+ }
- _createColGroupCells: function (columnSize, store) {
- var self = this, o = this.options;
- columnSize = columnSize || o.columnSize;
- store = store || {};
- var frag = document.createDocumentFragment();
- BI.each(columnSize, function (i, size) {
- var width = self._calculateWidth(size);
- var col = $("").attr("width", width).css("width", width);
- store[i] = col;
- frag.appendChild(col[0]);
- });
- return frag;
- },
+ function onKeyPress(e) {
+ var cm = this;
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
+ var keyCode = e.keyCode, charCode = e.charCode;
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
+ if (handleCharBinding(cm, e, ch)) return;
+ cm.display.input.onKeyPress(e);
+ }
- _createHeaderCells: function (items, columnSize, mergeCols, TDs, Ws, start) {
- var self = this, o = this.options;
- start || (start = 0);
- var frag = this._createCells(items, columnSize, BI.range(o.columnSize.length), TDs, Ws, start, o.headerRowSize || o.rowSize);
+ // FOCUS/BLUR EVENTS
- if (o.isNeedResize === true) {
- var tds = TDs[BI.size(TDs) - 1];
- BI.each(tds, function (j, td) {
- j = j | 0;
- var resizer;
- var getHeight = function (size, position) {
- var rowSize = self.getCalculateRegionRowSize();
- if (o.isNeedFreeze === true) {
- var tableHeight = self.bottomRightContainer.element.outerHeight();
- return size.height + Math.min(rowSize[1], tableHeight);
- } else {
- var tableHeight = self.tableContainer.element.outerHeight();
- var offset = self.tableContainer.element.offset();
- var offsetTop = position.top - offset.top;
- var height = tableHeight - offsetTop;
- height = Math.min(height, rowSize[0] - offsetTop);
- return height;
- }
- };
- if (j < BI.size(tds) - 1) {
- td.resizable({
- handles: "e",
- minWidth: 15,
- helper: "clone",
- start: function (event, ui) {
- var height = getHeight(ui.size, ui.position);
- resizer = BI.createWidget({
- type: "bi.layout",
- cls: "bi-resizer",
- width: ui.size.width,
- height: height
- });
+ function delayBlurEvent(cm) {
+ cm.state.delayingBlurEvent = true;
+ setTimeout(function() {
+ if (cm.state.delayingBlurEvent) {
+ cm.state.delayingBlurEvent = false;
+ onBlur(cm);
+ }
+ }, 100);
+ }
- BI.createWidget({
- type: "bi.absolute",
- element: "body",
- items: [{
- el: resizer,
- left: ui.position.left,
- top: ui.position.top
- }]
- });
- self.fireEvent(BI.Table.EVENT_TABLE_BEFORE_COLUMN_RESIZE);
- },
- resize: function (e, ui) {
- var height = getHeight(ui.size, ui.position);
- resizer.element.css({"width": ui.size.width + "px", "height": height + "px"});
- //o.columnSize[start + j] = ui.size.width;
- //self.setColumnSize(o.columnSize);
- self.fireEvent(BI.Table.EVENT_TABLE_COLUMN_RESIZE);
- e.stopPropagation();
- //return false;
- },
- stop: function (e, ui) {
- resizer.destroy();
- resizer = null;
- o.columnSize[start + j] = ui.size.width - 1;
- self.setColumnSize(o.columnSize);
- self.fireEvent(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE);
- }
- })
- }
- })
- }
- return frag;
- },
+ function onFocus(cm) {
+ if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
- _createFooterCells: function (items, columnSize, TDs, Ws) {
- var o = this.options;
- var frag = this._createCells(items, columnSize, [], TDs, Ws, 0);
- return frag;
- },
+ if (cm.options.readOnly == "nocursor") return;
+ if (!cm.state.focused) {
+ signal(cm, "focus", cm);
+ cm.state.focused = true;
+ addClass(cm.display.wrapper, "CodeMirror-focused");
+ // This test prevents this from firing when a context
+ // menu is closed (since the input reset would kill the
+ // select-all detection hack)
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
+ cm.display.input.reset();
+ if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
+ }
+ cm.display.input.receivedFocus();
+ }
+ restartBlink(cm);
+ }
+ function onBlur(cm) {
+ if (cm.state.delayingBlurEvent) return;
- _createColGroup: function (columnSize, store, widgets) {
- var self = this, o = this.options;
- this.colgroup = this._colgroup();
- this.colgroup.element.append(this._createColGroupCells(columnSize, store, widgets));
- return this.colgroup;
- },
+ if (cm.state.focused) {
+ signal(cm, "blur", cm);
+ cm.state.focused = false;
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
+ }
+ clearInterval(cm.display.blinker);
+ setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
+ }
- _createHeader: function () {
- var self = this, o = this.options;
- if (o.header === false) {
- return;
- }
- this.header = this._header();
- this.header.element.append(this._createHeaderCells(o.header, null, null, this.headerTds, this.headerItems));
- return this.header;
- },
+ // CONTEXT MENU HANDLING
- _createFooter: function (columnSize, store, widgets) {
- var self = this, o = this.options;
- if (o.footer === false) {
- return;
- }
- this.footer = this._footer();
- this.footer.element.append(this._createFooterCells(o.footer, null, this.footerTds, this.footerItems));
- return this.footer;
- },
+ // To make the context menu work, we need to briefly unhide the
+ // textarea (making it as unobtrusive as possible) to let the
+ // right-click take effect on it.
+ function onContextMenu(cm, e) {
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
+ cm.display.input.onContextMenu(e);
+ }
- _createBody: function () {
- var self = this, o = this.options;
- this.body = this._body();
- this.body.element.append(this._createCells(o.items, null, null, this.bodyTds, this.bodyItems));
- return this.body;
- },
+ function contextMenuInGutter(cm, e) {
+ if (!hasHandler(cm, "gutterContextMenu")) return false;
+ return gutterEvent(cm, e, "gutterContextMenu", false, signal);
+ }
- _createNormalTable: function () {
- var self = this, o = this.options, table = this._table();
- this.colgroupTds = {};
- this.headerTds = {};
- this.footerTds = {};
- this.bodyTds = {};
+ // UPDATING
- this.headerItems = {};
- this.footerItems = {};
- this.bodyItems = {};
- var colgroup = this._createColGroup(null, this.colgroupTds);
- var header = this._createHeader();
- var footer = this._createFooter();
- var body = this._createBody();
+ // Compute the position of the end of a change (its 'to' property
+ // refers to the pre-change end).
+ var changeEnd = CodeMirror.changeEnd = function(change) {
+ if (!change.text) return change.to;
+ return Pos(change.from.line + change.text.length - 1,
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
+ };
- BI.createWidget({
- type: "bi.adaptive",
- element: table,
- items: [colgroup, header, footer, body]
- });
+ // Adjust a position to refer to the post-change position of the
+ // same text, or the end of the change if the change covers it.
+ function adjustForChange(pos, change) {
+ if (cmp(pos, change.from) < 0) return pos;
+ if (cmp(pos, change.to) <= 0) return changeEnd(change);
- var w = BI.sum(this.options.columnSize) || undefined;
- w = this._calculateWidth(w);
- if (BI.isNumeric(w) && w > 1) {
- w += o.columnSize.length;
- }
- this.tableContainer = BI.createWidget({
- type: "bi.adaptive",
- width: this._calculateWidth(w),
- items: [table]
- });
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
+ if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
+ return Pos(line, ch);
+ }
- this.scrollBottomRight = BI.createWidget({
- type: "bi.adaptive",
- width: "100%",
- height: "100%",
- cls: "scroll-bottom-right",
- scrollable: true,
- items: [this.tableContainer]
- });
+ function computeSelAfterChange(doc, change) {
+ var out = [];
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ var range = doc.sel.ranges[i];
+ out.push(new Range(adjustForChange(range.anchor, change),
+ adjustForChange(range.head, change)));
+ }
+ return normalizeSelection(out, doc.sel.primIndex);
+ }
- BI.createWidget({
- type: "bi.adaptive",
- cls: "bottom-right",
- element: this,
- scrollable: false,
- items: [this.scrollBottomRight]
- });
+ function offsetPos(pos, old, nw) {
+ if (pos.line == old.line)
+ return Pos(nw.line, pos.ch - old.ch + nw.ch);
+ else
+ return Pos(nw.line + (pos.line - old.line), pos.ch);
+ }
- this._resize = function () {
- if (self.element.is(":visible")) {
- self.setColumnSize(o.columnSize);
- }
- };
+ // Used by replaceSelections to allow moving the selection to the
+ // start or around the replaced test. Hint may be "start" or "around".
+ function computeReplacedSel(doc, changes, hint) {
+ var out = [];
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
+ for (var i = 0; i < changes.length; i++) {
+ var change = changes[i];
+ var from = offsetPos(change.from, oldPrev, newPrev);
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
+ oldPrev = change.to;
+ newPrev = to;
+ if (hint == "around") {
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
+ out[i] = new Range(inv ? to : from, inv ? from : to);
+ } else {
+ out[i] = new Range(from, from);
+ }
+ }
+ return new Selection(out, doc.sel.primIndex);
+ }
- this._initNormalScroll();
- BI.Resizers.add(this.getName(), function (e) {
- if (self.element.is(":visible") && BI.isWindow(e.target)) {
- self._resize();
- self.fireEvent(BI.Table.EVENT_TABLE_RESIZE);
- }
- });
- BI.nextTick(function () {
- if (self.element.is(":visible")) {
- self.fireEvent(BI.Table.EVENT_TABLE_AFTER_INIT);
- }
- });
- },
+ // Allow "beforeChange" event handlers to influence a change
+ function filterChange(doc, change, update) {
+ var obj = {
+ canceled: false,
+ from: change.from,
+ to: change.to,
+ text: change.text,
+ origin: change.origin,
+ cancel: function() { this.canceled = true; }
+ };
+ if (update) obj.update = function(from, to, text, origin) {
+ if (from) this.from = clipPos(doc, from);
+ if (to) this.to = clipPos(doc, to);
+ if (text) this.text = text;
+ if (origin !== undefined) this.origin = origin;
+ };
+ signal(doc, "beforeChange", doc, obj);
+ if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
- _initNormalScroll: function () {
- var self = this;
- var scrolling, scrollX;
- this.scrollBottomRight.element.mousewheel(function (event, delta, deltaX, deltaY) {
- var inf = self._getScrollOffsetAndDur(event);
- if (deltaY < 0 || deltaY > 0) {
- var ele = self.scrollBottomRight.element;
- if (scrolling) {
- ele[0].scrollTop = scrolling;
- }
+ if (obj.canceled) return null;
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
+ }
- scrolling = ele[0].scrollTop - delta * inf.offset;
- var stopPropagation = false;
- var st = ele[0].scrollTop;
- ele[0].scrollTop = scrolling;
- if (ele[0].scrollTop !== st) {
- stopPropagation = true;
- }
- ele[0].scrollTop = st;
- self._animateScrollTo(ele, ele[0].scrollTop, scrolling, inf.dur, "linear", {
- onStart: function () {
- },
- onUpdate: function (top) {
- self.fireEvent(BI.Table.EVENT_TABLE_SCROLL, top);
- },
- onComplete: function () {
- self.fireEvent(BI.Table.EVENT_TABLE_SCROLL, scrolling);
- scrolling = null;
- }
- });
- //var scrollTop = self.scrollBottomRight.element[0].scrollTop = self.scrollBottomRight.element[0].scrollTop - delta * offset;
- //self.fireEvent(BI.Table.EVENT_TABLE_SCROLL, scrollTop);
- if (stopPropagation === true) {
- event.stopPropagation();
- return false;
- }
- }
- });
- var scrollTop = 0, scrollLeft = 0;
- this.scrollBottomRight.element.scroll(function (e) {
- var change = false;
- var scrollElement = self.scrollBottomRight.element;
- if (scrollElement.scrollTop() != scrollTop) {
- if (Math.abs(scrollElement.scrollTop() - scrollTop) > 0.1) {
- e.stopPropagation();
- change = true;
- }
- scrollTop = scrollElement.scrollTop();
- }
- if (scrollElement.scrollLeft() != scrollLeft) {
- if (Math.abs(scrollElement.scrollLeft() - scrollLeft) > 0.1) {
- e.stopPropagation();
- change = true;
- }
- scrollLeft = scrollElement.scrollLeft();
- }
- self.fireEvent(BI.Table.EVENT_TABLE_SCROLL);
- if (change === true) {
- e.stopPropagation();
- //return false;
- }
- return false;
- });
- },
+ // Apply a change to a document, and add it to the document's
+ // history, and propagating it to all linked documents.
+ function makeChange(doc, change, ignoreReadOnly) {
+ if (doc.cm) {
+ if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
+ if (doc.cm.state.suppressEdits) return;
+ }
- _split: function (items) {
- var o = this.options, left = [], right = [], isRight = this._isRightFreeze();
- BI.each(items, function (i, rows) {
- left.push([]);
- right.push([]);
- BI.each(rows, function (j, cell) {
- if (o.freezeCols.contains(j)) {
- (isRight ? right : left)[i].push(cell);
- } else {
- (isRight ? left : right)[i].push(cell);
- }
- })
- });
- return {
- left: left,
- right: right
- }
- },
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
+ change = filterChange(doc, change, true);
+ if (!change) return;
+ }
- _table: function () {
- return BI.createWidget({
- type: "bi.layout",
- tagName: "table",
- cls: "table",
- attribute: {"cellspacing": 0, "cellpadding": 0}
- });
- },
+ // Possibly split or suppress the update based on the presence
+ // of read-only spans in its range.
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
+ if (split) {
+ for (var i = split.length - 1; i >= 0; --i)
+ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
+ } else {
+ makeChangeInner(doc, change);
+ }
+ }
- _header: function () {
- return BI.createWidget({
- type: "bi.layout",
- cls: "header",
- tagName: "thead"
- });
- },
+ function makeChangeInner(doc, change) {
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
+ var selAfter = computeSelAfterChange(doc, change);
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
- _footer: function () {
- return BI.createWidget({
- type: "bi.layout",
- cls: "footer",
- tagName: "tfoot"
- });
- },
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
+ var rebased = [];
- _body: function () {
- return BI.createWidget({
- type: "bi.layout",
- tagName: "tbody",
- cls: "body"
- });
- },
+ linkedDocs(doc, function(doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
+ });
+ }
- _colgroup: function () {
- return BI.createWidget({
- type: "bi.layout",
- tagName: "colgroup"
- });
- },
+ // Revert a change stored in a document's history.
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
+ if (doc.cm && doc.cm.state.suppressEdits) return;
- _init: function () {
- BI.Table.superclass._init.apply(this, arguments);
+ var hist = doc.history, event, selAfter = doc.sel;
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
- this.populate(this.options.items);
- },
+ // Verify that there is a useable event (so that ctrl-z won't
+ // needlessly clear selection events)
+ for (var i = 0; i < source.length; i++) {
+ event = source[i];
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
+ break;
+ }
+ if (i == source.length) return;
+ hist.lastOrigin = hist.lastSelOrigin = null;
- setColumnSize: function (columnSize) {
- var self = this, o = this.options;
- var isRight = this._isRightFreeze();
- o.columnSize = columnSize || [];
- if (o.isNeedFreeze) {
- var columnLeft = [];
- var columnRight = [];
- BI.each(o.columnSize, function (i, size) {
- if (o.freezeCols.contains(i)) {
- isRight ? columnRight.push(size) : columnLeft.push(size);
- } else {
- isRight ? columnLeft.push(size) : columnRight.push(size);
- }
- });
- var topleft = 0, topright = 1, bottomleft = 2, bottomright = 3;
- var run = function (direction) {
- var colgroupTds, bodyTds, bodyItems, sizes;
- switch (direction) {
- case topleft:
- colgroupTds = self.topLeftColGroupTds;
- bodyTds = self.topLeftBodyTds;
- bodyItems = self.topLeftBodyItems;
- sizes = columnLeft;
- break;
- case topright:
- colgroupTds = self.topRightColGroupTds;
- bodyTds = self.topRightBodyTds;
- bodyItems = self.topRightBodyItems;
- sizes = columnRight;
- break;
- case bottomleft:
- colgroupTds = self.bottomLeftColGroupTds;
- bodyTds = self.bottomLeftBodyTds;
- bodyItems = self.bottomLeftBodyItems;
- sizes = columnLeft;
+ for (;;) {
+ event = source.pop();
+ if (event.ranges) {
+ pushSelectionToHistory(event, dest);
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
+ setSelection(doc, event, {clearRedo: false});
+ return;
+ }
+ selAfter = event;
+ }
+ else break;
+ }
+
+ // Build up a reverse change object to add to the opposite history
+ // stack (redo when undoing, and vice versa).
+ var antiChanges = [];
+ pushSelectionToHistory(selAfter, dest);
+ dest.push({changes: antiChanges, generation: hist.generation});
+ hist.generation = event.generation || ++hist.maxGeneration;
+
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
+
+ for (var i = event.changes.length - 1; i >= 0; --i) {
+ var change = event.changes[i];
+ change.origin = type;
+ if (filter && !filterChange(doc, change, false)) {
+ source.length = 0;
+ return;
+ }
+
+ antiChanges.push(historyChangeFromChange(doc, change));
+
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
+ if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
+ var rebased = [];
+
+ // Propagate to the linked documents
+ linkedDocs(doc, function(doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
+ });
+ }
+ }
+
+ // Sub-views need their line numbers shifted when text is added
+ // above or below them in the parent document.
+ function shiftDoc(doc, distance) {
+ if (distance == 0) return;
+ doc.first += distance;
+ doc.sel = new Selection(map(doc.sel.ranges, function(range) {
+ return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
+ Pos(range.head.line + distance, range.head.ch));
+ }), doc.sel.primIndex);
+ if (doc.cm) {
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
+ regLineChange(doc.cm, l, "gutter");
+ }
+ }
+
+ // More lower-level change function, handling only a single document
+ // (not linked ones).
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
+ if (doc.cm && !doc.cm.curOp)
+ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
+
+ if (change.to.line < doc.first) {
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
+ return;
+ }
+ if (change.from.line > doc.lastLine()) return;
+
+ // Clip the change to the size of this doc
+ if (change.from.line < doc.first) {
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
+ shiftDoc(doc, shift);
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
+ text: [lst(change.text)], origin: change.origin};
+ }
+ var last = doc.lastLine();
+ if (change.to.line > last) {
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
+ text: [change.text[0]], origin: change.origin};
+ }
+
+ change.removed = getBetween(doc, change.from, change.to);
+
+ if (!selAfter) selAfter = computeSelAfterChange(doc, change);
+ if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
+ else updateDoc(doc, change, spans);
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
+ }
+
+ // Handle the interaction of a change to a document with the editor
+ // that this document is part of.
+ function makeChangeSingleDocInEditor(cm, change, spans) {
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
+
+ var recomputeMaxLength = false, checkWidthStart = from.line;
+ if (!cm.options.lineWrapping) {
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
+ if (line == display.maxLine) {
+ recomputeMaxLength = true;
+ return true;
+ }
+ });
+ }
+
+ if (doc.sel.contains(change.from, change.to) > -1)
+ signalCursorActivity(cm);
+
+ updateDoc(doc, change, spans, estimateHeight(cm));
+
+ if (!cm.options.lineWrapping) {
+ doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
+ var len = lineLength(line);
+ if (len > display.maxLineLength) {
+ display.maxLine = line;
+ display.maxLineLength = len;
+ display.maxLineChanged = true;
+ recomputeMaxLength = false;
+ }
+ });
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
+ }
+
+ // Adjust frontier, schedule worker
+ doc.frontier = Math.min(doc.frontier, from.line);
+ startWorker(cm, 400);
+
+ var lendiff = change.text.length - (to.line - from.line) - 1;
+ // Remember that these lines changed, for updating the display
+ if (change.full)
+ regChange(cm);
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
+ regLineChange(cm, from.line, "text");
+ else
+ regChange(cm, from.line, to.line + 1, lendiff);
+
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
+ if (changeHandler || changesHandler) {
+ var obj = {
+ from: from, to: to,
+ text: change.text,
+ removed: change.removed,
+ origin: change.origin
+ };
+ if (changeHandler) signalLater(cm, "change", cm, obj);
+ if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
+ }
+ cm.display.selForContextMenu = null;
+ }
+
+ function replaceRange(doc, code, from, to, origin) {
+ if (!to) to = from;
+ if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
+ if (typeof code == "string") code = splitLines(code);
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
+ }
+
+ // SCROLLING THINGS INTO VIEW
+
+ // If an editor sits on the top or bottom of the window, partially
+ // scrolled out of view, this ensures that the cursor is visible.
+ function maybeScrollWindow(cm, coords) {
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
+
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
+ if (coords.top + box.top < 0) doScroll = true;
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
+ if (doScroll != null && !phantom) {
+ var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
+ (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
+ (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
+ coords.left + "px; width: 2px;");
+ cm.display.lineSpace.appendChild(scrollNode);
+ scrollNode.scrollIntoView(doScroll);
+ cm.display.lineSpace.removeChild(scrollNode);
+ }
+ }
+
+ // Scroll a given position into view (immediately), verifying that
+ // it actually became visible (as line heights are accurately
+ // measured, the position of something may 'drift' during drawing).
+ function scrollPosIntoView(cm, pos, end, margin) {
+ if (margin == null) margin = 0;
+ for (var limit = 0; limit < 5; limit++) {
+ var changed = false, coords = cursorCoords(cm, pos);
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
+ var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
+ Math.min(coords.top, endCoords.top) - margin,
+ Math.max(coords.left, endCoords.left),
+ Math.max(coords.bottom, endCoords.bottom) + margin);
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
+ if (scrollPos.scrollTop != null) {
+ setScrollTop(cm, scrollPos.scrollTop);
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
+ }
+ if (scrollPos.scrollLeft != null) {
+ setScrollLeft(cm, scrollPos.scrollLeft);
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
+ }
+ if (!changed) break;
+ }
+ return coords;
+ }
+
+ // Scroll a given set of coordinates into view (immediately).
+ function scrollIntoView(cm, x1, y1, x2, y2) {
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
+ }
+
+ // Calculate a new scroll position needed to scroll the given
+ // rectangle into view. Returns an object with scrollTop and
+ // scrollLeft properties. When these are undefined, the
+ // vertical/horizontal position does not need to be adjusted.
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
+ var display = cm.display, snapMargin = textHeight(cm.display);
+ if (y1 < 0) y1 = 0;
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
+ var screen = displayHeight(cm), result = {};
+ if (y2 - y1 > screen) y2 = y1 + screen;
+ var docBottom = cm.doc.height + paddingVert(display);
+ var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
+ if (y1 < screentop) {
+ result.scrollTop = atTop ? 0 : y1;
+ } else if (y2 > screentop + screen) {
+ var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
+ if (newTop != screentop) result.scrollTop = newTop;
+ }
+
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
+ var tooWide = x2 - x1 > screenw;
+ if (tooWide) x2 = x1 + screenw;
+ if (x1 < 10)
+ result.scrollLeft = 0;
+ else if (x1 < screenleft)
+ result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
+ else if (x2 > screenw + screenleft - 3)
+ result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
+ return result;
+ }
+
+ // Store a relative adjustment to the scroll position in the current
+ // operation (to be applied when the operation finishes).
+ function addToScrollPos(cm, left, top) {
+ if (left != null || top != null) resolveScrollToPos(cm);
+ if (left != null)
+ cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
+ if (top != null)
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
+ }
+
+ // Make sure that at the end of the operation the current cursor is
+ // shown.
+ function ensureCursorVisible(cm) {
+ resolveScrollToPos(cm);
+ var cur = cm.getCursor(), from = cur, to = cur;
+ if (!cm.options.lineWrapping) {
+ from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
+ to = Pos(cur.line, cur.ch + 1);
+ }
+ cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
+ }
+
+ // When an operation has its scrollToPos property set, and another
+ // scroll action is applied before the end of the operation, this
+ // 'simulates' scrolling that position into view in a cheap way, so
+ // that the effect of intermediate scroll commands is not ignored.
+ function resolveScrollToPos(cm) {
+ var range = cm.curOp.scrollToPos;
+ if (range) {
+ cm.curOp.scrollToPos = null;
+ var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
+ var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
+ Math.min(from.top, to.top) - range.margin,
+ Math.max(from.right, to.right),
+ Math.max(from.bottom, to.bottom) + range.margin);
+ cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
+ }
+ }
+
+ // API UTILITIES
+
+ // Indent the given line. The how parameter can be "smart",
+ // "add"/null, "subtract", or "prev". When aggressive is false
+ // (typically set to true for forced single-line indents), empty
+ // lines are not indented, and places where the mode returns Pass
+ // are left alone.
+ function indentLine(cm, n, how, aggressive) {
+ var doc = cm.doc, state;
+ if (how == null) how = "add";
+ if (how == "smart") {
+ // Fall back to "prev" when the mode doesn't have an indentation
+ // method.
+ if (!doc.mode.indent) how = "prev";
+ else state = getStateBefore(cm, n);
+ }
+
+ var tabSize = cm.options.tabSize;
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
+ if (line.stateAfter) line.stateAfter = null;
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
+ if (!aggressive && !/\S/.test(line.text)) {
+ indentation = 0;
+ how = "not";
+ } else if (how == "smart") {
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
+ if (indentation == Pass || indentation > 150) {
+ if (!aggressive) return;
+ how = "prev";
+ }
+ }
+ if (how == "prev") {
+ if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
+ else indentation = 0;
+ } else if (how == "add") {
+ indentation = curSpace + cm.options.indentUnit;
+ } else if (how == "subtract") {
+ indentation = curSpace - cm.options.indentUnit;
+ } else if (typeof how == "number") {
+ indentation = curSpace + how;
+ }
+ indentation = Math.max(0, indentation);
+
+ var indentString = "", pos = 0;
+ if (cm.options.indentWithTabs)
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
+
+ if (indentString != curSpaceString) {
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
+ line.stateAfter = null;
+ return true;
+ } else {
+ // Ensure that, if the cursor was in the whitespace at the start
+ // of the line, it is moved to the end of that space.
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ var range = doc.sel.ranges[i];
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
+ var pos = Pos(n, curSpaceString.length);
+ replaceOneSelection(doc, i, new Range(pos, pos));
+ break;
+ }
+ }
+ }
+ }
+
+ // Utility for applying a change to a line by handle or number,
+ // returning the number and optionally registering the line as
+ // changed.
+ function changeLine(doc, handle, changeType, op) {
+ var no = handle, line = handle;
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
+ else no = lineNo(handle);
+ if (no == null) return null;
+ if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
+ return line;
+ }
+
+ // Helper for deleting text near the selection(s), used to implement
+ // backspace, delete, and similar functionality.
+ function deleteNearSelection(cm, compute) {
+ var ranges = cm.doc.sel.ranges, kill = [];
+ // Build up a set of ranges to kill first, merging overlapping
+ // ranges.
+ for (var i = 0; i < ranges.length; i++) {
+ var toKill = compute(ranges[i]);
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
+ var replaced = kill.pop();
+ if (cmp(replaced.from, toKill.from) < 0) {
+ toKill.from = replaced.from;
+ break;
+ }
+ }
+ kill.push(toKill);
+ }
+ // Next, remove those actual ranges.
+ runInOp(cm, function() {
+ for (var i = kill.length - 1; i >= 0; i--)
+ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
+ ensureCursorVisible(cm);
+ });
+ }
+
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
+ // right), unit can be "char", "column" (like char, but doesn't
+ // cross line boundaries), "word" (across next word), or "group" (to
+ // the start of next group of word or non-word-non-whitespace
+ // chars). The visually param controls whether, in right-to-left
+ // text, direction 1 means to move towards the next index in the
+ // string, or towards the character to the right of the current
+ // position. The resulting position will have a hitSide=true
+ // property if it reached the end of the document.
+ function findPosH(doc, pos, dir, unit, visually) {
+ var line = pos.line, ch = pos.ch, origDir = dir;
+ var lineObj = getLine(doc, line);
+ var possible = true;
+ function findNextLine() {
+ var l = line + dir;
+ if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
+ line = l;
+ return lineObj = getLine(doc, l);
+ }
+ function moveOnce(boundToLine) {
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
+ if (next == null) {
+ if (!boundToLine && findNextLine()) {
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
+ else ch = dir < 0 ? lineObj.text.length : 0;
+ } else return (possible = false);
+ } else ch = next;
+ return true;
+ }
+
+ if (unit == "char") moveOnce();
+ else if (unit == "column") moveOnce(true);
+ else if (unit == "word" || unit == "group") {
+ var sawType = null, group = unit == "group";
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
+ for (var first = true;; first = false) {
+ if (dir < 0 && !moveOnce(!first)) break;
+ var cur = lineObj.text.charAt(ch) || "\n";
+ var type = isWordChar(cur, helper) ? "w"
+ : group && cur == "\n" ? "n"
+ : !group || /\s/.test(cur) ? null
+ : "p";
+ if (group && !first && !type) type = "s";
+ if (sawType && sawType != type) {
+ if (dir < 0) {dir = 1; moveOnce();}
+ break;
+ }
+
+ if (type) sawType = type;
+ if (dir > 0 && !moveOnce(!first)) break;
+ }
+ }
+ var result = skipAtomic(doc, Pos(line, ch), origDir, true);
+ if (!possible) result.hitSide = true;
+ return result;
+ }
+
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
+ // "page" or "line". The resulting position will have a hitSide=true
+ // property if it reached the end of the document.
+ function findPosV(cm, pos, dir, unit) {
+ var doc = cm.doc, x = pos.left, y;
+ if (unit == "page") {
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
+ y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
+ } else if (unit == "line") {
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
+ }
+ for (;;) {
+ var target = coordsChar(cm, x, y);
+ if (!target.outside) break;
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
+ y += dir * 5;
+ }
+ return target;
+ }
+
+ // EDITOR METHODS
+
+ // The publicly visible API. Note that methodOp(f) means
+ // 'wrap f in an operation, performed on its `this` parameter'.
+
+ // This is not the complete set of editor methods. Most of the
+ // methods defined on the Doc type are also injected into
+ // CodeMirror.prototype, for backwards compatibility and
+ // convenience.
+
+ CodeMirror.prototype = {
+ constructor: CodeMirror,
+ focus: function(){window.focus(); this.display.input.focus();},
+
+ setOption: function(option, value) {
+ var options = this.options, old = options[option];
+ if (options[option] == value && option != "mode") return;
+ options[option] = value;
+ if (optionHandlers.hasOwnProperty(option))
+ operation(this, optionHandlers[option])(this, value, old);
+ },
+
+ getOption: function(option) {return this.options[option];},
+ getDoc: function() {return this.doc;},
+
+ addKeyMap: function(map, bottom) {
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
+ },
+ removeKeyMap: function(map) {
+ var maps = this.state.keyMaps;
+ for (var i = 0; i < maps.length; ++i)
+ if (maps[i] == map || maps[i].name == map) {
+ maps.splice(i, 1);
+ return true;
+ }
+ },
+
+ addOverlay: methodOp(function(spec, options) {
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
+ if (mode.startState) throw new Error("Overlays may not be stateful.");
+ this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
+ this.state.modeGen++;
+ regChange(this);
+ }),
+ removeOverlay: methodOp(function(spec) {
+ var overlays = this.state.overlays;
+ for (var i = 0; i < overlays.length; ++i) {
+ var cur = overlays[i].modeSpec;
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
+ overlays.splice(i, 1);
+ this.state.modeGen++;
+ regChange(this);
+ return;
+ }
+ }
+ }),
+
+ indentLine: methodOp(function(n, dir, aggressive) {
+ if (typeof dir != "string" && typeof dir != "number") {
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
+ else dir = dir ? "add" : "subtract";
+ }
+ if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
+ }),
+ indentSelection: methodOp(function(how) {
+ var ranges = this.doc.sel.ranges, end = -1;
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ if (!range.empty()) {
+ var from = range.from(), to = range.to();
+ var start = Math.max(end, from.line);
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
+ for (var j = start; j < end; ++j)
+ indentLine(this, j, how);
+ var newRanges = this.doc.sel.ranges;
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
+ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
+ } else if (range.head.line > end) {
+ indentLine(this, range.head.line, how, true);
+ end = range.head.line;
+ if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
+ }
+ }
+ }),
+
+ // Fetch the parser token for a given character. Useful for hacks
+ // that want to inspect the mode state (say, for completion).
+ getTokenAt: function(pos, precise) {
+ return takeToken(this, pos, precise);
+ },
+
+ getLineTokens: function(line, precise) {
+ return takeToken(this, Pos(line), precise, true);
+ },
+
+ getTokenTypeAt: function(pos) {
+ pos = clipPos(this.doc, pos);
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
+ var type;
+ if (ch == 0) type = styles[2];
+ else for (;;) {
+ var mid = (before + after) >> 1;
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
+ else if (styles[mid * 2 + 1] < ch) before = mid + 1;
+ else { type = styles[mid * 2 + 2]; break; }
+ }
+ var cut = type ? type.indexOf("cm-overlay ") : -1;
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
+ },
+
+ getModeAt: function(pos) {
+ var mode = this.doc.mode;
+ if (!mode.innerMode) return mode;
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
+ },
+
+ getHelper: function(pos, type) {
+ return this.getHelpers(pos, type)[0];
+ },
+
+ getHelpers: function(pos, type) {
+ var found = [];
+ if (!helpers.hasOwnProperty(type)) return found;
+ var help = helpers[type], mode = this.getModeAt(pos);
+ if (typeof mode[type] == "string") {
+ if (help[mode[type]]) found.push(help[mode[type]]);
+ } else if (mode[type]) {
+ for (var i = 0; i < mode[type].length; i++) {
+ var val = help[mode[type][i]];
+ if (val) found.push(val);
+ }
+ } else if (mode.helperType && help[mode.helperType]) {
+ found.push(help[mode.helperType]);
+ } else if (help[mode.name]) {
+ found.push(help[mode.name]);
+ }
+ for (var i = 0; i < help._global.length; i++) {
+ var cur = help._global[i];
+ if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
+ found.push(cur.val);
+ }
+ return found;
+ },
+
+ getStateAfter: function(line, precise) {
+ var doc = this.doc;
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
+ return getStateBefore(this, line + 1, precise);
+ },
+
+ cursorCoords: function(start, mode) {
+ var pos, range = this.doc.sel.primary();
+ if (start == null) pos = range.head;
+ else if (typeof start == "object") pos = clipPos(this.doc, start);
+ else pos = start ? range.from() : range.to();
+ return cursorCoords(this, pos, mode || "page");
+ },
+
+ charCoords: function(pos, mode) {
+ return charCoords(this, clipPos(this.doc, pos), mode || "page");
+ },
+
+ coordsChar: function(coords, mode) {
+ coords = fromCoordSystem(this, coords, mode || "page");
+ return coordsChar(this, coords.left, coords.top);
+ },
+
+ lineAtHeight: function(height, mode) {
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
+ return lineAtHeight(this.doc, height + this.display.viewOffset);
+ },
+ heightAtLine: function(line, mode) {
+ var end = false, lineObj;
+ if (typeof line == "number") {
+ var last = this.doc.first + this.doc.size - 1;
+ if (line < this.doc.first) line = this.doc.first;
+ else if (line > last) { line = last; end = true; }
+ lineObj = getLine(this.doc, line);
+ } else {
+ lineObj = line;
+ }
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
+ (end ? this.doc.height - heightAtLine(lineObj) : 0);
+ },
+
+ defaultTextHeight: function() { return textHeight(this.display); },
+ defaultCharWidth: function() { return charWidth(this.display); },
+
+ setGutterMarker: methodOp(function(line, gutterID, value) {
+ return changeLine(this.doc, line, "gutter", function(line) {
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
+ markers[gutterID] = value;
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
+ return true;
+ });
+ }),
+
+ clearGutter: methodOp(function(gutterID) {
+ var cm = this, doc = cm.doc, i = doc.first;
+ doc.iter(function(line) {
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
+ line.gutterMarkers[gutterID] = null;
+ regLineChange(cm, i, "gutter");
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
+ }
+ ++i;
+ });
+ }),
+
+ lineInfo: function(line) {
+ if (typeof line == "number") {
+ if (!isLine(this.doc, line)) return null;
+ var n = line;
+ line = getLine(this.doc, line);
+ if (!line) return null;
+ } else {
+ var n = lineNo(line);
+ if (n == null) return null;
+ }
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
+ widgets: line.widgets};
+ },
+
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
+
+ addWidget: function(pos, node, scroll, vert, horiz) {
+ var display = this.display;
+ pos = cursorCoords(this, clipPos(this.doc, pos));
+ var top = pos.bottom, left = pos.left;
+ node.style.position = "absolute";
+ node.setAttribute("cm-ignore-events", "true");
+ this.display.input.setUneditable(node);
+ display.sizer.appendChild(node);
+ if (vert == "over") {
+ top = pos.top;
+ } else if (vert == "above" || vert == "near") {
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
+ top = pos.top - node.offsetHeight;
+ else if (pos.bottom + node.offsetHeight <= vspace)
+ top = pos.bottom;
+ if (left + node.offsetWidth > hspace)
+ left = hspace - node.offsetWidth;
+ }
+ node.style.top = top + "px";
+ node.style.left = node.style.right = "";
+ if (horiz == "right") {
+ left = display.sizer.clientWidth - node.offsetWidth;
+ node.style.right = "0px";
+ } else {
+ if (horiz == "left") left = 0;
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
+ node.style.left = left + "px";
+ }
+ if (scroll)
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
+ },
+
+ triggerOnKeyDown: methodOp(onKeyDown),
+ triggerOnKeyPress: methodOp(onKeyPress),
+ triggerOnKeyUp: onKeyUp,
+
+ execCommand: function(cmd) {
+ if (commands.hasOwnProperty(cmd))
+ return commands[cmd](this);
+ },
+
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
+
+ findPosH: function(from, amount, unit, visually) {
+ var dir = 1;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
+ cur = findPosH(this.doc, cur, dir, unit, visually);
+ if (cur.hitSide) break;
+ }
+ return cur;
+ },
+
+ moveH: methodOp(function(dir, unit) {
+ var cm = this;
+ cm.extendSelectionsBy(function(range) {
+ if (cm.display.shift || cm.doc.extend || range.empty())
+ return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
+ else
+ return dir < 0 ? range.from() : range.to();
+ }, sel_move);
+ }),
+
+ deleteH: methodOp(function(dir, unit) {
+ var sel = this.doc.sel, doc = this.doc;
+ if (sel.somethingSelected())
+ doc.replaceSelection("", null, "+delete");
+ else
+ deleteNearSelection(this, function(range) {
+ var other = findPosH(doc, range.head, dir, unit, false);
+ return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
+ });
+ }),
+
+ findPosV: function(from, amount, unit, goalColumn) {
+ var dir = 1, x = goalColumn;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
+ var coords = cursorCoords(this, cur, "div");
+ if (x == null) x = coords.left;
+ else coords.left = x;
+ cur = findPosV(this, coords, dir, unit);
+ if (cur.hitSide) break;
+ }
+ return cur;
+ },
+
+ moveV: methodOp(function(dir, unit) {
+ var cm = this, doc = this.doc, goals = [];
+ var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
+ doc.extendSelectionsBy(function(range) {
+ if (collapse)
+ return dir < 0 ? range.from() : range.to();
+ var headPos = cursorCoords(cm, range.head, "div");
+ if (range.goalColumn != null) headPos.left = range.goalColumn;
+ goals.push(headPos.left);
+ var pos = findPosV(cm, headPos, dir, unit);
+ if (unit == "page" && range == doc.sel.primary())
+ addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
+ return pos;
+ }, sel_move);
+ if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
+ doc.sel.ranges[i].goalColumn = goals[i];
+ }),
+
+ // Find the word at the given position (as returned by coordsChar).
+ findWordAt: function(pos) {
+ var doc = this.doc, line = getLine(doc, pos.line).text;
+ var start = pos.ch, end = pos.ch;
+ if (line) {
+ var helper = this.getHelper(pos, "wordChars");
+ if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
+ var startChar = line.charAt(start);
+ var check = isWordChar(startChar, helper)
+ ? function(ch) { return isWordChar(ch, helper); }
+ : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
+ : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
+ while (start > 0 && check(line.charAt(start - 1))) --start;
+ while (end < line.length && check(line.charAt(end))) ++end;
+ }
+ return new Range(Pos(pos.line, start), Pos(pos.line, end));
+ },
+
+ toggleOverwrite: function(value) {
+ if (value != null && value == this.state.overwrite) return;
+ if (this.state.overwrite = !this.state.overwrite)
+ addClass(this.display.cursorDiv, "CodeMirror-overwrite");
+ else
+ rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
+
+ signal(this, "overwriteToggle", this, this.state.overwrite);
+ },
+ hasFocus: function() { return this.display.input.getField() == activeElt(); },
+
+ scrollTo: methodOp(function(x, y) {
+ if (x != null || y != null) resolveScrollToPos(this);
+ if (x != null) this.curOp.scrollLeft = x;
+ if (y != null) this.curOp.scrollTop = y;
+ }),
+ getScrollInfo: function() {
+ var scroller = this.display.scroller;
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
+ },
+
+ scrollIntoView: methodOp(function(range, margin) {
+ if (range == null) {
+ range = {from: this.doc.sel.primary().head, to: null};
+ if (margin == null) margin = this.options.cursorScrollMargin;
+ } else if (typeof range == "number") {
+ range = {from: Pos(range, 0), to: null};
+ } else if (range.from == null) {
+ range = {from: range, to: null};
+ }
+ if (!range.to) range.to = range.from;
+ range.margin = margin || 0;
+
+ if (range.from.line != null) {
+ resolveScrollToPos(this);
+ this.curOp.scrollToPos = range;
+ } else {
+ var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
+ Math.min(range.from.top, range.to.top) - range.margin,
+ Math.max(range.from.right, range.to.right),
+ Math.max(range.from.bottom, range.to.bottom) + range.margin);
+ this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
+ }
+ }),
+
+ setSize: methodOp(function(width, height) {
+ var cm = this;
+ function interpret(val) {
+ return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
+ }
+ if (width != null) cm.display.wrapper.style.width = interpret(width);
+ if (height != null) cm.display.wrapper.style.height = interpret(height);
+ if (cm.options.lineWrapping) clearLineMeasurementCache(this);
+ var lineNo = cm.display.viewFrom;
+ cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
+ if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
+ ++lineNo;
+ });
+ cm.curOp.forceUpdate = true;
+ signal(cm, "refresh", this);
+ }),
+
+ operation: function(f){return runInOp(this, f);},
+
+ refresh: methodOp(function() {
+ var oldHeight = this.display.cachedTextHeight;
+ regChange(this);
+ this.curOp.forceUpdate = true;
+ clearCaches(this);
+ this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
+ updateGutterSpace(this);
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
+ estimateLineHeights(this);
+ signal(this, "refresh", this);
+ }),
+
+ swapDoc: methodOp(function(doc) {
+ var old = this.doc;
+ old.cm = null;
+ attachDoc(this, doc);
+ clearCaches(this);
+ this.display.input.reset();
+ this.scrollTo(doc.scrollLeft, doc.scrollTop);
+ this.curOp.forceScroll = true;
+ signalLater(this, "swapDoc", this, old);
+ return old;
+ }),
+
+ getInputField: function(){return this.display.input.getField();},
+ getWrapperElement: function(){return this.display.wrapper;},
+ getScrollerElement: function(){return this.display.scroller;},
+ getGutterElement: function(){return this.display.gutters;}
+ };
+ eventMixin(CodeMirror);
+
+ // OPTION DEFAULTS
+
+ // The default configuration options.
+ var defaults = CodeMirror.defaults = {};
+ // Functions to run when options are changed.
+ var optionHandlers = CodeMirror.optionHandlers = {};
+
+ function option(name, deflt, handle, notOnInit) {
+ CodeMirror.defaults[name] = deflt;
+ if (handle) optionHandlers[name] =
+ notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
+ }
+
+ // Passed to option handlers when there is no old value.
+ var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
+
+ // These two are, on init, called from the constructor because they
+ // have to be initialized before the editor can start at all.
+ option("value", "", function(cm, val) {
+ cm.setValue(val);
+ }, true);
+ option("mode", null, function(cm, val) {
+ cm.doc.modeOption = val;
+ loadMode(cm);
+ }, true);
+
+ option("indentUnit", 2, loadMode, true);
+ option("indentWithTabs", false);
+ option("smartIndent", true);
+ option("tabSize", 4, function(cm) {
+ resetModeState(cm);
+ clearCaches(cm);
+ regChange(cm);
+ }, true);
+ option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
+ if (old != CodeMirror.Init) cm.refresh();
+ });
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
+ option("electricChars", true);
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
+ throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
+ }, true);
+ option("rtlMoveVisually", !windows);
+ option("wholeLineUpdateBefore", true);
+
+ option("theme", "default", function(cm) {
+ themeChanged(cm);
+ guttersChanged(cm);
+ }, true);
+ option("keyMap", "default", function(cm, val, old) {
+ var next = getKeyMap(val);
+ var prev = old != CodeMirror.Init && getKeyMap(old);
+ if (prev && prev.detach) prev.detach(cm, next);
+ if (next.attach) next.attach(cm, prev || null);
+ });
+ option("extraKeys", null);
+
+ option("lineWrapping", false, wrappingChanged, true);
+ option("gutters", [], function(cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("fixedGutter", true, function(cm, val) {
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
+ cm.refresh();
+ }, true);
+ option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
+ option("scrollbarStyle", "native", function(cm) {
+ initScrollbars(cm);
+ updateScrollbars(cm);
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
+ }, true);
+ option("lineNumbers", false, function(cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("firstLineNumber", 1, guttersChanged, true);
+ option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
+ option("showCursorWhenSelecting", false, updateSelection, true);
+
+ option("resetSelectionOnContextMenu", true);
+ option("lineWiseCopyCut", true);
+
+ option("readOnly", false, function(cm, val) {
+ if (val == "nocursor") {
+ onBlur(cm);
+ cm.display.input.blur();
+ cm.display.disabled = true;
+ } else {
+ cm.display.disabled = false;
+ if (!val) cm.display.input.reset();
+ }
+ });
+ option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
+ option("dragDrop", true, dragDropChanged);
+
+ option("cursorBlinkRate", 530);
+ option("cursorScrollMargin", 0);
+ option("cursorHeight", 1, updateSelection, true);
+ option("singleCursorHeightPerLine", true, updateSelection, true);
+ option("workTime", 100);
+ option("workDelay", 100);
+ option("flattenSpans", true, resetModeState, true);
+ option("addModeClass", false, resetModeState, true);
+ option("pollInterval", 100);
+ option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
+ option("historyEventDelay", 1250);
+ option("viewportMargin", 10, function(cm){cm.refresh();}, true);
+ option("maxHighlightLength", 10000, resetModeState, true);
+ option("moveInputWithCursor", true, function(cm, val) {
+ if (!val) cm.display.input.resetPosition();
+ });
+
+ option("tabindex", null, function(cm, val) {
+ cm.display.input.getField().tabIndex = val || "";
+ });
+ option("autofocus", null);
+
+ // MODE DEFINITION AND QUERYING
+
+ // Known modes, by name and by MIME
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
+
+ // Extra arguments are stored as the mode's dependencies, which is
+ // used by (legacy) mechanisms like loadmode.js to automatically
+ // load a mode. (Preferred mechanism is the require/define calls.)
+ CodeMirror.defineMode = function(name, mode) {
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
+ if (arguments.length > 2)
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
+ modes[name] = mode;
+ };
+
+ CodeMirror.defineMIME = function(mime, spec) {
+ mimeModes[mime] = spec;
+ };
+
+ // Given a MIME type, a {name, ...options} config object, or a name
+ // string, return a mode config object.
+ CodeMirror.resolveMode = function(spec) {
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
+ spec = mimeModes[spec];
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
+ var found = mimeModes[spec.name];
+ if (typeof found == "string") found = {name: found};
+ spec = createObj(found, spec);
+ spec.name = found.name;
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
+ return CodeMirror.resolveMode("application/xml");
+ }
+ if (typeof spec == "string") return {name: spec};
+ else return spec || {name: "null"};
+ };
+
+ // Given a mode spec (anything that resolveMode accepts), find and
+ // initialize an actual mode object.
+ CodeMirror.getMode = function(options, spec) {
+ var spec = CodeMirror.resolveMode(spec);
+ var mfactory = modes[spec.name];
+ if (!mfactory) return CodeMirror.getMode(options, "text/plain");
+ var modeObj = mfactory(options, spec);
+ if (modeExtensions.hasOwnProperty(spec.name)) {
+ var exts = modeExtensions[spec.name];
+ for (var prop in exts) {
+ if (!exts.hasOwnProperty(prop)) continue;
+ if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
+ modeObj[prop] = exts[prop];
+ }
+ }
+ modeObj.name = spec.name;
+ if (spec.helperType) modeObj.helperType = spec.helperType;
+ if (spec.modeProps) for (var prop in spec.modeProps)
+ modeObj[prop] = spec.modeProps[prop];
+
+ return modeObj;
+ };
+
+ // Minimal default mode.
+ CodeMirror.defineMode("null", function() {
+ return {token: function(stream) {stream.skipToEnd();}};
+ });
+ CodeMirror.defineMIME("text/plain", "null");
+
+ // This can be used to attach properties to mode objects from
+ // outside the actual mode definition.
+ var modeExtensions = CodeMirror.modeExtensions = {};
+ CodeMirror.extendMode = function(mode, properties) {
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
+ copyObj(properties, exts);
+ };
+
+ // EXTENSIONS
+
+ CodeMirror.defineExtension = function(name, func) {
+ CodeMirror.prototype[name] = func;
+ };
+ CodeMirror.defineDocExtension = function(name, func) {
+ Doc.prototype[name] = func;
+ };
+ CodeMirror.defineOption = option;
+
+ var initHooks = [];
+ CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
+
+ var helpers = CodeMirror.helpers = {};
+ CodeMirror.registerHelper = function(type, name, value) {
+ if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
+ helpers[type][name] = value;
+ };
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
+ CodeMirror.registerHelper(type, name, value);
+ helpers[type]._global.push({pred: predicate, val: value});
+ };
+
+ // MODE STATE HANDLING
+
+ // Utility functions for working with state. Exported because nested
+ // modes need to do this for their inner modes.
+
+ var copyState = CodeMirror.copyState = function(mode, state) {
+ if (state === true) return state;
+ if (mode.copyState) return mode.copyState(state);
+ var nstate = {};
+ for (var n in state) {
+ var val = state[n];
+ if (val instanceof Array) val = val.concat([]);
+ nstate[n] = val;
+ }
+ return nstate;
+ };
+
+ var startState = CodeMirror.startState = function(mode, a1, a2) {
+ return mode.startState ? mode.startState(a1, a2) : true;
+ };
+
+ // Given a mode and a state (for that mode), find the inner mode and
+ // state at the position that the state refers to.
+ CodeMirror.innerMode = function(mode, state) {
+ while (mode.innerMode) {
+ var info = mode.innerMode(state);
+ if (!info || info.mode == mode) break;
+ state = info.state;
+ mode = info.mode;
+ }
+ return info || {mode: mode, state: state};
+ };
+
+ // STANDARD COMMANDS
+
+ // Commands are parameter-less actions that can be performed on an
+ // editor, mostly used for keybindings.
+ var commands = CodeMirror.commands = {
+ selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
+ singleSelection: function(cm) {
+ cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
+ },
+ killLine: function(cm) {
+ deleteNearSelection(cm, function(range) {
+ if (range.empty()) {
+ var len = getLine(cm.doc, range.head.line).text.length;
+ if (range.head.ch == len && range.head.line < cm.lastLine())
+ return {from: range.head, to: Pos(range.head.line + 1, 0)};
+ else
+ return {from: range.head, to: Pos(range.head.line, len)};
+ } else {
+ return {from: range.from(), to: range.to()};
+ }
+ });
+ },
+ deleteLine: function(cm) {
+ deleteNearSelection(cm, function(range) {
+ return {from: Pos(range.from().line, 0),
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
+ });
+ },
+ delLineLeft: function(cm) {
+ deleteNearSelection(cm, function(range) {
+ return {from: Pos(range.from().line, 0), to: range.from()};
+ });
+ },
+ delWrappedLineLeft: function(cm) {
+ deleteNearSelection(cm, function(range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
+ return {from: leftPos, to: range.from()};
+ });
+ },
+ delWrappedLineRight: function(cm) {
+ deleteNearSelection(cm, function(range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
+ return {from: range.from(), to: rightPos };
+ });
+ },
+ undo: function(cm) {cm.undo();},
+ redo: function(cm) {cm.redo();},
+ undoSelection: function(cm) {cm.undoSelection();},
+ redoSelection: function(cm) {cm.redoSelection();},
+ goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
+ goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
+ goLineStart: function(cm) {
+ cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
+ {origin: "+move", bias: 1});
+ },
+ goLineStartSmart: function(cm) {
+ cm.extendSelectionsBy(function(range) {
+ return lineStartSmart(cm, range.head);
+ }, {origin: "+move", bias: 1});
+ },
+ goLineEnd: function(cm) {
+ cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
+ {origin: "+move", bias: -1});
+ },
+ goLineRight: function(cm) {
+ cm.extendSelectionsBy(function(range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
+ }, sel_move);
+ },
+ goLineLeft: function(cm) {
+ cm.extendSelectionsBy(function(range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: 0, top: top}, "div");
+ }, sel_move);
+ },
+ goLineLeftSmart: function(cm) {
+ cm.extendSelectionsBy(function(range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
+ return pos;
+ }, sel_move);
+ },
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
+ goLineDown: function(cm) {cm.moveV(1, "line");},
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
+ goPageDown: function(cm) {cm.moveV(1, "page");},
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
+ goCharRight: function(cm) {cm.moveH(1, "char");},
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
+ goGroupRight: function(cm) {cm.moveH(1, "group");},
+ goGroupLeft: function(cm) {cm.moveH(-1, "group");},
+ goWordRight: function(cm) {cm.moveH(1, "word");},
+ delCharBefore: function(cm) {cm.deleteH(-1, "char");},
+ delCharAfter: function(cm) {cm.deleteH(1, "char");},
+ delWordBefore: function(cm) {cm.deleteH(-1, "word");},
+ delWordAfter: function(cm) {cm.deleteH(1, "word");},
+ delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
+ delGroupAfter: function(cm) {cm.deleteH(1, "group");},
+ indentAuto: function(cm) {cm.indentSelection("smart");},
+ indentMore: function(cm) {cm.indentSelection("add");},
+ indentLess: function(cm) {cm.indentSelection("subtract");},
+ insertTab: function(cm) {cm.replaceSelection("\t");},
+ insertSoftTab: function(cm) {
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
+ for (var i = 0; i < ranges.length; i++) {
+ var pos = ranges[i].from();
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
+ spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
+ }
+ cm.replaceSelections(spaces);
+ },
+ defaultTab: function(cm) {
+ if (cm.somethingSelected()) cm.indentSelection("add");
+ else cm.execCommand("insertTab");
+ },
+ transposeChars: function(cm) {
+ runInOp(cm, function() {
+ var ranges = cm.listSelections(), newSel = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
+ if (line) {
+ if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
+ if (cur.ch > 0) {
+ cur = new Pos(cur.line, cur.ch + 1);
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
+ } else if (cur.line > cm.doc.first) {
+ var prev = getLine(cm.doc, cur.line - 1).text;
+ if (prev)
+ cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),
+ Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
+ }
+ }
+ newSel.push(new Range(cur, cur));
+ }
+ cm.setSelections(newSel);
+ });
+ },
+ newlineAndIndent: function(cm) {
+ runInOp(cm, function() {
+ var len = cm.listSelections().length;
+ for (var i = 0; i < len; i++) {
+ var range = cm.listSelections()[i];
+ cm.replaceRange("\n", range.anchor, range.head, "+input");
+ cm.indentLine(range.from().line + 1, null, true);
+ ensureCursorVisible(cm);
+ }
+ });
+ },
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
+ };
+
+
+ // STANDARD KEYMAPS
+
+ var keyMap = CodeMirror.keyMap = {};
+
+ keyMap.basic = {
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
+ "Esc": "singleSelection"
+ };
+ // Note that the save and find-related commands aren't defined by
+ // default. User code or addons can define them. Unknown commands
+ // are simply ignored.
+ keyMap.pcDefault = {
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
+ fallthrough: "basic"
+ };
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
+ keyMap.emacsy = {
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
+ };
+ keyMap.macDefault = {
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
+ fallthrough: ["basic", "emacsy"]
+ };
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
+
+ // KEYMAP DISPATCH
+
+ function normalizeKeyName(name) {
+ var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
+ var alt, ctrl, shift, cmd;
+ for (var i = 0; i < parts.length - 1; i++) {
+ var mod = parts[i];
+ if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
+ else if (/^a(lt)?$/i.test(mod)) alt = true;
+ else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
+ else if (/^s(hift)$/i.test(mod)) shift = true;
+ else throw new Error("Unrecognized modifier name: " + mod);
+ }
+ if (alt) name = "Alt-" + name;
+ if (ctrl) name = "Ctrl-" + name;
+ if (cmd) name = "Cmd-" + name;
+ if (shift) name = "Shift-" + name;
+ return name;
+ }
+
+ // This is a kludge to keep keymaps mostly working as raw objects
+ // (backwards compatibility) while at the same time support features
+ // like normalization and multi-stroke key bindings. It compiles a
+ // new normalized keymap, and then updates the old object to reflect
+ // this.
+ CodeMirror.normalizeKeyMap = function(keymap) {
+ var copy = {};
+ for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
+ var value = keymap[keyname];
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
+ if (value == "...") { delete keymap[keyname]; continue; }
+
+ var keys = map(keyname.split(" "), normalizeKeyName);
+ for (var i = 0; i < keys.length; i++) {
+ var val, name;
+ if (i == keys.length - 1) {
+ name = keys.join(" ");
+ val = value;
+ } else {
+ name = keys.slice(0, i + 1).join(" ");
+ val = "...";
+ }
+ var prev = copy[name];
+ if (!prev) copy[name] = val;
+ else if (prev != val) throw new Error("Inconsistent bindings for " + name);
+ }
+ delete keymap[keyname];
+ }
+ for (var prop in copy) keymap[prop] = copy[prop];
+ return keymap;
+ };
+
+ var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
+ map = getKeyMap(map);
+ var found = map.call ? map.call(key, context) : map[key];
+ if (found === false) return "nothing";
+ if (found === "...") return "multi";
+ if (found != null && handle(found)) return "handled";
+
+ if (map.fallthrough) {
+ if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
+ return lookupKey(key, map.fallthrough, handle, context);
+ for (var i = 0; i < map.fallthrough.length; i++) {
+ var result = lookupKey(key, map.fallthrough[i], handle, context);
+ if (result) return result;
+ }
+ }
+ };
+
+ // Modifier key presses don't count as 'real' key presses for the
+ // purpose of keymap fallthrough.
+ var isModifierKey = CodeMirror.isModifierKey = function(value) {
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
+ };
+
+ // Look up the name of a key as indicated by an event object.
+ var keyName = CodeMirror.keyName = function(event, noShift) {
+ if (presto && event.keyCode == 34 && event["char"]) return false;
+ var base = keyNames[event.keyCode], name = base;
+ if (name == null || event.altGraphKey) return false;
+ if (event.altKey && base != "Alt") name = "Alt-" + name;
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
+ if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
+ return name;
+ };
+
+ function getKeyMap(val) {
+ return typeof val == "string" ? keyMap[val] : val;
+ }
+
+ // FROMTEXTAREA
+
+ CodeMirror.fromTextArea = function(textarea, options) {
+ options = options ? copyObj(options) : {};
+ options.value = textarea.value;
+ if (!options.tabindex && textarea.tabIndex)
+ options.tabindex = textarea.tabIndex;
+ if (!options.placeholder && textarea.placeholder)
+ options.placeholder = textarea.placeholder;
+ // Set autofocus to true if this textarea is focused, or if it has
+ // autofocus and no other element is focused.
+ if (options.autofocus == null) {
+ var hasFocus = activeElt();
+ options.autofocus = hasFocus == textarea ||
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
+ }
+
+ function save() {textarea.value = cm.getValue();}
+ if (textarea.form) {
+ on(textarea.form, "submit", save);
+ // Deplorable hack to make the submit method do the right thing.
+ if (!options.leaveSubmitMethodAlone) {
+ var form = textarea.form, realSubmit = form.submit;
+ try {
+ var wrappedSubmit = form.submit = function() {
+ save();
+ form.submit = realSubmit;
+ form.submit();
+ form.submit = wrappedSubmit;
+ };
+ } catch(e) {}
+ }
+ }
+
+ options.finishInit = function(cm) {
+ cm.save = save;
+ cm.getTextArea = function() { return textarea; };
+ cm.toTextArea = function() {
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
+ save();
+ textarea.parentNode.removeChild(cm.getWrapperElement());
+ textarea.style.display = "";
+ if (textarea.form) {
+ off(textarea.form, "submit", save);
+ if (typeof textarea.form.submit == "function")
+ textarea.form.submit = realSubmit;
+ }
+ };
+ };
+
+ textarea.style.display = "none";
+ var cm = CodeMirror(function(node) {
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
+ }, options);
+ return cm;
+ };
+
+ // STRING STREAM
+
+ // Fed to the mode parsers, provides helper functions to make
+ // parsers more succinct.
+
+ var StringStream = CodeMirror.StringStream = function(string, tabSize) {
+ this.pos = this.start = 0;
+ this.string = string;
+ this.tabSize = tabSize || 8;
+ this.lastColumnPos = this.lastColumnValue = 0;
+ this.lineStart = 0;
+ };
+
+ StringStream.prototype = {
+ eol: function() {return this.pos >= this.string.length;},
+ sol: function() {return this.pos == this.lineStart;},
+ peek: function() {return this.string.charAt(this.pos) || undefined;},
+ next: function() {
+ if (this.pos < this.string.length)
+ return this.string.charAt(this.pos++);
+ },
+ eat: function(match) {
+ var ch = this.string.charAt(this.pos);
+ if (typeof match == "string") var ok = ch == match;
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
+ if (ok) {++this.pos; return ch;}
+ },
+ eatWhile: function(match) {
+ var start = this.pos;
+ while (this.eat(match)){}
+ return this.pos > start;
+ },
+ eatSpace: function() {
+ var start = this.pos;
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
+ return this.pos > start;
+ },
+ skipToEnd: function() {this.pos = this.string.length;},
+ skipTo: function(ch) {
+ var found = this.string.indexOf(ch, this.pos);
+ if (found > -1) {this.pos = found; return true;}
+ },
+ backUp: function(n) {this.pos -= n;},
+ column: function() {
+ if (this.lastColumnPos < this.start) {
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
+ this.lastColumnPos = this.start;
+ }
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
+ },
+ indentation: function() {
+ return countColumn(this.string, null, this.tabSize) -
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
+ },
+ match: function(pattern, consume, caseInsensitive) {
+ if (typeof pattern == "string") {
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
+ var substr = this.string.substr(this.pos, pattern.length);
+ if (cased(substr) == cased(pattern)) {
+ if (consume !== false) this.pos += pattern.length;
+ return true;
+ }
+ } else {
+ var match = this.string.slice(this.pos).match(pattern);
+ if (match && match.index > 0) return null;
+ if (match && consume !== false) this.pos += match[0].length;
+ return match;
+ }
+ },
+ current: function(){return this.string.slice(this.start, this.pos);},
+ hideFirstChars: function(n, inner) {
+ this.lineStart += n;
+ try { return inner(); }
+ finally { this.lineStart -= n; }
+ }
+ };
+
+ // TEXTMARKERS
+
+ // Created with markText and setBookmark methods. A TextMarker is a
+ // handle that can be used to clear or find a marked position in the
+ // document. Line objects hold arrays (markedSpans) containing
+ // {from, to, marker} object pointing to such marker objects, and
+ // indicating that such a marker is present on that line. Multiple
+ // lines may point to the same marker when it spans across lines.
+ // The spans will have null for their from/to properties when the
+ // marker continues beyond the start/end of the line. Markers have
+ // links back to the lines they currently touch.
+
+ var nextMarkerId = 0;
+
+ var TextMarker = CodeMirror.TextMarker = function(doc, type) {
+ this.lines = [];
+ this.type = type;
+ this.doc = doc;
+ this.id = ++nextMarkerId;
+ };
+ eventMixin(TextMarker);
+
+ // Clear the marker.
+ TextMarker.prototype.clear = function() {
+ if (this.explicitlyCleared) return;
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
+ if (withOp) startOperation(cm);
+ if (hasHandler(this, "clear")) {
+ var found = this.find();
+ if (found) signalLater(this, "clear", found.from, found.to);
+ }
+ var min = null, max = null;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this);
+ if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
+ else if (cm) {
+ if (span.to != null) max = lineNo(line);
+ if (span.from != null) min = lineNo(line);
+ }
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
+ if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
+ updateLineHeight(line, textHeight(cm.display));
+ }
+ if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
+ var visual = visualLine(this.lines[i]), len = lineLength(visual);
+ if (len > cm.display.maxLineLength) {
+ cm.display.maxLine = visual;
+ cm.display.maxLineLength = len;
+ cm.display.maxLineChanged = true;
+ }
+ }
+
+ if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
+ this.lines.length = 0;
+ this.explicitlyCleared = true;
+ if (this.atomic && this.doc.cantEdit) {
+ this.doc.cantEdit = false;
+ if (cm) reCheckSelection(cm.doc);
+ }
+ if (cm) signalLater(cm, "markerCleared", cm, this);
+ if (withOp) endOperation(cm);
+ if (this.parent) this.parent.clear();
+ };
+
+ // Find the position of the marker in the document. Returns a {from,
+ // to} object by default. Side can be passed to get a specific side
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
+ // Pos objects returned contain a line object, rather than a line
+ // number (used to prevent looking up the same line twice).
+ TextMarker.prototype.find = function(side, lineObj) {
+ if (side == null && this.type == "bookmark") side = 1;
+ var from, to;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this);
+ if (span.from != null) {
+ from = Pos(lineObj ? line : lineNo(line), span.from);
+ if (side == -1) return from;
+ }
+ if (span.to != null) {
+ to = Pos(lineObj ? line : lineNo(line), span.to);
+ if (side == 1) return to;
+ }
+ }
+ return from && {from: from, to: to};
+ };
+
+ // Signals that the marker's widget changed, and surrounding layout
+ // should be recomputed.
+ TextMarker.prototype.changed = function() {
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
+ if (!pos || !cm) return;
+ runInOp(cm, function() {
+ var line = pos.line, lineN = lineNo(pos.line);
+ var view = findViewForLine(cm, lineN);
+ if (view) {
+ clearLineMeasurementCacheFor(view);
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
+ }
+ cm.curOp.updateMaxLine = true;
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
+ var oldHeight = widget.height;
+ widget.height = null;
+ var dHeight = widgetHeight(widget) - oldHeight;
+ if (dHeight)
+ updateLineHeight(line, line.height + dHeight);
+ }
+ });
+ };
+
+ TextMarker.prototype.attachLine = function(line) {
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp;
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
+ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
+ }
+ this.lines.push(line);
+ };
+ TextMarker.prototype.detachLine = function(line) {
+ this.lines.splice(indexOf(this.lines, line), 1);
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp;
+ (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
+ }
+ };
+
+ // Collapsed markers have unique ids, in order to be able to order
+ // them, which is needed for uniquely determining an outer marker
+ // when they overlap (they may nest, but not partially overlap).
+ var nextMarkerId = 0;
+
+ // Create a marker, wire it up to the right lines, and
+ function markText(doc, from, to, options, type) {
+ // Shared markers (across linked documents) are handled separately
+ // (markTextShared will call out to this again, once per
+ // document).
+ if (options && options.shared) return markTextShared(doc, from, to, options, type);
+ // Ensure we are in an operation.
+ if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
+
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
+ if (options) copyObj(options, marker, false);
+ // Don't connect empty markers unless clearWhenEmpty is false
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
+ return marker;
+ if (marker.replacedWith) {
+ // Showing up as a widget implies collapsed (widget replaces text)
+ marker.collapsed = true;
+ marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
+ if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
+ if (options.insertLeft) marker.widgetNode.insertLeft = true;
+ }
+ if (marker.collapsed) {
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
+ throw new Error("Inserting collapsed marker partially overlapping an existing one");
+ sawCollapsedSpans = true;
+ }
+
+ if (marker.addToHistory)
+ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
+
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
+ doc.iter(curLine, to.line + 1, function(line) {
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
+ updateMaxLine = true;
+ if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
+ addMarkedSpan(line, new MarkedSpan(marker,
+ curLine == from.line ? from.ch : null,
+ curLine == to.line ? to.ch : null));
+ ++curLine;
+ });
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
+ if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
+ if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
+ });
+
+ if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
+
+ if (marker.readOnly) {
+ sawReadOnlySpans = true;
+ if (doc.history.done.length || doc.history.undone.length)
+ doc.clearHistory();
+ }
+ if (marker.collapsed) {
+ marker.id = ++nextMarkerId;
+ marker.atomic = true;
+ }
+ if (cm) {
+ // Sync editor state
+ if (updateMaxLine) cm.curOp.updateMaxLine = true;
+ if (marker.collapsed)
+ regChange(cm, from.line, to.line + 1);
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
+ for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
+ if (marker.atomic) reCheckSelection(cm.doc);
+ signalLater(cm, "markerAdded", cm, marker);
+ }
+ return marker;
+ }
+
+ // SHARED TEXTMARKERS
+
+ // A shared marker spans multiple linked documents. It is
+ // implemented as a meta-marker-object controlling multiple normal
+ // markers.
+ var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
+ this.markers = markers;
+ this.primary = primary;
+ for (var i = 0; i < markers.length; ++i)
+ markers[i].parent = this;
+ };
+ eventMixin(SharedTextMarker);
+
+ SharedTextMarker.prototype.clear = function() {
+ if (this.explicitlyCleared) return;
+ this.explicitlyCleared = true;
+ for (var i = 0; i < this.markers.length; ++i)
+ this.markers[i].clear();
+ signalLater(this, "clear");
+ };
+ SharedTextMarker.prototype.find = function(side, lineObj) {
+ return this.primary.find(side, lineObj);
+ };
+
+ function markTextShared(doc, from, to, options, type) {
+ options = copyObj(options);
+ options.shared = false;
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
+ var widget = options.widgetNode;
+ linkedDocs(doc, function(doc) {
+ if (widget) options.widgetNode = widget.cloneNode(true);
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
+ for (var i = 0; i < doc.linked.length; ++i)
+ if (doc.linked[i].isParent) return;
+ primary = lst(markers);
+ });
+ return new SharedTextMarker(markers, primary);
+ }
+
+ function findSharedMarkers(doc) {
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
+ function(m) { return m.parent; });
+ }
+
+ function copySharedMarkers(doc, markers) {
+ for (var i = 0; i < markers.length; i++) {
+ var marker = markers[i], pos = marker.find();
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
+ if (cmp(mFrom, mTo)) {
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
+ marker.markers.push(subMark);
+ subMark.parent = marker;
+ }
+ }
+ }
+
+ function detachSharedMarkers(markers) {
+ for (var i = 0; i < markers.length; i++) {
+ var marker = markers[i], linked = [marker.primary.doc];;
+ linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
+ for (var j = 0; j < marker.markers.length; j++) {
+ var subMarker = marker.markers[j];
+ if (indexOf(linked, subMarker.doc) == -1) {
+ subMarker.parent = null;
+ marker.markers.splice(j--, 1);
+ }
+ }
+ }
+ }
+
+ // TEXTMARKER SPANS
+
+ function MarkedSpan(marker, from, to) {
+ this.marker = marker;
+ this.from = from; this.to = to;
+ }
+
+ // Search an array of spans for a span matching the given marker.
+ function getMarkedSpanFor(spans, marker) {
+ if (spans) for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.marker == marker) return span;
+ }
+ }
+ // Remove a span from an array, returning undefined if no spans are
+ // left (we don't store arrays for lines without spans).
+ function removeMarkedSpan(spans, span) {
+ for (var r, i = 0; i < spans.length; ++i)
+ if (spans[i] != span) (r || (r = [])).push(spans[i]);
+ return r;
+ }
+ // Add a span to a line.
+ function addMarkedSpan(line, span) {
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
+ span.marker.attachLine(line);
+ }
+
+ // Used for the algorithm that adjusts markers for a change in the
+ // document. These functions cut an array of spans at a given
+ // character position, returning an array of remaining chunks (or
+ // undefined if nothing remains).
+ function markedSpansBefore(old, startCh, isInsert) {
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
+ (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
+ }
+ }
+ return nw;
+ }
+ function markedSpansAfter(old, endCh, isInsert) {
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
+ (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
+ span.to == null ? null : span.to - endCh));
+ }
+ }
+ return nw;
+ }
+
+ // Given a change object, compute the new set of marker spans that
+ // cover the line in which the change took place. Removes spans
+ // entirely within the change, reconnects spans belonging to the
+ // same marker that appear on both sides of the change, and cuts off
+ // spans partially within the change. Returns an array of span
+ // arrays with one element for each line in (after) the change.
+ function stretchSpansOverChange(doc, change) {
+ if (change.full) return null;
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
+ if (!oldFirst && !oldLast) return null;
+
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
+ // Get the spans that 'stick out' on both sides
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
+
+ // Next, merge those two ends
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
+ if (first) {
+ // Fix up .to properties of first
+ for (var i = 0; i < first.length; ++i) {
+ var span = first[i];
+ if (span.to == null) {
+ var found = getMarkedSpanFor(last, span.marker);
+ if (!found) span.to = startCh;
+ else if (sameLine) span.to = found.to == null ? null : found.to + offset;
+ }
+ }
+ }
+ if (last) {
+ // Fix up .from in last (or move them into first in case of sameLine)
+ for (var i = 0; i < last.length; ++i) {
+ var span = last[i];
+ if (span.to != null) span.to += offset;
+ if (span.from == null) {
+ var found = getMarkedSpanFor(first, span.marker);
+ if (!found) {
+ span.from = offset;
+ if (sameLine) (first || (first = [])).push(span);
+ }
+ } else {
+ span.from += offset;
+ if (sameLine) (first || (first = [])).push(span);
+ }
+ }
+ }
+ // Make sure we didn't create any zero-length spans
+ if (first) first = clearEmptySpans(first);
+ if (last && last != first) last = clearEmptySpans(last);
+
+ var newMarkers = [first];
+ if (!sameLine) {
+ // Fill gap with whole-line-spans
+ var gap = change.text.length - 2, gapMarkers;
+ if (gap > 0 && first)
+ for (var i = 0; i < first.length; ++i)
+ if (first[i].to == null)
+ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
+ for (var i = 0; i < gap; ++i)
+ newMarkers.push(gapMarkers);
+ newMarkers.push(last);
+ }
+ return newMarkers;
+ }
+
+ // Remove spans that are empty and don't have a clearWhenEmpty
+ // option of false.
+ function clearEmptySpans(spans) {
+ for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
+ spans.splice(i--, 1);
+ }
+ if (!spans.length) return null;
+ return spans;
+ }
+
+ // Used for un/re-doing changes from the history. Combines the
+ // result of computing the existing spans with the set of spans that
+ // existed in the history (so that deleting around a span and then
+ // undoing brings back the span).
+ function mergeOldSpans(doc, change) {
+ var old = getOldSpans(doc, change);
+ var stretched = stretchSpansOverChange(doc, change);
+ if (!old) return stretched;
+ if (!stretched) return old;
+
+ for (var i = 0; i < old.length; ++i) {
+ var oldCur = old[i], stretchCur = stretched[i];
+ if (oldCur && stretchCur) {
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
+ var span = stretchCur[j];
+ for (var k = 0; k < oldCur.length; ++k)
+ if (oldCur[k].marker == span.marker) continue spans;
+ oldCur.push(span);
+ }
+ } else if (stretchCur) {
+ old[i] = stretchCur;
+ }
+ }
+ return old;
+ }
+
+ // Used to 'clip' out readOnly ranges when making a change.
+ function removeReadOnlyRanges(doc, from, to) {
+ var markers = null;
+ doc.iter(from.line, to.line + 1, function(line) {
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
+ var mark = line.markedSpans[i].marker;
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
+ (markers || (markers = [])).push(mark);
+ }
+ });
+ if (!markers) return null;
+ var parts = [{from: from, to: to}];
+ for (var i = 0; i < markers.length; ++i) {
+ var mk = markers[i], m = mk.find(0);
+ for (var j = 0; j < parts.length; ++j) {
+ var p = parts[j];
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
+ newParts.push({from: p.from, to: m.from});
+ if (dto > 0 || !mk.inclusiveRight && !dto)
+ newParts.push({from: m.to, to: p.to});
+ parts.splice.apply(parts, newParts);
+ j += newParts.length - 1;
+ }
+ }
+ return parts;
+ }
+
+ // Connect or disconnect spans from a line.
+ function detachMarkedSpans(line) {
+ var spans = line.markedSpans;
+ if (!spans) return;
+ for (var i = 0; i < spans.length; ++i)
+ spans[i].marker.detachLine(line);
+ line.markedSpans = null;
+ }
+ function attachMarkedSpans(line, spans) {
+ if (!spans) return;
+ for (var i = 0; i < spans.length; ++i)
+ spans[i].marker.attachLine(line);
+ line.markedSpans = spans;
+ }
+
+ // Helpers used when computing which overlapping collapsed span
+ // counts as the larger one.
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
+
+ // Returns a number indicating which of two overlapping collapsed
+ // spans is larger (and thus includes the other). Falls back to
+ // comparing ids when the spans cover exactly the same range.
+ function compareCollapsedMarkers(a, b) {
+ var lenDiff = a.lines.length - b.lines.length;
+ if (lenDiff != 0) return lenDiff;
+ var aPos = a.find(), bPos = b.find();
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
+ if (fromCmp) return -fromCmp;
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
+ if (toCmp) return toCmp;
+ return b.id - a.id;
+ }
+
+ // Find out whether a line ends or starts in a collapsed span. If
+ // so, return the marker for that span.
+ function collapsedSpanAtSide(line, start) {
+ var sps = sawCollapsedSpans && line.markedSpans, found;
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
+ found = sp.marker;
+ }
+ return found;
+ }
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
+
+ // Test whether there exists a collapsed span that partially
+ // overlaps (covers the start or end, but not both) of a new span.
+ // Such overlap is not allowed.
+ function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
+ var line = getLine(doc, lineNo);
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) for (var i = 0; i < sps.length; ++i) {
+ var sp = sps[i];
+ if (!sp.marker.collapsed) continue;
+ var found = sp.marker.find(0);
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
+ if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
+ fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
+ return true;
+ }
+ }
+
+ // A visual line is a line as drawn on the screen. Folding, for
+ // example, can cause multiple logical lines to appear on the same
+ // visual line. This finds the start of the visual line that the
+ // given line is part of (usually that is the line itself).
+ function visualLine(line) {
+ var merged;
+ while (merged = collapsedSpanAtStart(line))
+ line = merged.find(-1, true).line;
+ return line;
+ }
+
+ // Returns an array of logical lines that continue the visual line
+ // started by the argument, or undefined if there are no such lines.
+ function visualLineContinued(line) {
+ var merged, lines;
+ while (merged = collapsedSpanAtEnd(line)) {
+ line = merged.find(1, true).line;
+ (lines || (lines = [])).push(line);
+ }
+ return lines;
+ }
+
+ // Get the line number of the start of the visual line that the
+ // given line number is part of.
+ function visualLineNo(doc, lineN) {
+ var line = getLine(doc, lineN), vis = visualLine(line);
+ if (line == vis) return lineN;
+ return lineNo(vis);
+ }
+ // Get the line number of the start of the next visual line after
+ // the given line.
+ function visualLineEndNo(doc, lineN) {
+ if (lineN > doc.lastLine()) return lineN;
+ var line = getLine(doc, lineN), merged;
+ if (!lineIsHidden(doc, line)) return lineN;
+ while (merged = collapsedSpanAtEnd(line))
+ line = merged.find(1, true).line;
+ return lineNo(line) + 1;
+ }
+
+ // Compute whether a line is hidden. Lines count as hidden when they
+ // are part of a visual line that starts with another line, or when
+ // they are entirely covered by collapsed, non-widget span.
+ function lineIsHidden(doc, line) {
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (!sp.marker.collapsed) continue;
+ if (sp.from == null) return true;
+ if (sp.marker.widgetNode) continue;
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
+ return true;
+ }
+ }
+ function lineIsHiddenInner(doc, line, span) {
+ if (span.to == null) {
+ var end = span.marker.find(1, true);
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
+ }
+ if (span.marker.inclusiveRight && span.to == line.text.length)
+ return true;
+ for (var sp, i = 0; i < line.markedSpans.length; ++i) {
+ sp = line.markedSpans[i];
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
+ (sp.to == null || sp.to != span.from) &&
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
+ lineIsHiddenInner(doc, line, sp)) return true;
+ }
+ }
+
+ // LINE WIDGETS
+
+ // Line widgets are block elements displayed above or below a line.
+
+ var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
+ if (options) for (var opt in options) if (options.hasOwnProperty(opt))
+ this[opt] = options[opt];
+ this.doc = doc;
+ this.node = node;
+ };
+ eventMixin(LineWidget);
+
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
+ addToScrollPos(cm, null, diff);
+ }
+
+ LineWidget.prototype.clear = function() {
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
+ if (no == null || !ws) return;
+ for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
+ if (!ws.length) line.widgets = null;
+ var height = widgetHeight(this);
+ updateLineHeight(line, Math.max(0, line.height - height));
+ if (cm) runInOp(cm, function() {
+ adjustScrollWhenAboveVisible(cm, line, -height);
+ regLineChange(cm, no, "widget");
+ });
+ };
+ LineWidget.prototype.changed = function() {
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
+ this.height = null;
+ var diff = widgetHeight(this) - oldH;
+ if (!diff) return;
+ updateLineHeight(line, line.height + diff);
+ if (cm) runInOp(cm, function() {
+ cm.curOp.forceUpdate = true;
+ adjustScrollWhenAboveVisible(cm, line, diff);
+ });
+ };
+
+ function widgetHeight(widget) {
+ if (widget.height != null) return widget.height;
+ var cm = widget.doc.cm;
+ if (!cm) return 0;
+ if (!contains(document.body, widget.node)) {
+ var parentStyle = "position: relative;";
+ if (widget.coverGutter)
+ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
+ if (widget.noHScroll)
+ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
+ }
+ return widget.height = widget.node.offsetHeight;
+ }
+
+ function addLineWidget(doc, handle, node, options) {
+ var widget = new LineWidget(doc, node, options);
+ var cm = doc.cm;
+ if (cm && widget.noHScroll) cm.display.alignWidgets = true;
+ changeLine(doc, handle, "widget", function(line) {
+ var widgets = line.widgets || (line.widgets = []);
+ if (widget.insertAt == null) widgets.push(widget);
+ else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
+ widget.line = line;
+ if (cm && !lineIsHidden(doc, line)) {
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
+ updateLineHeight(line, line.height + widgetHeight(widget));
+ if (aboveVisible) addToScrollPos(cm, null, widget.height);
+ cm.curOp.forceUpdate = true;
+ }
+ return true;
+ });
+ return widget;
+ }
+
+ // LINE DATA STRUCTURE
+
+ // Line objects. These hold state related to a line, including
+ // highlighting info (the styles array).
+ var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
+ this.text = text;
+ attachMarkedSpans(this, markedSpans);
+ this.height = estimateHeight ? estimateHeight(this) : 1;
+ };
+ eventMixin(Line);
+ Line.prototype.lineNo = function() { return lineNo(this); };
+
+ // Change the content (text, markers) of a line. Automatically
+ // invalidates cached information and tries to re-estimate the
+ // line's height.
+ function updateLine(line, text, markedSpans, estimateHeight) {
+ line.text = text;
+ if (line.stateAfter) line.stateAfter = null;
+ if (line.styles) line.styles = null;
+ if (line.order != null) line.order = null;
+ detachMarkedSpans(line);
+ attachMarkedSpans(line, markedSpans);
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
+ }
+
+ // Detach a line from the document tree and its markers.
+ function cleanUpLine(line) {
+ line.parent = null;
+ detachMarkedSpans(line);
+ }
+
+ function extractLineClasses(type, output) {
+ if (type) for (;;) {
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
+ if (!lineClass) break;
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
+ var prop = lineClass[1] ? "bgClass" : "textClass";
+ if (output[prop] == null)
+ output[prop] = lineClass[2];
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
+ output[prop] += " " + lineClass[2];
+ }
+ return type;
+ }
+
+ function callBlankLine(mode, state) {
+ if (mode.blankLine) return mode.blankLine(state);
+ if (!mode.innerMode) return;
+ var inner = CodeMirror.innerMode(mode, state);
+ if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
+ }
+
+ function readToken(mode, stream, state, inner) {
+ for (var i = 0; i < 10; i++) {
+ if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
+ var style = mode.token(stream, state);
+ if (stream.pos > stream.start) return style;
+ }
+ throw new Error("Mode " + mode.name + " failed to advance stream.");
+ }
+
+ // Utility for getTokenAt and getLineTokens
+ function takeToken(cm, pos, precise, asArray) {
+ function getObj(copy) {
+ return {start: stream.start, end: stream.pos,
+ string: stream.current(),
+ type: style || null,
+ state: copy ? copyState(doc.mode, state) : state};
+ }
+
+ var doc = cm.doc, mode = doc.mode, style;
+ pos = clipPos(doc, pos);
+ var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
+ var stream = new StringStream(line.text, cm.options.tabSize), tokens;
+ if (asArray) tokens = [];
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
+ stream.start = stream.pos;
+ style = readToken(mode, stream, state);
+ if (asArray) tokens.push(getObj(true));
+ }
+ return asArray ? tokens : getObj();
+ }
+
+ // Run the given mode's parser over a line, calling f for each token.
+ function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
+ var flattenSpans = mode.flattenSpans;
+ if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
+ var curStart = 0, curStyle = null;
+ var stream = new StringStream(text, cm.options.tabSize), style;
+ var inner = cm.options.addModeClass && [null];
+ if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
+ while (!stream.eol()) {
+ if (stream.pos > cm.options.maxHighlightLength) {
+ flattenSpans = false;
+ if (forceToEnd) processLine(cm, text, state, stream.pos);
+ stream.pos = text.length;
+ style = null;
+ } else {
+ style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
+ }
+ if (inner) {
+ var mName = inner[0].name;
+ if (mName) style = "m-" + (style ? mName + " " + style : mName);
+ }
+ if (!flattenSpans || curStyle != style) {
+ while (curStart < stream.start) {
+ curStart = Math.min(stream.start, curStart + 50000);
+ f(curStart, curStyle);
+ }
+ curStyle = style;
+ }
+ stream.start = stream.pos;
+ }
+ while (curStart < stream.pos) {
+ // Webkit seems to refuse to render text nodes longer than 57444 characters
+ var pos = Math.min(stream.pos, curStart + 50000);
+ f(pos, curStyle);
+ curStart = pos;
+ }
+ }
+
+ // Compute a style array (an array starting with a mode generation
+ // -- for invalidation -- followed by pairs of end positions and
+ // style strings), which is used to highlight the tokens on the
+ // line.
+ function highlightLine(cm, line, state, forceToEnd) {
+ // A styles array always starts with a number identifying the
+ // mode/overlays that it is based on (for easy invalidation).
+ var st = [cm.state.modeGen], lineClasses = {};
+ // Compute the base array of styles
+ runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
+ st.push(end, style);
+ }, lineClasses, forceToEnd);
+
+ // Run overlays, adjust style array.
+ for (var o = 0; o < cm.state.overlays.length; ++o) {
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
+ runMode(cm, line.text, overlay.mode, true, function(end, style) {
+ var start = i;
+ // Ensure there's a token end at the current position, and that i points at it
+ while (at < end) {
+ var i_end = st[i];
+ if (i_end > end)
+ st.splice(i, 1, end, st[i+1], i_end);
+ i += 2;
+ at = Math.min(end, i_end);
+ }
+ if (!style) return;
+ if (overlay.opaque) {
+ st.splice(start, i - start, end, "cm-overlay " + style);
+ i = start + 2;
+ } else {
+ for (; start < i; start += 2) {
+ var cur = st[start+1];
+ st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
+ }
+ }
+ }, lineClasses);
+ }
+
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
+ }
+
+ function getLineStyles(cm, line, updateFrontier) {
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
+ var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
+ line.styles = result.styles;
+ if (result.classes) line.styleClasses = result.classes;
+ else if (line.styleClasses) line.styleClasses = null;
+ if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
+ }
+ return line.styles;
+ }
+
+ // Lightweight form of highlight -- proceed over this line and
+ // update state, but don't save a style array. Used for lines that
+ // aren't currently visible.
+ function processLine(cm, text, state, startAt) {
+ var mode = cm.doc.mode;
+ var stream = new StringStream(text, cm.options.tabSize);
+ stream.start = stream.pos = startAt || 0;
+ if (text == "") callBlankLine(mode, state);
+ while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
+ readToken(mode, stream, state);
+ stream.start = stream.pos;
+ }
+ }
+
+ // Convert a style as returned by a mode (either null, or a string
+ // containing one or more styles) to a CSS style. This is cached,
+ // and also looks for line-wide styles.
+ var styleToClassCache = {}, styleToClassCacheWithMode = {};
+ function interpretTokenStyle(style, options) {
+ if (!style || /^\s*$/.test(style)) return null;
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
+ return cache[style] ||
+ (cache[style] = style.replace(/\S+/g, "cm-$&"));
+ }
+
+ // Render the DOM representation of the text of a line. Also builds
+ // up a 'line map', which points at the DOM nodes that represent
+ // specific stretches of text, and is used by the measuring code.
+ // The returned object contains the DOM node, this map, and
+ // information about line-wide styles that were set by the mode.
+ function buildLineContent(cm, lineView) {
+ // The padding-right forces the element to have a 'border', which
+ // is needed on Webkit to be able to get line-level bounding
+ // rectangles for it (in measureChar).
+ var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
+ var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
+ col: 0, pos: 0, cm: cm,
+ splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
+ lineView.measure = {};
+
+ // Iterate over the logical lines that make up this visual line.
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
+ var line = i ? lineView.rest[i - 1] : lineView.line, order;
+ builder.pos = 0;
+ builder.addToken = buildToken;
+ // Optionally wire in some hacks into the token-rendering
+ // algorithm, to deal with browser quirks.
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
+ builder.addToken = buildTokenBadBidi(builder.addToken, order);
+ builder.map = [];
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
+ if (line.styleClasses) {
+ if (line.styleClasses.bgClass)
+ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
+ if (line.styleClasses.textClass)
+ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
+ }
+
+ // Ensure at least a single node is present, for measuring.
+ if (builder.map.length == 0)
+ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
+
+ // Store the map and a cache object for the current logical line
+ if (i == 0) {
+ lineView.measure.map = builder.map;
+ lineView.measure.cache = {};
+ } else {
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
+ (lineView.measure.caches || (lineView.measure.caches = [])).push({});
+ }
+ }
+
+ // See issue #2901
+ if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
+ builder.content.className = "cm-tab-wrap-hack";
+
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
+ if (builder.pre.className)
+ builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
+
+ return builder;
+ }
+
+ function defaultSpecialCharPlaceholder(ch) {
+ var token = elt("span", "\u2022", "cm-invalidchar");
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
+ token.setAttribute("aria-label", token.title);
+ return token;
+ }
+
+ // Build up the DOM representation for a single token, and add it to
+ // the line map. Takes care to render special characters separately.
+ function buildToken(builder, text, style, startStyle, endStyle, title, css) {
+ if (!text) return;
+ var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
+ var special = builder.cm.state.specialChars, mustWrap = false;
+ if (!special.test(text)) {
+ builder.col += text.length;
+ var content = document.createTextNode(displayText);
+ builder.map.push(builder.pos, builder.pos + text.length, content);
+ if (ie && ie_version < 9) mustWrap = true;
+ builder.pos += text.length;
+ } else {
+ var content = document.createDocumentFragment(), pos = 0;
+ while (true) {
+ special.lastIndex = pos;
+ var m = special.exec(text);
+ var skipped = m ? m.index - pos : text.length - pos;
+ if (skipped) {
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
+ else content.appendChild(txt);
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
+ builder.col += skipped;
+ builder.pos += skipped;
+ }
+ if (!m) break;
+ pos += skipped + 1;
+ if (m[0] == "\t") {
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
+ var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
+ txt.setAttribute("role", "presentation");
+ txt.setAttribute("cm-text", "\t");
+ builder.col += tabWidth;
+ } else {
+ var txt = builder.cm.options.specialCharPlaceholder(m[0]);
+ txt.setAttribute("cm-text", m[0]);
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
+ else content.appendChild(txt);
+ builder.col += 1;
+ }
+ builder.map.push(builder.pos, builder.pos + 1, txt);
+ builder.pos++;
+ }
+ }
+ if (style || startStyle || endStyle || mustWrap || css) {
+ var fullStyle = style || "";
+ if (startStyle) fullStyle += startStyle;
+ if (endStyle) fullStyle += endStyle;
+ var token = elt("span", [content], fullStyle, css);
+ if (title) token.title = title;
+ return builder.content.appendChild(token);
+ }
+ builder.content.appendChild(content);
+ }
+
+ function splitSpaces(old) {
+ var out = " ";
+ for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
+ out += " ";
+ return out;
+ }
+
+ // Work around nonsense dimensions being reported for stretches of
+ // right-to-left text.
+ function buildTokenBadBidi(inner, order) {
+ return function(builder, text, style, startStyle, endStyle, title, css) {
+ style = style ? style + " cm-force-border" : "cm-force-border";
+ var start = builder.pos, end = start + text.length;
+ for (;;) {
+ // Find the part that overlaps with the start of this text
+ for (var i = 0; i < order.length; i++) {
+ var part = order[i];
+ if (part.to > start && part.from <= start) break;
+ }
+ if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
+ startStyle = null;
+ text = text.slice(part.to - start);
+ start = part.to;
+ }
+ };
+ }
+
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
+ var widget = !ignoreWidget && marker.widgetNode;
+ if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
+ if (!widget)
+ widget = builder.content.appendChild(document.createElement("span"));
+ widget.setAttribute("cm-marker", marker.id);
+ }
+ if (widget) {
+ builder.cm.display.input.setUneditable(widget);
+ builder.content.appendChild(widget);
+ }
+ builder.pos += size;
+ }
+
+ // Outputs a number of spans to make up a line, taking highlighting
+ // and marked text into account.
+ function insertLineContent(line, builder, styles) {
+ var spans = line.markedSpans, allText = line.text, at = 0;
+ if (!spans) {
+ for (var i = 1; i < styles.length; i+=2)
+ builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
+ return;
+ }
+
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
+ for (;;) {
+ if (nextChange == pos) { // Update current marker set
+ spanStyle = spanEndStyle = spanStartStyle = title = css = "";
+ collapsed = null; nextChange = Infinity;
+ var foundBookmarks = [];
+ for (var j = 0; j < spans.length; ++j) {
+ var sp = spans[j], m = sp.marker;
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
+ foundBookmarks.push(m);
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
+ nextChange = sp.to;
+ spanEndStyle = "";
+ }
+ if (m.className) spanStyle += " " + m.className;
+ if (m.css) css = m.css;
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
+ if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
+ if (m.title && !title) title = m.title;
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
+ collapsed = sp;
+ } else if (sp.from > pos && nextChange > sp.from) {
+ nextChange = sp.from;
+ }
+ }
+ if (collapsed && (collapsed.from || 0) == pos) {
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
+ collapsed.marker, collapsed.from == null);
+ if (collapsed.to == null) return;
+ if (collapsed.to == pos) collapsed = false;
+ }
+ if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
+ buildCollapsedSpan(builder, 0, foundBookmarks[j]);
+ }
+ if (pos >= len) break;
+
+ var upto = Math.min(len, nextChange);
+ while (true) {
+ if (text) {
+ var end = pos + text.length;
+ if (!collapsed) {
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
+ }
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
+ pos = end;
+ spanStartStyle = "";
+ }
+ text = allText.slice(at, at = styles[i++]);
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
+ }
+ }
+ }
+
+ // DOCUMENT DATA STRUCTURE
+
+ // By default, updates that start and end at the beginning of a line
+ // are treated specially, in order to make the association of line
+ // widgets and marker elements with the text behave more intuitive.
+ function isWholeLineUpdate(doc, change) {
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
+ }
+
+ // Perform a change on the document data structure.
+ function updateDoc(doc, change, markedSpans, estimateHeight) {
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
+ function update(line, text, spans) {
+ updateLine(line, text, spans, estimateHeight);
+ signalLater(line, "change", line, change);
+ }
+ function linesFor(start, end) {
+ for (var i = start, result = []; i < end; ++i)
+ result.push(new Line(text[i], spansFor(i), estimateHeight));
+ return result;
+ }
+
+ var from = change.from, to = change.to, text = change.text;
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
+
+ // Adjust the line structure
+ if (change.full) {
+ doc.insert(0, linesFor(0, text.length));
+ doc.remove(text.length, doc.size - text.length);
+ } else if (isWholeLineUpdate(doc, change)) {
+ // This is a whole-line replace. Treated specially to make
+ // sure line objects move the way they are supposed to.
+ var added = linesFor(0, text.length - 1);
+ update(lastLine, lastLine.text, lastSpans);
+ if (nlines) doc.remove(from.line, nlines);
+ if (added.length) doc.insert(from.line, added);
+ } else if (firstLine == lastLine) {
+ if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
+ } else {
+ var added = linesFor(1, text.length - 1);
+ added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ doc.insert(from.line + 1, added);
+ }
+ } else if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
+ doc.remove(from.line + 1, nlines);
+ } else {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
+ var added = linesFor(1, text.length - 1);
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
+ doc.insert(from.line + 1, added);
+ }
+
+ signalLater(doc, "change", doc, change);
+ }
+
+ // The document is represented as a BTree consisting of leaves, with
+ // chunk of lines in them, and branches, with up to ten leaves or
+ // other branch nodes below them. The top node is always a branch
+ // node, and is the document object itself (meaning it has
+ // additional methods and properties).
+ //
+ // All nodes have parent links. The tree is used both to go from
+ // line numbers to line objects, and to go from objects to numbers.
+ // It also indexes by height, and is used to convert between height
+ // and line object, and to find the total height of the document.
+ //
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
+
+ function LeafChunk(lines) {
+ this.lines = lines;
+ this.parent = null;
+ for (var i = 0, height = 0; i < lines.length; ++i) {
+ lines[i].parent = this;
+ height += lines[i].height;
+ }
+ this.height = height;
+ }
+
+ LeafChunk.prototype = {
+ chunkSize: function() { return this.lines.length; },
+ // Remove the n lines at offset 'at'.
+ removeInner: function(at, n) {
+ for (var i = at, e = at + n; i < e; ++i) {
+ var line = this.lines[i];
+ this.height -= line.height;
+ cleanUpLine(line);
+ signalLater(line, "delete");
+ }
+ this.lines.splice(at, n);
+ },
+ // Helper used to collapse a small branch into a single leaf.
+ collapse: function(lines) {
+ lines.push.apply(lines, this.lines);
+ },
+ // Insert the given array of lines at offset 'at', count them as
+ // having the given height.
+ insertInner: function(at, lines, height) {
+ this.height += height;
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
+ for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
+ },
+ // Used to iterate over a part of the tree.
+ iterN: function(at, n, op) {
+ for (var e = at + n; at < e; ++at)
+ if (op(this.lines[at])) return true;
+ }
+ };
+
+ function BranchChunk(children) {
+ this.children = children;
+ var size = 0, height = 0;
+ for (var i = 0; i < children.length; ++i) {
+ var ch = children[i];
+ size += ch.chunkSize(); height += ch.height;
+ ch.parent = this;
+ }
+ this.size = size;
+ this.height = height;
+ this.parent = null;
+ }
+
+ BranchChunk.prototype = {
+ chunkSize: function() { return this.size; },
+ removeInner: function(at, n) {
+ this.size -= n;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
+ child.removeInner(at, rm);
+ this.height -= oldHeight - child.height;
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
+ if ((n -= rm) == 0) break;
+ at = 0;
+ } else at -= sz;
+ }
+ // If the result is smaller than 25 lines, ensure that it is a
+ // single leaf node.
+ if (this.size - n < 25 &&
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
+ var lines = [];
+ this.collapse(lines);
+ this.children = [new LeafChunk(lines)];
+ this.children[0].parent = this;
+ }
+ },
+ collapse: function(lines) {
+ for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
+ },
+ insertInner: function(at, lines, height) {
+ this.size += lines.length;
+ this.height += height;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at <= sz) {
+ child.insertInner(at, lines, height);
+ if (child.lines && child.lines.length > 50) {
+ while (child.lines.length > 50) {
+ var spilled = child.lines.splice(child.lines.length - 25, 25);
+ var newleaf = new LeafChunk(spilled);
+ child.height -= newleaf.height;
+ this.children.splice(i + 1, 0, newleaf);
+ newleaf.parent = this;
+ }
+ this.maybeSpill();
+ }
+ break;
+ }
+ at -= sz;
+ }
+ },
+ // When a node has grown, check whether it should be split.
+ maybeSpill: function() {
+ if (this.children.length <= 10) return;
+ var me = this;
+ do {
+ var spilled = me.children.splice(me.children.length - 5, 5);
+ var sibling = new BranchChunk(spilled);
+ if (!me.parent) { // Become the parent node
+ var copy = new BranchChunk(me.children);
+ copy.parent = me;
+ me.children = [copy, sibling];
+ me = copy;
+ } else {
+ me.size -= sibling.size;
+ me.height -= sibling.height;
+ var myIndex = indexOf(me.parent.children, me);
+ me.parent.children.splice(myIndex + 1, 0, sibling);
+ }
+ sibling.parent = me.parent;
+ } while (me.children.length > 10);
+ me.parent.maybeSpill();
+ },
+ iterN: function(at, n, op) {
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var used = Math.min(n, sz - at);
+ if (child.iterN(at, used, op)) return true;
+ if ((n -= used) == 0) break;
+ at = 0;
+ } else at -= sz;
+ }
+ }
+ };
+
+ var nextDocId = 0;
+ var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
+ if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
+ if (firstLine == null) firstLine = 0;
+
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
+ this.first = firstLine;
+ this.scrollTop = this.scrollLeft = 0;
+ this.cantEdit = false;
+ this.cleanGeneration = 1;
+ this.frontier = firstLine;
+ var start = Pos(firstLine, 0);
+ this.sel = simpleSelection(start);
+ this.history = new History(null);
+ this.id = ++nextDocId;
+ this.modeOption = mode;
+
+ if (typeof text == "string") text = splitLines(text);
+ updateDoc(this, {from: start, to: start, text: text});
+ setSelection(this, simpleSelection(start), sel_dontScroll);
+ };
+
+ Doc.prototype = createObj(BranchChunk.prototype, {
+ constructor: Doc,
+ // Iterate over the document. Supports two forms -- with only one
+ // argument, it calls that for each line in the document. With
+ // three, it iterates over the range given by the first two (with
+ // the second being non-inclusive).
+ iter: function(from, to, op) {
+ if (op) this.iterN(from - this.first, to - from, op);
+ else this.iterN(this.first, this.first + this.size, from);
+ },
+
+ // Non-public interface for adding and removing lines.
+ insert: function(at, lines) {
+ var height = 0;
+ for (var i = 0; i < lines.length; ++i) height += lines[i].height;
+ this.insertInner(at - this.first, lines, height);
+ },
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
+
+ // From here, the methods are part of the public interface. Most
+ // are also available from CodeMirror (editor) instances.
+
+ getValue: function(lineSep, lineFilter) {
+ var lines = getLines(this, this.first, this.first + this.size, lineFilter);
+ if (lineSep === false) return lines;
+ return lines.join(lineSep || "\n");
+ },
+ setValue: docMethodOp(function(code) {
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
+ text: splitLines(code), origin: "setValue", full: true}, true);
+ setSelection(this, simpleSelection(top));
+ }),
+ replaceRange: function(code, from, to, origin) {
+ from = clipPos(this, from);
+ to = to ? clipPos(this, to) : from;
+ replaceRange(this, code, from, to, origin);
+ },
+ getRange: function(from, to, lineSep) {
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
+ if (lineSep === false) return lines;
+ return lines.join(lineSep || "\n");
+ },
+
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
+
+ getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
+ getLineNumber: function(line) {return lineNo(line);},
+
+ getLineHandleVisualStart: function(line) {
+ if (typeof line == "number") line = getLine(this, line);
+ return visualLine(line);
+ },
+
+ lineCount: function() {return this.size;},
+ firstLine: function() {return this.first;},
+ lastLine: function() {return this.first + this.size - 1;},
+
+ clipPos: function(pos) {return clipPos(this, pos);},
+
+ getCursor: function(start) {
+ var range = this.sel.primary(), pos;
+ if (start == null || start == "head") pos = range.head;
+ else if (start == "anchor") pos = range.anchor;
+ else if (start == "end" || start == "to" || start === false) pos = range.to();
+ else pos = range.from();
+ return pos;
+ },
+ listSelections: function() { return this.sel.ranges; },
+ somethingSelected: function() {return this.sel.somethingSelected();},
+
+ setCursor: docMethodOp(function(line, ch, options) {
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
+ }),
+ setSelection: docMethodOp(function(anchor, head, options) {
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
+ }),
+ extendSelection: docMethodOp(function(head, other, options) {
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
+ }),
+ extendSelections: docMethodOp(function(heads, options) {
+ extendSelections(this, clipPosArray(this, heads, options));
+ }),
+ extendSelectionsBy: docMethodOp(function(f, options) {
+ extendSelections(this, map(this.sel.ranges, f), options);
+ }),
+ setSelections: docMethodOp(function(ranges, primary, options) {
+ if (!ranges.length) return;
+ for (var i = 0, out = []; i < ranges.length; i++)
+ out[i] = new Range(clipPos(this, ranges[i].anchor),
+ clipPos(this, ranges[i].head));
+ if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
+ setSelection(this, normalizeSelection(out, primary), options);
+ }),
+ addSelection: docMethodOp(function(anchor, head, options) {
+ var ranges = this.sel.ranges.slice(0);
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
+ }),
+
+ getSelection: function(lineSep) {
+ var ranges = this.sel.ranges, lines;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
+ lines = lines ? lines.concat(sel) : sel;
+ }
+ if (lineSep === false) return lines;
+ else return lines.join(lineSep || "\n");
+ },
+ getSelections: function(lineSep) {
+ var parts = [], ranges = this.sel.ranges;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
+ if (lineSep !== false) sel = sel.join(lineSep || "\n");
+ parts[i] = sel;
+ }
+ return parts;
+ },
+ replaceSelection: function(code, collapse, origin) {
+ var dup = [];
+ for (var i = 0; i < this.sel.ranges.length; i++)
+ dup[i] = code;
+ this.replaceSelections(dup, collapse, origin || "+input");
+ },
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
+ var changes = [], sel = this.sel;
+ for (var i = 0; i < sel.ranges.length; i++) {
+ var range = sel.ranges[i];
+ changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
+ }
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
+ for (var i = changes.length - 1; i >= 0; i--)
+ makeChange(this, changes[i]);
+ if (newSel) setSelectionReplaceHistory(this, newSel);
+ else if (this.cm) ensureCursorVisible(this.cm);
+ }),
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
+
+ setExtending: function(val) {this.extend = val;},
+ getExtending: function() {return this.extend;},
+
+ historySize: function() {
+ var hist = this.history, done = 0, undone = 0;
+ for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
+ for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
+ return {undo: done, redo: undone};
+ },
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
+
+ markClean: function() {
+ this.cleanGeneration = this.changeGeneration(true);
+ },
+ changeGeneration: function(forceSplit) {
+ if (forceSplit)
+ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
+ return this.history.generation;
+ },
+ isClean: function (gen) {
+ return this.history.generation == (gen || this.cleanGeneration);
+ },
+
+ getHistory: function() {
+ return {done: copyHistoryArray(this.history.done),
+ undone: copyHistoryArray(this.history.undone)};
+ },
+ setHistory: function(histData) {
+ var hist = this.history = new History(this.history.maxGeneration);
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
+ },
+
+ addLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ if (!line[prop]) line[prop] = cls;
+ else if (classTest(cls).test(line[prop])) return false;
+ else line[prop] += " " + cls;
+ return true;
+ });
+ }),
+ removeLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ var cur = line[prop];
+ if (!cur) return false;
+ else if (cls == null) line[prop] = null;
+ else {
+ var found = cur.match(classTest(cls));
+ if (!found) return false;
+ var end = found.index + found[0].length;
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
+ }
+ return true;
+ });
+ }),
+
+ addLineWidget: docMethodOp(function(handle, node, options) {
+ return addLineWidget(this, handle, node, options);
+ }),
+ removeLineWidget: function(widget) { widget.clear(); },
+
+ markText: function(from, to, options) {
+ return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
+ },
+ setBookmark: function(pos, options) {
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
+ insertLeft: options && options.insertLeft,
+ clearWhenEmpty: false, shared: options && options.shared,
+ handleMouseEvents: options && options.handleMouseEvents};
+ pos = clipPos(this, pos);
+ return markText(this, pos, pos, realOpts, "bookmark");
+ },
+ findMarksAt: function(pos) {
+ pos = clipPos(this, pos);
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
+ if (spans) for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if ((span.from == null || span.from <= pos.ch) &&
+ (span.to == null || span.to >= pos.ch))
+ markers.push(span.marker.parent || span.marker);
+ }
+ return markers;
+ },
+ findMarks: function(from, to, filter) {
+ from = clipPos(this, from); to = clipPos(this, to);
+ var found = [], lineNo = from.line;
+ this.iter(from.line, to.line + 1, function(line) {
+ var spans = line.markedSpans;
+ if (spans) for (var i = 0; i < spans.length; i++) {
+ var span = spans[i];
+ if (!(lineNo == from.line && from.ch > span.to ||
+ span.from == null && lineNo != from.line||
+ lineNo == to.line && span.from > to.ch) &&
+ (!filter || filter(span.marker)))
+ found.push(span.marker.parent || span.marker);
+ }
+ ++lineNo;
+ });
+ return found;
+ },
+ getAllMarks: function() {
+ var markers = [];
+ this.iter(function(line) {
+ var sps = line.markedSpans;
+ if (sps) for (var i = 0; i < sps.length; ++i)
+ if (sps[i].from != null) markers.push(sps[i].marker);
+ });
+ return markers;
+ },
+
+ posFromIndex: function(off) {
+ var ch, lineNo = this.first;
+ this.iter(function(line) {
+ var sz = line.text.length + 1;
+ if (sz > off) { ch = off; return true; }
+ off -= sz;
+ ++lineNo;
+ });
+ return clipPos(this, Pos(lineNo, ch));
+ },
+ indexFromPos: function (coords) {
+ coords = clipPos(this, coords);
+ var index = coords.ch;
+ if (coords.line < this.first || coords.ch < 0) return 0;
+ this.iter(this.first, coords.line, function (line) {
+ index += line.text.length + 1;
+ });
+ return index;
+ },
+
+ copy: function(copyHistory) {
+ var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
+ doc.sel = this.sel;
+ doc.extend = false;
+ if (copyHistory) {
+ doc.history.undoDepth = this.history.undoDepth;
+ doc.setHistory(this.getHistory());
+ }
+ return doc;
+ },
+
+ linkedDoc: function(options) {
+ if (!options) options = {};
+ var from = this.first, to = this.first + this.size;
+ if (options.from != null && options.from > from) from = options.from;
+ if (options.to != null && options.to < to) to = options.to;
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
+ if (options.sharedHist) copy.history = this.history;
+ (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
+ copySharedMarkers(copy, findSharedMarkers(this));
+ return copy;
+ },
+ unlinkDoc: function(other) {
+ if (other instanceof CodeMirror) other = other.doc;
+ if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
+ var link = this.linked[i];
+ if (link.doc != other) continue;
+ this.linked.splice(i, 1);
+ other.unlinkDoc(this);
+ detachSharedMarkers(findSharedMarkers(this));
+ break;
+ }
+ // If the histories were shared, split them again
+ if (other.history == this.history) {
+ var splitIds = [other.id];
+ linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
+ other.history = new History(null);
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
+ }
+ },
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
+
+ getMode: function() {return this.mode;},
+ getEditor: function() {return this.cm;}
+ });
+
+ // Public alias.
+ Doc.prototype.eachLine = Doc.prototype.iter;
+
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
+ var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
+ for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
+ CodeMirror.prototype[prop] = (function(method) {
+ return function() {return method.apply(this.doc, arguments);};
+ })(Doc.prototype[prop]);
+
+ eventMixin(Doc);
+
+ // Call f for all linked documents.
+ function linkedDocs(doc, f, sharedHistOnly) {
+ function propagate(doc, skip, sharedHist) {
+ if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
+ var rel = doc.linked[i];
+ if (rel.doc == skip) continue;
+ var shared = sharedHist && rel.sharedHist;
+ if (sharedHistOnly && !shared) continue;
+ f(rel.doc, shared);
+ propagate(rel.doc, doc, shared);
+ }
+ }
+ propagate(doc, null, true);
+ }
+
+ // Attach a document to an editor.
+ function attachDoc(cm, doc) {
+ if (doc.cm) throw new Error("This document is already in use.");
+ cm.doc = doc;
+ doc.cm = cm;
+ estimateLineHeights(cm);
+ loadMode(cm);
+ if (!cm.options.lineWrapping) findMaxLine(cm);
+ cm.options.mode = doc.modeOption;
+ regChange(cm);
+ }
+
+ // LINE UTILITIES
+
+ // Find the line object corresponding to the given line number.
+ function getLine(doc, n) {
+ n -= doc.first;
+ if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
+ for (var chunk = doc; !chunk.lines;) {
+ for (var i = 0;; ++i) {
+ var child = chunk.children[i], sz = child.chunkSize();
+ if (n < sz) { chunk = child; break; }
+ n -= sz;
+ }
+ }
+ return chunk.lines[n];
+ }
+
+ // Get the part of a document between two positions, as an array of
+ // strings.
+ function getBetween(doc, start, end) {
+ var out = [], n = start.line;
+ doc.iter(start.line, end.line + 1, function(line) {
+ var text = line.text;
+ if (n == end.line) text = text.slice(0, end.ch);
+ if (n == start.line) text = text.slice(start.ch);
+ out.push(text);
+ ++n;
+ });
+ return out;
+ }
+ // Get the lines between from and to, as array of strings.
+ function getLines(doc, from, to, lineFilter) {
+ var out = [];
+ doc.iter(from, to, function(line) {
+ var text = line.text;
+ if(lineFilter){
+ text = lineFilter(line);
+ }
+ out.push(text);
+ });
+ return out;
+ }
+
+ // Update the height of a line, propagating the height change
+ // upwards to parent nodes.
+ function updateLineHeight(line, height) {
+ var diff = height - line.height;
+ if (diff) for (var n = line; n; n = n.parent) n.height += diff;
+ }
+
+ // Given a line object, find its line number by walking up through
+ // its parent links.
+ function lineNo(line) {
+ if (line.parent == null) return null;
+ var cur = line.parent, no = indexOf(cur.lines, line);
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
+ for (var i = 0;; ++i) {
+ if (chunk.children[i] == cur) break;
+ no += chunk.children[i].chunkSize();
+ }
+ }
+ return no + cur.first;
+ }
+
+ // Find the line at the given vertical position, using the height
+ // information in the document tree.
+ function lineAtHeight(chunk, h) {
+ var n = chunk.first;
+ outer: do {
+ for (var i = 0; i < chunk.children.length; ++i) {
+ var child = chunk.children[i], ch = child.height;
+ if (h < ch) { chunk = child; continue outer; }
+ h -= ch;
+ n += child.chunkSize();
+ }
+ return n;
+ } while (!chunk.lines);
+ for (var i = 0; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i], lh = line.height;
+ if (h < lh) break;
+ h -= lh;
+ }
+ return n + i;
+ }
+
+
+ // Find the height above the given line.
+ function heightAtLine(lineObj) {
+ lineObj = visualLine(lineObj);
+
+ var h = 0, chunk = lineObj.parent;
+ for (var i = 0; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i];
+ if (line == lineObj) break;
+ else h += line.height;
+ }
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
+ for (var i = 0; i < p.children.length; ++i) {
+ var cur = p.children[i];
+ if (cur == chunk) break;
+ else h += cur.height;
+ }
+ }
+ return h;
+ }
+
+ // Get the bidi ordering for the given line (and cache it). Returns
+ // false for lines that are fully left-to-right, and an array of
+ // BidiSpan objects otherwise.
+ function getOrder(line) {
+ var order = line.order;
+ if (order == null) order = line.order = bidiOrdering(line.text);
+ return order;
+ }
+
+ // HISTORY
+
+ function History(startGen) {
+ // Arrays of change events and selections. Doing something adds an
+ // event to done and clears undo. Undoing moves events from done
+ // to undone, redoing moves them in the other direction.
+ this.done = []; this.undone = [];
+ this.undoDepth = Infinity;
+ // Used to track when changes can be merged into a single undo
+ // event
+ this.lastModTime = this.lastSelTime = 0;
+ this.lastOp = this.lastSelOp = null;
+ this.lastOrigin = this.lastSelOrigin = null;
+ // Used by the isClean() method
+ this.generation = this.maxGeneration = startGen || 1;
+ }
+
+ // Create a history change event from an updateDoc-style change
+ // object.
+ function historyChangeFromChange(doc, change) {
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
+ linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
+ return histChange;
+ }
+
+ // Pop all selection events off the end of a history array. Stop at
+ // a change event.
+ function clearSelectionEvents(array) {
+ while (array.length) {
+ var last = lst(array);
+ if (last.ranges) array.pop();
+ else break;
+ }
+ }
+
+ // Find the top change event in the history. Pop off selection
+ // events that are in the way.
+ function lastChangeEvent(hist, force) {
+ if (force) {
+ clearSelectionEvents(hist.done);
+ return lst(hist.done);
+ } else if (hist.done.length && !lst(hist.done).ranges) {
+ return lst(hist.done);
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
+ hist.done.pop();
+ return lst(hist.done);
+ }
+ }
+
+ // Register a change in the history. Merges changes that are within
+ // a single operation, ore are close together with an origin that
+ // allows merging (starting with "+") into a single event.
+ function addChangeToHistory(doc, change, selAfter, opId) {
+ var hist = doc.history;
+ hist.undone.length = 0;
+ var time = +new Date, cur;
+
+ if ((hist.lastOp == opId ||
+ hist.lastOrigin == change.origin && change.origin &&
+ ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
+ change.origin.charAt(0) == "*")) &&
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
+ // Merge this change into the last event
+ var last = lst(cur.changes);
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
+ // Optimized case for simple insertion -- don't want to add
+ // new changesets for every character typed
+ last.to = changeEnd(change);
+ } else {
+ // Add new sub-event
+ cur.changes.push(historyChangeFromChange(doc, change));
+ }
+ } else {
+ // Can not be merged, start a new event.
+ var before = lst(hist.done);
+ if (!before || !before.ranges)
+ pushSelectionToHistory(doc.sel, hist.done);
+ cur = {changes: [historyChangeFromChange(doc, change)],
+ generation: hist.generation};
+ hist.done.push(cur);
+ while (hist.done.length > hist.undoDepth) {
+ hist.done.shift();
+ if (!hist.done[0].ranges) hist.done.shift();
+ }
+ }
+ hist.done.push(selAfter);
+ hist.generation = ++hist.maxGeneration;
+ hist.lastModTime = hist.lastSelTime = time;
+ hist.lastOp = hist.lastSelOp = opId;
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
+
+ if (!last) signal(doc, "historyAdded");
+ }
+
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
+ var ch = origin.charAt(0);
+ return ch == "*" ||
+ ch == "+" &&
+ prev.ranges.length == sel.ranges.length &&
+ prev.somethingSelected() == sel.somethingSelected() &&
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
+ }
+
+ // Called whenever the selection changes, sets the new selection as
+ // the pending selection in the history, and pushes the old pending
+ // selection into the 'done' array when it was significantly
+ // different (in number of selected ranges, emptiness, or time).
+ function addSelectionToHistory(doc, sel, opId, options) {
+ var hist = doc.history, origin = options && options.origin;
+
+ // A new event is started when the previous origin does not match
+ // the current, or the origins don't allow matching. Origins
+ // starting with * are always merged, those starting with + are
+ // merged when similar and close together in time.
+ if (opId == hist.lastSelOp ||
+ (origin && hist.lastSelOrigin == origin &&
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
+ hist.done[hist.done.length - 1] = sel;
+ else
+ pushSelectionToHistory(sel, hist.done);
+
+ hist.lastSelTime = +new Date;
+ hist.lastSelOrigin = origin;
+ hist.lastSelOp = opId;
+ if (options && options.clearRedo !== false)
+ clearSelectionEvents(hist.undone);
+ }
+
+ function pushSelectionToHistory(sel, dest) {
+ var top = lst(dest);
+ if (!(top && top.ranges && top.equals(sel)))
+ dest.push(sel);
+ }
+
+ // Used to store marked span information in the history.
+ function attachLocalSpans(doc, change, from, to) {
+ var existing = change["spans_" + doc.id], n = 0;
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
+ if (line.markedSpans)
+ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
+ ++n;
+ });
+ }
+
+ // When un/re-doing restores text containing marked spans, those
+ // that have been explicitly cleared should not be restored.
+ function removeClearedSpans(spans) {
+ if (!spans) return null;
+ for (var i = 0, out; i < spans.length; ++i) {
+ if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
+ else if (out) out.push(spans[i]);
+ }
+ return !out ? spans : out.length ? out : null;
+ }
+
+ // Retrieve and filter the old marked spans stored in a change event.
+ function getOldSpans(doc, change) {
+ var found = change["spans_" + doc.id];
+ if (!found) return null;
+ for (var i = 0, nw = []; i < change.text.length; ++i)
+ nw.push(removeClearedSpans(found[i]));
+ return nw;
+ }
+
+ // Used both to provide a JSON-safe object in .getHistory, and, when
+ // detaching a document, to split the history in two
+ function copyHistoryArray(events, newGroup, instantiateSel) {
+ for (var i = 0, copy = []; i < events.length; ++i) {
+ var event = events[i];
+ if (event.ranges) {
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
+ continue;
+ }
+ var changes = event.changes, newChanges = [];
+ copy.push({changes: newChanges});
+ for (var j = 0; j < changes.length; ++j) {
+ var change = changes[j], m;
+ newChanges.push({from: change.from, to: change.to, text: change.text});
+ if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
+ if (indexOf(newGroup, Number(m[1])) > -1) {
+ lst(newChanges)[prop] = change[prop];
+ delete change[prop];
+ }
+ }
+ }
+ }
+ return copy;
+ }
+
+ // Rebasing/resetting history to deal with externally-sourced changes
+
+ function rebaseHistSelSingle(pos, from, to, diff) {
+ if (to < pos.line) {
+ pos.line += diff;
+ } else if (from < pos.line) {
+ pos.line = from;
+ pos.ch = 0;
+ }
+ }
+
+ // Tries to rebase an array of history events given a change in the
+ // document. If the change touches the same lines as the event, the
+ // event, and everything 'behind' it, is discarded. If the change is
+ // before the event, the event's positions are updated. Uses a
+ // copy-on-write scheme for the positions, to avoid having to
+ // reallocate them all on every rebase, but also avoid problems with
+ // shared position objects being unsafely updated.
+ function rebaseHistArray(array, from, to, diff) {
+ for (var i = 0; i < array.length; ++i) {
+ var sub = array[i], ok = true;
+ if (sub.ranges) {
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
+ for (var j = 0; j < sub.ranges.length; j++) {
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
+ }
+ continue;
+ }
+ for (var j = 0; j < sub.changes.length; ++j) {
+ var cur = sub.changes[j];
+ if (to < cur.from.line) {
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
+ } else if (from <= cur.to.line) {
+ ok = false;
+ break;
+ }
+ }
+ if (!ok) {
+ array.splice(0, i + 1);
+ i = 0;
+ }
+ }
+ }
+
+ function rebaseHist(hist, change) {
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
+ rebaseHistArray(hist.done, from, to, diff);
+ rebaseHistArray(hist.undone, from, to, diff);
+ }
+
+ // EVENT UTILITIES
+
+ // Due to the fact that we still support jurassic IE versions, some
+ // compatibility wrappers are needed.
+
+ var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
+ if (e.preventDefault) e.preventDefault();
+ else e.returnValue = false;
+ };
+ var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
+ if (e.stopPropagation) e.stopPropagation();
+ else e.cancelBubble = true;
+ };
+ function e_defaultPrevented(e) {
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
+ }
+ var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
+
+ function e_target(e) {return e.target || e.srcElement;}
+ function e_button(e) {
+ var b = e.which;
+ if (b == null) {
+ if (e.button & 1) b = 1;
+ else if (e.button & 2) b = 3;
+ else if (e.button & 4) b = 2;
+ }
+ if (mac && e.ctrlKey && b == 1) b = 3;
+ return b;
+ }
+
+ // EVENT HANDLING
+
+ // Lightweight event framework. on/off also work on DOM nodes,
+ // registering native DOM handlers.
+
+ var on = CodeMirror.on = function(emitter, type, f) {
+ if (emitter.addEventListener)
+ emitter.addEventListener(type, f, false);
+ else if (emitter.attachEvent)
+ emitter.attachEvent("on" + type, f);
+ else {
+ var map = emitter._handlers || (emitter._handlers = {});
+ var arr = map[type] || (map[type] = []);
+ arr.push(f);
+ }
+ };
+
+ var off = CodeMirror.off = function(emitter, type, f) {
+ if (emitter.removeEventListener)
+ emitter.removeEventListener(type, f, false);
+ else if (emitter.detachEvent)
+ emitter.detachEvent("on" + type, f);
+ else {
+ var arr = emitter._handlers && emitter._handlers[type];
+ if (!arr) return;
+ for (var i = 0; i < arr.length; ++i)
+ if (arr[i] == f) { arr.splice(i, 1); break; }
+ }
+ };
+
+ var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
+ var arr = emitter._handlers && emitter._handlers[type];
+ if (!arr) return;
+ var args = Array.prototype.slice.call(arguments, 2);
+ for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
+ };
+
+ var orphanDelayedCallbacks = null;
+
+ // Often, we want to signal events at a point where we are in the
+ // middle of some work, but don't want the handler to start calling
+ // other methods on the editor, which might be in an inconsistent
+ // state or simply not expect any other events to happen.
+ // signalLater looks whether there are any handlers, and schedules
+ // them to be executed when the last operation ends, or, if no
+ // operation is active, when a timeout fires.
+ function signalLater(emitter, type /*, values...*/) {
+ var arr = emitter._handlers && emitter._handlers[type];
+ if (!arr) return;
+ var args = Array.prototype.slice.call(arguments, 2), list;
+ if (operationGroup) {
+ list = operationGroup.delayedCallbacks;
+ } else if (orphanDelayedCallbacks) {
+ list = orphanDelayedCallbacks;
+ } else {
+ list = orphanDelayedCallbacks = [];
+ setTimeout(fireOrphanDelayed, 0);
+ }
+ function bnd(f) {return function(){f.apply(null, args);};};
+ for (var i = 0; i < arr.length; ++i)
+ list.push(bnd(arr[i]));
+ }
+
+ function fireOrphanDelayed() {
+ var delayed = orphanDelayedCallbacks;
+ orphanDelayedCallbacks = null;
+ for (var i = 0; i < delayed.length; ++i) delayed[i]();
+ }
+
+ // The DOM events that CodeMirror handles can be overridden by
+ // registering a (non-DOM) handler on the editor for the event name,
+ // and preventDefault-ing the event in that handler.
+ function signalDOMEvent(cm, e, override) {
+ if (typeof e == "string")
+ e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
+ signal(cm, override || e.type, cm, e);
+ return e_defaultPrevented(e) || e.codemirrorIgnore;
+ }
+
+ function signalCursorActivity(cm) {
+ var arr = cm._handlers && cm._handlers.cursorActivity;
+ if (!arr) return;
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
+ for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
+ set.push(arr[i]);
+ }
+
+ function hasHandler(emitter, type) {
+ var arr = emitter._handlers && emitter._handlers[type];
+ return arr && arr.length > 0;
+ }
+
+ // Add on and off methods to a constructor's prototype, to make
+ // registering events on such objects more convenient.
+ function eventMixin(ctor) {
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
+ }
+
+ // MISC UTILITIES
+
+ // Number of pixels added to scroller and sizer to hide scrollbar
+ var scrollerGap = 30;
+
+ // Returned or thrown by various protocols to signal 'I'm not
+ // handling this'.
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
+
+ // Reused option objects for setSelection & friends
+ var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
+
+ function Delayed() {this.id = null;}
+ Delayed.prototype.set = function(ms, f) {
+ clearTimeout(this.id);
+ this.id = setTimeout(f, ms);
+ };
+
+ // Counts the column offset in a string, taking tabs into account.
+ // Used mostly to find indentation.
+ var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
+ if (end == null) {
+ end = string.search(/[^\s\u00a0]/);
+ if (end == -1) end = string.length;
+ }
+ for (var i = startIndex || 0, n = startValue || 0;;) {
+ var nextTab = string.indexOf("\t", i);
+ if (nextTab < 0 || nextTab >= end)
+ return n + (end - i);
+ n += nextTab - i;
+ n += tabSize - (n % tabSize);
+ i = nextTab + 1;
+ }
+ };
+
+ // The inverse of countColumn -- find the offset that corresponds to
+ // a particular column.
+ function findColumn(string, goal, tabSize) {
+ for (var pos = 0, col = 0;;) {
+ var nextTab = string.indexOf("\t", pos);
+ if (nextTab == -1) nextTab = string.length;
+ var skipped = nextTab - pos;
+ if (nextTab == string.length || col + skipped >= goal)
+ return pos + Math.min(skipped, goal - col);
+ col += nextTab - pos;
+ col += tabSize - (col % tabSize);
+ pos = nextTab + 1;
+ if (col >= goal) return pos;
+ }
+ }
+
+ var spaceStrs = [""];
+ function spaceStr(n) {
+ while (spaceStrs.length <= n)
+ spaceStrs.push(lst(spaceStrs) + " ");
+ return spaceStrs[n];
+ }
+
+ function lst(arr) { return arr[arr.length-1]; }
+
+ var selectInput = function(node) { node.select(); };
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
+ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
+ else if (ie) // Suppress mysterious IE10 errors
+ selectInput = function(node) { try { node.select(); } catch(_e) {} };
+
+ function indexOf(array, elt) {
+ for (var i = 0; i < array.length; ++i)
+ if (array[i] == elt) return i;
+ return -1;
+ }
+ function map(array, f) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
+ return out;
+ }
+
+ function nothing() {}
+
+ function createObj(base, props) {
+ var inst;
+ if (Object.create) {
+ inst = Object.create(base);
+ } else {
+ nothing.prototype = base;
+ inst = new nothing();
+ }
+ if (props) copyObj(props, inst);
+ return inst;
+ };
+
+ function copyObj(obj, target, overwrite) {
+ if (!target) target = {};
+ for (var prop in obj)
+ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
+ target[prop] = obj[prop];
+ return target;
+ }
+
+ function bind(f) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function(){return f.apply(null, args);};
+ }
+
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
+ var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
+ return /\w/.test(ch) || ch > "\x80" &&
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
+ };
+ function isWordChar(ch, helper) {
+ if (!helper) return isWordCharBasic(ch);
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
+ return helper.test(ch);
+ }
+
+ function isEmpty(obj) {
+ for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
+ return true;
+ }
+
+ // Extending unicode characters. A series of a non-extending char +
+ // any number of extending chars is treated as a single unit as far
+ // as editing and measuring is concerned. This is not fully correct,
+ // since some scripts/fonts/browsers also treat other configurations
+ // of code points as a group.
+ 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]/;
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
+
+ // DOM UTILITIES
+
+ function elt(tag, content, className, style) {
+ var e = document.createElement(tag);
+ if (className) e.className = className;
+ if (style) e.style.cssText = style;
+ if (typeof content == "string") e.appendChild(document.createTextNode(content));
+ else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
+ return e;
+ }
+
+ var range;
+ if (document.createRange) range = function(node, start, end, endNode) {
+ var r = document.createRange();
+ r.setEnd(endNode || node, end);
+ r.setStart(node, start);
+ return r;
+ };
+ else range = function(node, start, end) {
+ var r = document.body.createTextRange();
+ try { r.moveToElementText(node.parentNode); }
+ catch(e) { return r; }
+ r.collapse(true);
+ r.moveEnd("character", end);
+ r.moveStart("character", start);
+ return r;
+ };
+
+ function removeChildren(e) {
+ for (var count = e.childNodes.length; count > 0; --count)
+ e.removeChild(e.firstChild);
+ return e;
+ }
+
+ function removeChildrenAndAdd(parent, e) {
+ return removeChildren(parent).appendChild(e);
+ }
+
+ var contains = CodeMirror.contains = function(parent, child) {
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
+ child = child.parentNode;
+ if (parent.contains)
+ return parent.contains(child);
+ do {
+ if (child.nodeType == 11) child = child.host;
+ if (child == parent) return true;
+ } while (child = child.parentNode);
+ };
+
+ function activeElt() { return document.activeElement; }
+ // Older versions of IE throws unspecified error when touching
+ // document.activeElement in some cases (during loading, in iframe)
+ if (ie && ie_version < 11) activeElt = function() {
+ try { return document.activeElement; }
+ catch(e) { return document.body; }
+ };
+
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
+ var rmClass = CodeMirror.rmClass = function(node, cls) {
+ var current = node.className;
+ var match = classTest(cls).exec(current);
+ if (match) {
+ var after = current.slice(match.index + match[0].length);
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
+ }
+ };
+ var addClass = CodeMirror.addClass = function(node, cls) {
+ var current = node.className;
+ if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
+ };
+ function joinClasses(a, b) {
+ var as = a.split(" ");
+ for (var i = 0; i < as.length; i++)
+ if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
+ return b;
+ }
+
+ // WINDOW-WIDE EVENTS
+
+ // These must be handled carefully, because naively registering a
+ // handler for each editor will cause the editors to never be
+ // garbage collected.
+
+ function forEachCodeMirror(f) {
+ if (!document.body.getElementsByClassName) return;
+ var byClass = document.body.getElementsByClassName("CodeMirror");
+ for (var i = 0; i < byClass.length; i++) {
+ var cm = byClass[i].CodeMirror;
+ if (cm) f(cm);
+ }
+ }
+
+ var globalsRegistered = false;
+ function ensureGlobalHandlers() {
+ if (globalsRegistered) return;
+ registerGlobalHandlers();
+ globalsRegistered = true;
+ }
+ function registerGlobalHandlers() {
+ // When the window resizes, we need to refresh active editors.
+ var resizeTimer;
+ on(window, "resize", function() {
+ if (resizeTimer == null) resizeTimer = setTimeout(function() {
+ resizeTimer = null;
+ forEachCodeMirror(onResize);
+ }, 100);
+ });
+ // When the window loses focus, we want to show the editor as blurred
+ on(window, "blur", function() {
+ forEachCodeMirror(onBlur);
+ });
+ }
+
+ // FEATURE DETECTION
+
+ // Detect drag-and-drop
+ var dragAndDrop = function() {
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
+ // couldn't get it to work yet.
+ if (ie && ie_version < 9) return false;
+ var div = elt('div');
+ return "draggable" in div || "dragDrop" in div;
+ }();
+
+ var zwspSupported;
+ function zeroWidthElement(measure) {
+ if (zwspSupported == null) {
+ var test = elt("span", "\u200b");
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
+ if (measure.firstChild.offsetHeight != 0)
+ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
+ }
+ var node = zwspSupported ? elt("span", "\u200b") :
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
+ node.setAttribute("cm-text", "");
+ return node;
+ }
+
+ // Feature-detect IE's crummy client rect reporting for bidi text
+ var badBidiRects;
+ function hasBadBidiRects(measure) {
+ if (badBidiRects != null) return badBidiRects;
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
+ if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
+ return badBidiRects = (r1.right - r0.right < 3);
+ }
+
+ // See if "".split is the broken IE version, if so, provide an
+ // alternative way to split lines.
+ var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
+ var pos = 0, result = [], l = string.length;
+ while (pos <= l) {
+ var nl = string.indexOf("\n", pos);
+ if (nl == -1) nl = string.length;
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
+ var rt = line.indexOf("\r");
+ if (rt != -1) {
+ result.push(line.slice(0, rt));
+ pos += rt + 1;
+ } else {
+ result.push(line);
+ pos = nl + 1;
+ }
+ }
+ return result;
+ } : function(string){return string.split(/\r\n?|\n/);};
+
+ var hasSelection = window.getSelection ? function(te) {
+ try { return te.selectionStart != te.selectionEnd; }
+ catch(e) { return false; }
+ } : function(te) {
+ try {var range = te.ownerDocument.selection.createRange();}
+ catch(e) {}
+ if (!range || range.parentElement() != te) return false;
+ return range.compareEndPoints("StartToEnd", range) != 0;
+ };
+
+ var hasCopyEvent = (function() {
+ var e = elt("div");
+ if ("oncopy" in e) return true;
+ e.setAttribute("oncopy", "return;");
+ return typeof e.oncopy == "function";
+ })();
+
+ var badZoomedRects = null;
+ function hasBadZoomedRects(measure) {
+ if (badZoomedRects != null) return badZoomedRects;
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
+ var normal = node.getBoundingClientRect();
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
+ }
+
+ // KEY NAMES
+
+ var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
+ CodeMirror.keyNames = keyNames;
+ (function() {
+ // Number keys
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
+ // Alphabetic keys
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
+ // Function keys
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
+ })();
+
+ // BIDI HELPERS
+
+ function iterateBidiSections(order, from, to, f) {
+ if (!order) return f(from, to, "ltr");
+ var found = false;
+ for (var i = 0; i < order.length; ++i) {
+ var part = order[i];
+ if (part.from < to && part.to > from || from == to && part.to == from) {
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
+ found = true;
+ }
+ }
+ if (!found) f(from, to, "ltr");
+ }
+
+ function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
+ function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
+
+ function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
+ function lineRight(line) {
+ var order = getOrder(line);
+ if (!order) return line.text.length;
+ return bidiRight(lst(order));
+ }
+
+ function lineStart(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLine(line);
+ if (visual != line) lineN = lineNo(visual);
+ var order = getOrder(visual);
+ var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
+ return Pos(lineN, ch);
+ }
+ function lineEnd(cm, lineN) {
+ var merged, line = getLine(cm.doc, lineN);
+ while (merged = collapsedSpanAtEnd(line)) {
+ line = merged.find(1, true).line;
+ lineN = null;
+ }
+ var order = getOrder(line);
+ var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
+ return Pos(lineN == null ? lineNo(line) : lineN, ch);
+ }
+ function lineStartSmart(cm, pos) {
+ var start = lineStart(cm, pos.line);
+ var line = getLine(cm.doc, start.line);
+ var order = getOrder(line);
+ if (!order || order[0].level == 0) {
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
+ return Pos(start.line, inWS ? 0 : firstNonWS);
+ }
+ return start;
+ }
+
+ function compareBidiLevel(order, a, b) {
+ var linedir = order[0].level;
+ if (a == linedir) return true;
+ if (b == linedir) return false;
+ return a < b;
+ }
+ var bidiOther;
+ function getBidiPartAt(order, pos) {
+ bidiOther = null;
+ for (var i = 0, found; i < order.length; ++i) {
+ var cur = order[i];
+ if (cur.from < pos && cur.to > pos) return i;
+ if ((cur.from == pos || cur.to == pos)) {
+ if (found == null) {
+ found = i;
+ } else if (compareBidiLevel(order, cur.level, order[found].level)) {
+ if (cur.from != cur.to) bidiOther = found;
+ return i;
+ } else {
+ if (cur.from != cur.to) bidiOther = i;
+ return found;
+ }
+ }
+ }
+ return found;
+ }
+
+ function moveInLine(line, pos, dir, byUnit) {
+ if (!byUnit) return pos + dir;
+ do pos += dir;
+ while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
+ return pos;
+ }
+
+ // This is needed in order to move 'visually' through bi-directional
+ // text -- i.e., pressing left should make the cursor go left, even
+ // when in RTL text. The tricky part is the 'jumps', where RTL and
+ // LTR text touch each other. This often requires the cursor offset
+ // to move more than one unit, in order to visually move one unit.
+ function moveVisually(line, start, dir, byUnit) {
+ var bidi = getOrder(line);
+ if (!bidi) return moveLogically(line, start, dir, byUnit);
+ var pos = getBidiPartAt(bidi, start), part = bidi[pos];
+ var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
+
+ for (;;) {
+ if (target > part.from && target < part.to) return target;
+ if (target == part.from || target == part.to) {
+ if (getBidiPartAt(bidi, target) == pos) return target;
+ part = bidi[pos += dir];
+ return (dir > 0) == part.level % 2 ? part.to : part.from;
+ } else {
+ part = bidi[pos += dir];
+ if (!part) return null;
+ if ((dir > 0) == part.level % 2)
+ target = moveInLine(line, part.to, -1, byUnit);
+ else
+ target = moveInLine(line, part.from, 1, byUnit);
+ }
+ }
+ }
+
+ function moveLogically(line, start, dir, byUnit) {
+ var target = start + dir;
+ if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
+ return target < 0 || target > line.text.length ? null : target;
+ }
+
+ // Bidirectional ordering algorithm
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
+ // that this (partially) implements.
+
+ // One-char codes used for character types:
+ // L (L): Left-to-Right
+ // R (R): Right-to-Left
+ // r (AL): Right-to-Left Arabic
+ // 1 (EN): European Number
+ // + (ES): European Number Separator
+ // % (ET): European Number Terminator
+ // n (AN): Arabic Number
+ // , (CS): Common Number Separator
+ // m (NSM): Non-Spacing Mark
+ // b (BN): Boundary Neutral
+ // s (B): Paragraph Separator
+ // t (S): Segment Separator
+ // w (WS): Whitespace
+ // N (ON): Other Neutrals
+
+ // Returns null if characters are ordered as they appear
+ // (left-to-right), or an array of sections ({from, to, level}
+ // objects) in the order in which they occur visually.
+ var bidiOrdering = (function() {
+ // Character types for codepoints 0 to 0xff
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
+ // Character types for codepoints 0x600 to 0x6ff
+ var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
+ function charType(code) {
+ if (code <= 0xf7) return lowTypes.charAt(code);
+ else if (0x590 <= code && code <= 0x5f4) return "R";
+ else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
+ else if (0x6ee <= code && code <= 0x8ac) return "r";
+ else if (0x2000 <= code && code <= 0x200b) return "w";
+ else if (code == 0x200c) return "b";
+ else return "L";
+ }
+
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
+ // Browsers seem to always treat the boundaries of block elements as being L.
+ var outerType = "L";
+
+ function BidiSpan(level, from, to) {
+ this.level = level;
+ this.from = from; this.to = to;
+ }
+
+ return function(str) {
+ if (!bidiRE.test(str)) return false;
+ var len = str.length, types = [];
+ for (var i = 0, type; i < len; ++i)
+ types.push(type = charType(str.charCodeAt(i)));
+
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
+ // change the type of the NSM to the type of the previous
+ // character. If the NSM is at the start of the level run, it will
+ // get the type of sor.
+ for (var i = 0, prev = outerType; i < len; ++i) {
+ var type = types[i];
+ if (type == "m") types[i] = prev;
+ else prev = type;
+ }
+
+ // W2. Search backwards from each instance of a European number
+ // until the first strong type (R, L, AL, or sor) is found. If an
+ // AL is found, change the type of the European number to Arabic
+ // number.
+ // W3. Change all ALs to R.
+ for (var i = 0, cur = outerType; i < len; ++i) {
+ var type = types[i];
+ if (type == "1" && cur == "r") types[i] = "n";
+ else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
+ }
+
+ // W4. A single European separator between two European numbers
+ // changes to a European number. A single common separator between
+ // two numbers of the same type changes to that type.
+ for (var i = 1, prev = types[0]; i < len - 1; ++i) {
+ var type = types[i];
+ if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
+ else if (type == "," && prev == types[i+1] &&
+ (prev == "1" || prev == "n")) types[i] = prev;
+ prev = type;
+ }
+
+ // W5. A sequence of European terminators adjacent to European
+ // numbers changes to all European numbers.
+ // W6. Otherwise, separators and terminators change to Other
+ // Neutral.
+ for (var i = 0; i < len; ++i) {
+ var type = types[i];
+ if (type == ",") types[i] = "N";
+ else if (type == "%") {
+ for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
+ var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
+ for (var j = i; j < end; ++j) types[j] = replace;
+ i = end - 1;
+ }
+ }
+
+ // W7. Search backwards from each instance of a European number
+ // until the first strong type (R, L, or sor) is found. If an L is
+ // found, then change the type of the European number to L.
+ for (var i = 0, cur = outerType; i < len; ++i) {
+ var type = types[i];
+ if (cur == "L" && type == "1") types[i] = "L";
+ else if (isStrong.test(type)) cur = type;
+ }
+
+ // N1. A sequence of neutrals takes the direction of the
+ // surrounding strong text if the text on both sides has the same
+ // direction. European and Arabic numbers act as if they were R in
+ // terms of their influence on neutrals. Start-of-level-run (sor)
+ // and end-of-level-run (eor) are used at level run boundaries.
+ // N2. Any remaining neutrals take the embedding direction.
+ for (var i = 0; i < len; ++i) {
+ if (isNeutral.test(types[i])) {
+ for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
+ var before = (i ? types[i-1] : outerType) == "L";
+ var after = (end < len ? types[end] : outerType) == "L";
+ var replace = before || after ? "L" : "R";
+ for (var j = i; j < end; ++j) types[j] = replace;
+ i = end - 1;
+ }
+ }
+
+ // Here we depart from the documented algorithm, in order to avoid
+ // building up an actual levels array. Since there are only three
+ // levels (0, 1, 2) in an implementation that doesn't take
+ // explicit embedding into account, we can build up the order on
+ // the fly, without following the level-based algorithm.
+ var order = [], m;
+ for (var i = 0; i < len;) {
+ if (countsAsLeft.test(types[i])) {
+ var start = i;
+ for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
+ order.push(new BidiSpan(0, start, i));
+ } else {
+ var pos = i, at = order.length;
+ for (++i; i < len && types[i] != "L"; ++i) {}
+ for (var j = pos; j < i;) {
+ if (countsAsNum.test(types[j])) {
+ if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
+ var nstart = j;
+ for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
+ order.splice(at, 0, new BidiSpan(2, nstart, j));
+ pos = j;
+ } else ++j;
+ }
+ if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
+ }
+ }
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
+ order[0].from = m[0].length;
+ order.unshift(new BidiSpan(0, 0, m[0].length));
+ }
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
+ lst(order).to -= m[0].length;
+ order.push(new BidiSpan(0, len - m[0].length, len));
+ }
+ if (order[0].level == 2)
+ order.unshift(new BidiSpan(1, order[0].to, order[0].to));
+ if (order[0].level != lst(order).level)
+ order.push(new BidiSpan(order[0].level, len, len));
+
+ return order;
+ };
+ })();
+
+ // THE END
+
+ CodeMirror.version = "5.4.1";
+
+ return CodeMirror;
+});;
+(function ($) {
+ /**
+ * 公式编辑控件
+ * @class BI.FormulaEditor
+ * @extends BI.Widget
+ */
+ BI.FormulaEditor = BI.inherit(BI.Single, {
+ _defaultConfig: function () {
+ return $.extend(BI.FormulaEditor.superclass._defaultConfig.apply(), {
+ baseCls: 'bi-formula-editor',
+ watermark: '',
+ value: '',
+ fieldTextValueMap: {},
+ showHint: true
+ });
+ },
+ _init: function () {
+ BI.FormulaEditor.superclass._init.apply(this, arguments);
+ var o = this.options, self = this;
+ this.editor = CodeMirror(this.element[0], {
+ textWrapping: true,
+ lineWrapping: true,
+ lineNumbers: false,
+ mode: 'formula'
+ });
+ this.editor.on("change", function (cm, change) {
+ self._checkWaterMark();
+ if(o.showHint){
+ CodeMirror.showHint(cm, CodeMirror.formulaHint, {completeSingle: false});
+ }
+ BI.nextTick(function () {
+ self.fireEvent(BI.FormulaEditor.EVENT_CHANGE)
+ });
+ });
+
+ this.editor.on("focus", function () {
+ self._checkWaterMark();
+ self.fireEvent(BI.FormulaEditor.EVENT_FOCUS);
+ });
+
+ this.editor.on("blur", function () {
+ self.fireEvent(BI.FormulaEditor.EVENT_BLUR);
+ });
+
+
+ if (BI.isKey(o.value)) {
+ self.setValue(o.value);
+ }
+
+ if (BI.isKey(this.options.watermark)) {
+ var self = this;
+ this.watermark = BI.createWidget({
+ type: "bi.label",
+ cls: "bi-water-mark",
+ text: this.options.watermark,
+ whiteSpace: "nowrap",
+ textAlign: "left"
+ });
+ BI.createWidget({
+ type: "bi.absolute",
+ element: self,
+ items: [{
+ el: self.watermark,
+ left: 0,
+ top: 0
+ }]
+ });
+
+ this.watermark.element.bind(
+ "mousedown", function (e) {
+ self.insertString("");
+ self.editor.focus();
+ e.stopEvent();
+ }
+ );
+ this.watermark.element.bind("click", function (e) {
+ self.editor.focus();
+ e.stopEvent();
+ });
+ this.watermark.element.css({
+ position: "absolute",
+ left: 3,
+ right: 3,
+ top: 6,
+ bottom: 0
+ });
+ }
+ },
+
+ _checkWaterMark: function () {
+ var o = this.options;
+ if (!this.disabledWarterMark && BI.isEmptyString(this.editor.getValue()) && BI.isKey(o.watermark)) {
+ this.watermark && this.watermark.visible();
+ } else {
+ this.watermark && this.watermark.invisible();
+ }
+ },
+
+ disableWarterMark: function () {
+ this.disabledWarterMark = true;
+ this._checkWaterMark();
+ },
+
+ focus: function() {
+ this.editor.focus();
+ },
+
+ /**
+ * 添加字段
+ * @param field
+ */
+ insertField: function (field) {
+ var from = this.editor.getCursor();
+ this.editor.replaceSelection(field);
+ var to = this.editor.getCursor();
+ this.editor.markText(from, to, {className: 'fieldName', atomic: true, startStyle : "start", endStyle:"end"});
+ this.editor.replaceSelection(" ");
+ this.editor.focus();
+ },
+
+ insertFunction: function (fn) {
+ var from = this.editor.getCursor();
+ this.editor.replaceSelection(fn);
+ var to = this.editor.getCursor();
+ this.editor.markText(from, to, {className: "#function", atomic: true});
+ this.editor.replaceSelection("() ");
+ to = this.editor.getCursor();
+ to.ch = to.ch - 2;
+ this.editor.setCursor(to);
+ this.editor.focus();
+ },
+ insertOperator: function (op) {
+ var from = this.editor.getCursor();
+ this.editor.replaceSelection(op);
+ var to = this.editor.getCursor();
+ this.editor.markText(from, to, {className: "%operator", atomic: true});
+ this.editor.replaceSelection(" ");
+ this.editor.focus();
+ },
+
+ setFunction: function (v) {
+ var from = this.editor.getCursor();
+ this.editor.replaceSelection(v);
+ var to = this.editor.getCursor();
+ this.editor.markText(from, to, {className: "#function", atomic: true});
+ },
+
+ insertString: function (str) {
+ this.editor.replaceSelection(str);
+ this.editor.focus();
+ },
+
+ getFormulaString: function () {
+ return this.editor.getValue();
+ },
+
+ getUsedFields: function () {
+ var fieldMap = this.options.fieldTextValueMap;
+ var fields = [];
+ this.editor.getValue(true, function (line) {
+ var value = line.text;
+ _.forEach(line.markedSpans, function (i, ms) {
+ switch (i.marker.className) {
+ case "fieldName":
+ var dId = fieldMap[value.substr(i.from, i.to - i.from)];
+ if (!fields.contains(dId)) {
+ fields.push(dId);
+ }
+
+ }
+ });
+ });
+ return fields;
+ },
+
+ getCheckString: function () {
+ return this.editor.getValue(true, function (line) {
+ var rawText = line.text, value = line.text, num = 0;
+ value.text = rawText;
+ _.forEach(line.markedSpans, function (i, ms) {
+
+ switch (i.marker.className) {
+ case "fieldName":
+ var fieldNameLength = i.to - i.from;
+ value = value.substr(0, i.from + num) + "$a" + value.substr(i.to + num, value.length);
+ num = num + 2 - fieldNameLength;
+ break;
+ }
+
+ });
+ return value;
+ });
+ },
+
+ getValue: function () {
+ var fieldMap = this.options.fieldTextValueMap;
+ return this.editor.getValue("\n", function (line) {
+ var rawText = line.text, value = line.text, num = 0;
+ value.text = rawText;
+ _.forEach(line.markedSpans, function (i, ms) {
+ switch (i.marker.className) {
+ case "fieldName":
+ var fieldNameLength = i.to - i.from;
+ var fieldId = fieldMap[value.substr(i.from + num, fieldNameLength)];
+ value = value.substr(0, i.from + num) + "$\{" + fieldMap[value.substr(i.from + num, fieldNameLength)] + "\}" + value.substr(i.to + num, value.length);
+ num += fieldId.length - fieldNameLength + 3;
+ break;
+ }
+ });
+ return value;
+ });
+ },
+
+ setValue: function (value) {
+ this.editor.setValue(value);
+ },
+
+ setFieldTextValueMap: function (fieldTextValueMap) {
+ this.options.fieldTextValueMap = fieldTextValueMap;
+ },
+
+ refresh: function () {
+ var self = this;
+ BI.nextTick(function () {
+ self.editor.refresh();
+ });
+ }
+
+ });
+ BI.FormulaEditor.EVENT_CHANGE = "EVENT_CHANGE";
+ BI.FormulaEditor.EVENT_BLUR = "EVENT_BLUR";
+ BI.FormulaEditor.EVENT_FOCUS = "EVENT_FOCUS";
+ $.shortcut("bi.formula", BI.FormulaEditor);
+})(jQuery);
+/**
+ * z-index在1亿层级
+ * 弹出提示消息框,用于模拟阻塞操作(通过回调函数实现)
+ * @class BI.Msg
+ */
+$.extend(BI, {
+ Msg: function () {
+
+ var messageShow, $mask, $pop;
+
+ return {
+ alert: function (title, message, callback) {
+ this._show(false, title, message, callback);
+ },
+ confirm: function (title, message, callback, min_width) {
+ this._show(true, title, message, callback);
+ },
+ prompt: function (title, message, value, callback, min_width) {
+ FR.Msg.prompt(title, message, value, callback, min_width);
+ },
+ toast: function (message, level, context) {
+ context = context || $("body");
+ var toast = BI.createWidget({
+ type: "bi.toast",
+ level: level,
+ text: message
+ });
+ BI.createWidget({
+ type: "bi.absolute",
+ element: context,
+ items: [{
+ el: toast,
+ left: "50%",
+ top: 0
+ }]
+ });
+ if (toast.element.outerWidth() > context.outerWidth()) {
+ toast.setWidth(context.width());
+ }
+ toast.element.css({"margin-left": -1 * toast.element.outerWidth() / 2});
+ toast.invisible();
+ toast.element.slideDown(500, function () {
+ BI.delay(function () {
+ toast.element.slideUp(500, function () {
+ toast.destroy();
+ })
+ }, 5000)
+ })
+ },
+ _show: function (hasCancel, title, message, callback) {
+ $mask = $('').css({
+ position: 'absolute',
+ 'zIndex': BI.zIndex_tip - 2,
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ opacity: 0.5
+ }).appendTo('body');
+ $pop = $(' ').css({
+ position: 'absolute',
+ 'zIndex': BI.zIndex_tip - 1,
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0
+ }).appendTo('body');
+ var close = function () {
+ messageShow.destroy();
+ $mask.remove();
+ };
+ var controlItems = [];
+ if (hasCancel === true) {
+ controlItems.push({
+ el: {
+ type: 'bi.button',
+ text: BI.i18nText("BI-Basic_Cancel"),
+ height: 30,
+ level: 'ignore',
+ handler: function () {
+ close();
+ if (BI.isFunction(callback)) {
+ callback.apply(null, [false]);
+ }
+ }
+ }
+ });
+ }
+ controlItems.push({
+ el: {
+ type: 'bi.button',
+ text: BI.i18nText("BI-Basic_OK"),
+ height: 30,
+ handler: function () {
+ close();
+ if (BI.isFunction(callback)) {
+ callback.apply(null, [true]);
+ }
+ }
+ }
+ });
+ var conf = {
+ element: $pop,
+ type: 'bi.center_adapt',
+ items: [
+ {
+ type: 'bi.border',
+ cls: 'bi-message-content',
+ items: {
+ 'north': {
+ el: {
+ type: 'bi.border',
+ cls: 'bi-message-title',
+ items: {
+ center: {
+ el: {
+ type: 'bi.label',
+ text: title || BI.i18nText("BI-Basic_Prompt"),
+ textAlign: 'left',
+ hgap: 20,
+ height: 50
+ }
+ },
+ east: {
+ el: {
+ type: 'bi.icon_button',
+ cls: 'bi-message-close close-font',
+// height: 50,
+ handler: function () {
+ close();
+ }
+ },
+ width: 60
+ }
+ }
+ },
+ height: 50
+ },
+ 'center': {
+ el: {
+ type: "bi.text",
+ cls: "bi-message-text",
+ tgap: 60,
+ hgap: 20,
+ lineHeight: 30,
+ whiteSpace: "normal",
+ text: message
+ }
+ },
+ 'south': {
+ el: {
+ type: "bi.absolute",
+ items: [{
+ el: {
+ type: 'bi.right_vertical_adapt',
+ hgap: 5,
+ items: controlItems
+ },
+ top: 0,
+ left: 20,
+ right: 20,
+ bottom: 0
+ }]
+
+ },
+ height: 60
+ }
+ },
+ width: 400,
+ height: 300
+ }
+ ]
+ };
+
+ messageShow = BI.createWidget(conf);
+ }
+ };
+ }()
+});/**
+ * Grid
+ *
+ * Created by GUY on 2016/1/11.
+ * @class BI.Grid
+ * @extends BI.Widget
+ */
+BI.Grid = BI.inherit(BI.Widget, {
+ _defaultConfig: function () {
+ return BI.extend(BI.Grid.superclass._defaultConfig.apply(this, arguments), {
+ baseCls: "bi-grid",
+ width: 400,
+ height: 300,
+ overflowX: true,
+ overflowY: true,
+ overscanColumnCount: 0,
+ overscanRowCount: 0,
+ rowHeightGetter: BI.emptyFn,
+ columnWidthGetter: BI.emptyFn,
+ estimatedColumnSize: 100,
+ estimatedRowSize: 30,
+ scrollLeft: 0,
+ scrollTop: 0,
+ items: []
+ });
+ },
+
+ _init: function () {
+ BI.Grid.superclass._init.apply(this, arguments);
+ var self = this, o = this.options;
+ this.renderedCells = [];
+ this.renderedKeys = [];
+ this._scrollLock = false;
+ this._debounceRelease = BI.debounce(function () {
+ self._scrollLock = false;
+ }, 150);
+ this.container = BI.createWidget({
+ type: "bi.absolute"
+ });
+ this.element.scroll(function () {
+ if (self._scrollLock === true) {
+ return;
+ }
+ o.scrollLeft = self.element.scrollLeft();
+ o.scrollTop = self.element.scrollTop();
+ self._calculateChildrenToRender();
+ self.fireEvent(BI.Grid.EVENT_SCROLL, {
+ scrollLeft: o.scrollLeft,
+ scrollTop: o.scrollTop
+ });
+ });
+ BI.createWidget({
+ type: "bi.vertical",
+ element: this,
+ scrollable: o.overflowX === true && o.overflowY === true,
+ scrolly: o.overflowX === false && o.overflowY === true,
+ scrollx: o.overflowX === true && o.overflowY === false,
+ items: [this.container]
+ });
+ if (o.items.length > 0) {
+ this._populate();
+ }
+ if (o.scrollLeft !== 0 || o.scrollTop !== 0) {
+ BI.nextTick(function () {
+ self.element.scrollTop(o.scrollTop);
+ self.element.scrollLeft(o.scrollLeft);
+ });
+ }
+ },
+
+ _getOverscanIndices: function (cellCount, overscanCellsCount, startIndex, stopIndex) {
+ return {
+ overscanStartIndex: Math.max(0, startIndex - overscanCellsCount),
+ overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount)
+ }
+ },
+
+ _calculateChildrenToRender: function () {
+ var self = this, o = this.options;
+
+ var width = o.width, height = o.height, scrollLeft = BI.clamp(o.scrollLeft, 0, this._getMaxScrollLeft()), scrollTop = BI.clamp(o.scrollTop, 0, this._getMaxScrollTop()),
+ overscanColumnCount = o.overscanColumnCount, overscanRowCount = o.overscanRowCount;
+
+ if (height > 0 && width > 0) {
+ var visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange(width, scrollLeft);
+ var visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange(height, scrollTop);
+
+ var horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment(width, scrollLeft);
+ var verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment(height, scrollTop);
+
+ this._renderedColumnStartIndex = visibleColumnIndices.start;
+ this._renderedColumnStopIndex = visibleColumnIndices.stop;
+ this._renderedRowStartIndex = visibleRowIndices.start;
+ this._renderedRowStopIndex = visibleRowIndices.stop;
+
+ var overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex)
+
+ var overscanRowIndices = this._getOverscanIndices(this.rowCount, overscanRowCount, this._renderedRowStartIndex, this._renderedRowStopIndex);
+
+ var columnStartIndex = overscanColumnIndices.overscanStartIndex;
+ var columnStopIndex = overscanColumnIndices.overscanStopIndex;
+ var rowStartIndex = overscanRowIndices.overscanStartIndex;
+ var rowStopIndex = overscanRowIndices.overscanStopIndex;
+
+ var renderedCells = [], renderedKeys = [];
+
+ for (var rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) {
+ var rowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex);
+
+ for (var columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) {
+ var key = [rowIndex, columnIndex];
+ var columnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex);
+
+ var index = BI.deepIndexOf(this.renderedKeys, key);
+ if (index > -1) {
+ if (columnDatum.size !== this.renderedCells[index]._width) {
+ this.renderedCells[index]._width = columnDatum.size;
+ this.renderedCells[index].el.setWidth(columnDatum.size);
+ }
+ if (rowDatum.size !== this.renderedCells[index]._height) {
+ this.renderedCells[index]._height = rowDatum.size;
+ this.renderedCells[index].el.setHeight(rowDatum.size);
+ }
+ if (this.renderedCells[index].left !== columnDatum.offset + horizontalOffsetAdjustment) {
+ this.renderedCells[index].el.element.css("left", (columnDatum.offset + horizontalOffsetAdjustment) + "px");
+ }
+ if (this.renderedCells[index].top !== rowDatum.offset + verticalOffsetAdjustment) {
+ this.renderedCells[index].el.element.css("top", (rowDatum.offset + verticalOffsetAdjustment) + "px");
+ }
+ renderedCells.push(this.renderedCells[index]);
+ } else {
+ var child = BI.createWidget(BI.extend({
+ type: "bi.label",
+ width: columnDatum.size,
+ height: rowDatum.size
+ }, o.items[rowIndex][columnIndex], {
+ cls: (o.items[rowIndex][columnIndex].cls || "") + " grid-cell" + (rowIndex === 0 ? " first-row" : "") + (columnIndex === 0 ? " first-col" : ""),
+ _rowIndex: rowIndex,
+ _columnIndex: columnIndex,
+ _left: columnDatum.offset + horizontalOffsetAdjustment,
+ _top: rowDatum.offset + verticalOffsetAdjustment
+ }));
+ renderedCells.push({
+ el: child,
+ left: columnDatum.offset + horizontalOffsetAdjustment,
+ top: rowDatum.offset + verticalOffsetAdjustment,
+ _width: columnDatum.size,
+ _height: rowDatum.size
+ });
+ }
+ renderedKeys.push(key);
+ }
+ }
+ //已存在的, 需要添加的和需要删除的
+ var existSet = {}, addSet = {}, deleteArray = [];
+ BI.each(renderedKeys, function (i, key) {
+ if (BI.deepContains(self.renderedKeys, key)) {
+ existSet[i] = key;
+ } else {
+ addSet[i] = key;
+ }
+ });
+ BI.each(this.renderedKeys, function (i, key) {
+ if (BI.deepContains(existSet, key)) {
+ return;
+ }
+ if (BI.deepContains(addSet, key)) {
+ return;
+ }
+ deleteArray.push(i);
+ });
+ BI.each(deleteArray, function (i, index) {
+ self.renderedCells[index].el.destroy();
+ });
+ var addedItems = [];
+ BI.each(addSet, function (index) {
+ addedItems.push(renderedCells[index])
+ });
+ BI.createWidget({
+ type: "bi.absolute",
+ element: this.container,
+ items: addedItems
+ });
+ this.renderedCells = renderedCells;
+ this.renderedKeys = renderedKeys;
+ }
+ },
+
+ _getMaxScrollLeft: function () {
+ return Math.max(0, this._columnSizeAndPositionManager.getTotalSize() - this.options.width + (this.options.overflowX ? BI.DOM.getScrollWidth() : 0));
+ },
+
+ _getMaxScrollTop: function () {
+ return Math.max(0, this._rowSizeAndPositionManager.getTotalSize() - this.options.height + (this.options.overflowY ? BI.DOM.getScrollWidth() : 0));
+ },
+
+ _populate: function () {
+ var self = this, o = this.options;
+ if (o.items.length > 0) {
+ this.columnCount = o.items[0].length;
+ this.rowCount = o.items.length;
+ this.container.setWidth(this.columnCount * o.estimatedColumnSize);
+ this.container.setHeight(this.rowCount * o.estimatedRowSize);
+
+ this._columnSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.columnCount, o.columnWidthGetter, o.estimatedColumnSize);
+ this._rowSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.rowCount, o.rowHeightGetter, o.estimatedRowSize);
+
+ this._calculateChildrenToRender();
+ this.element.scrollTop(o.scrollTop);
+ this.element.scrollLeft(o.scrollLeft);
+ }
+ },
+
+ setScrollLeft: function (scrollLeft) {
+ if (this.options.scrollLeft === scrollLeft) {
+ return;
+ }
+ this._scrollLock = true;
+ this.options.scrollLeft = BI.clamp(scrollLeft || 0, 0, this._getMaxScrollLeft());
+ this._debounceRelease();
+ this._calculateChildrenToRender();
+ this.element.scrollLeft(this.options.scrollLeft);
+ },
+
+ setScrollTop: function (scrollTop) {
+ if (this.options.scrollTop === scrollTop) {
+ return;
+ }
+ this._scrollLock = true;
+ this.options.scrollTop = BI.clamp(scrollTop || 0, 0, this._getMaxScrollTop());
+ this._debounceRelease();
+ this._calculateChildrenToRender();
+ this.element.scrollTop(this.options.scrollTop);
+ },
+
+ setOverflowX: function (b) {
+ var self = this;
+ if (this.options.overflowX !== !!b) {
+ this.options.overflowX = !!b;
+ BI.nextTick(function () {
+ self.element.css({overflowX: !!b ? "auto" : "hidden"});
+ });
+ }
+ },
+
+ setOverflowY: function (b) {
+ var self = this;
+ if (this.options.overflowY !== !!b) {
+ this.options.overflowY = !!b;
+ BI.nextTick(function () {
+ self.element.css({overflowY: !!b ? "auto" : "hidden"});
+ });
+ }
+ },
+
+ getScrollLeft: function () {
+ return this.options.scrollLeft;
+ },
+
+ getScrollTop: function () {
+ return this.options.scrollTop;
+ },
+
+ getMaxScrollLeft: function () {
+ return this._getMaxScrollLeft();
+ },
+
+ getMaxScrollTop: function () {
+ return this._getMaxScrollTop();
+ },
+
+ setEstimatedColumnSize: function (width) {
+ this.options.estimatedColumnSize = width;
+ },
+
+ setEstimatedRowSize: function (height) {
+ this.options.estimatedRowSize = height;
+ },
+
+ restore: function () {
+ BI.each(this.renderedCells, function (i, cell) {
+ cell.el.destroy();
+ });
+ this.renderedCells = [];
+ this.renderedKeys = [];
+ this._scrollLock = false;
+ },
+
+ populate: function (items) {
+ if (items && items !== this.options.items) {
+ this.options.items = items;
+ this.restore();
+ }
+ this._populate();
+ }
+});
+BI.Grid.EVENT_SCROLL = "EVENT_SCROLL";
+$.shortcut('bi.grid_view', BI.Grid);/**
+ * floatBox弹出层,
+ * @class BI.FloatBox
+ * @extends BI.Widget
+ */
+BI.FloatBox = BI.inherit(BI.Widget, {
+ _defaultConfig: function () {
+ return BI.extend(BI.FloatBox.superclass._defaultConfig.apply(this, arguments), {
+ baseCls: "bi-float-box",
+ width: 600,
+ height: 500
+ })
+ },
+ _init: function () {
+ BI.FloatBox.superclass._init.apply(this, arguments);
+ var self = this, o = this.options;
+ this.showAction = new BI.ShowAction({
+ tar: this
+ });
+ this._center = BI.createWidget();
+ this._north = BI.createWidget();
+ this.element.draggable({
+ cursor: BICst.cursorUrl,
+ handle: ".bi-message-title",
+ drag: function (e, ui) {
+ var W = $("body").width(), H = $("body").height();
+ if (ui.position.left + o.width > W) {
+ ui.position.left = W - o.width;
+ }
+ if (ui.position.top + o.height > H) {
+ ui.position.top = H - o.height;
+ }
+ if (ui.position.left < 0) {
+ ui.position.left = 0;
+ }
+ if (ui.position.top < 0) {
+ ui.position.top = 0;
+ }
+ }
+ });
+ this._south = BI.createWidget();
+ BI.createWidget({
+ type: 'bi.border',
+ element: this,
+ items: {
+ 'north': {
+ el: {
+ type: 'bi.border',
+ cls: 'bi-message-title',
+ items: {
+ center: {
+ el: {
+ type: "bi.absolute",
+ items: [{
+ el: this._north,
+ left: 10,
+ top: 0,
+ right: 0,
+ bottom: 0
+ }]
+ }
+ },
+ east: {
+ el: {
+ type: 'bi.icon_button',
+ cls: 'bi-message-close close-font',
+ height: 50,
+ handler: function () {
+ self.currentSectionProvider.close();
+ }
+ },
+ width: 60
+ }
+ }
+ },
+ height: 50
+ },
+ 'center': {
+ el: {
+ type: "bi.absolute",
+ items: [{
+ el: this._center,
+ left: 10,
+ top: 10,
+ right: 10,
+ bottom: 10
+ }]
+ }
+ },
+ 'south': {
+ el: {
+ type: "bi.absolute",
+ items: [{
+ el: this._south,
+ left: 10,
+ top: 0,
+ right: 10,
+ bottom: 0
+ }]
+ },
+ height: 60
+ }
+ }
+ })
+ },
+
+ populate: function (sectionProvider) {
+ var self = this;
+ this.currentSectionProvider = sectionProvider;
+ sectionProvider.rebuildNorth(this._north);
+ sectionProvider.rebuildCenter(this._center);
+ sectionProvider.rebuildSouth(this._south);
+ if (sectionProvider instanceof BI.Widget) {
+ sectionProvider.on(BI.PopoverSection.EVENT_CLOSE, function () {
+ self.close();
+ })
+ }
+ },
+
+ show: function () {
+ this.showAction.actionPerformed();
+ },
+
+ hide: function () {
+ this.showAction.actionBack();
+ },
+
+ open: function () {
+ this.show();
+ this.fireEvent(BI.FloatBox.EVENT_FLOAT_BOX_OPEN);
+ },
+
+ close: function () {
+ this.hide();
+ this.fireEvent(BI.FloatBox.EVENT_FLOAT_BOX_CLOSED);
+ },
+
+ setZindex: function (zindex) {
+ this.element.css({"z-index": zindex});
+ }
+});
+
+$.shortcut("bi.float_box", BI.FloatBox);
+
+BI.FloatBox.EVENT_FLOAT_BOX_CLOSED = "EVENT_FLOAT_BOX_CLOSED";
+BI.FloatBox.EVENT_FLOAT_BOX_OPEN = "EVENT_FLOAT_BOX_CLOSED";
+/**
+ * 下拉框弹出层, zIndex在1000w
+ * @class BI.PopupView
+ * @extends BI.Widget
+ */
+BI.PopupView = BI.inherit(BI.Widget, {
+ _defaultConfig: function () {
+ return BI.extend(BI.PopupView.superclass._defaultConfig.apply(this, arguments), {
+ baseCls: "bi-list-view",
+ maxWidth: 'auto',
+ minWidth: 100,
+ //maxHeight: 200,
+ minHeight: 25,
+ lgap: 0,
+ rgap: 0,
+ tgap: 0,
+ bgap: 0,
+ vgap: 0,
+ hgap: 0,
+ direction: BI.Direction.Top, //工具栏的方向
+ stopEvent: false,//是否停止mousedown、mouseup事件
+ stopPropagation: false, //是否停止mousedown、mouseup向上冒泡
+ logic: {
+ dynamic: true
+ },
+
+ tool: false, //自定义工具栏
+ tabs: [], //导航栏
+ buttons: [], //toolbar栏
+
+ el: {
+ type: "bi.button_group",
+ items: [],
+ chooseType: 0,
+ behaviors: {},
+ layouts: [{
+ type: "bi.vertical"
+ }]
+ }
+ })
+ },
+
+ _init: function () {
+ BI.PopupView.superclass._init.apply(this, arguments);
+ var self = this, o = this.options;
+ var fn = function (e) {
+ e.stopPropagation();
+ }, stop = function (e) {
+ e.stopEvent();
+ return false;
+ };
+ this.element.css({
+ "z-index": BI.zIndex_popup,
+ "min-width": o.minWidth + "px",
+ "max-width": o.maxWidth + "px"
+ }).bind({"click": fn});
+
+ //FIXME IE8下 jquery.mousewheeel.js 第一次执行65行$elem["offsetParent"]()的时候报错:未指明的错误 但是第二次或者调试的时候展开一下$elem内容均能避免上述问题
+ try {
+ this.element.bind("mousewheel", fn);
+ } catch (e) {
+ this.element.bind("mousewheel", fn);
+ }
+
+ o.stopPropagation && this.element.bind({"mousedown": fn, "mouseup": fn, "mouseover": fn});
+ o.stopEvent && this.element.bind({"mousedown": stop, "mouseup": stop, "mouseover": stop});
+ this.tool = this._createTool();
+ this.tab = this._createTab();
+ this.view = this._createView();
+ this.toolbar = this._createToolBar();
+
+ this.button_group.on(BI.Controller.EVENT_CHANGE, function (type) {
+ self.fireEvent(BI.Controller.EVENT_CHANGE, arguments);
+ if (type === BI.Events.CLICK) {
+ self.fireEvent(BI.PopupView.EVENT_CHANGE);
+ }
+ });
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({}, o.logic, {
+ scrolly: false,
+ lgap: o.lgap,
+ rgap: o.rgap,
+ tgap: o.tgap,
+ bgap: o.bgap,
+ vgap: o.vgap,
+ hgap: o.hgap,
+ items: BI.LogicFactory.createLogicItemsByDirection(o.direction,
+ BI.extend({
+ cls: "list-view-outer"
+ }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({}, o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.tool, this.tab, this.view, this.toolbar)
+ })))
+ )
+ }))));
+ },
+
+ _createView: function () {
+ var o = this.options;
+ this.button_group = BI.createWidget(o.el, {type: "bi.button_group"});
+ this.button_group.element.css({"min-height": o.minHeight + "px"});
+ return this.button_group;
+ },
+
+ _createTool: function () {
+ var o = this.options;
+ if (false === o.tool) {
+ return;
+ }
+ return BI.createWidget(o.tool)
+ },
+
+ _createTab: function () {
+ var o = this.options;
+ if (o.tabs.length === 0) {
+ return;
+ }
+ return BI.createWidget({
+ type: "bi.center",
+ cls: "list-view-tab",
+ height: 25,
+ items: o.tabs
+ })
+ },
+
+ _createToolBar: function () {
+ var o = this.options;
+ if (o.buttons.length === 0) {
+ return;
+ }
+
+ return BI.createWidget({
+ type: "bi.center",
+ cls: "list-view-toolbar",
+ height: 30,
+ items: BI.createItems(o.buttons, {
+ once: false,
+ shadow: true,
+ isShadowShowingOnSelected: true
+ })
+ })
+ },
+
+ getView: function () {
+ return this.button_group;
+ },
+
+ populate: function (items) {
+ this.button_group.populate.apply(this.button_group, arguments);
+ },
+
+ resetWidth: function (w) {
+ this.options.width = w;
+ this.element.width(w);
+ },
+
+ resetHeight: function (h) {
+ var tbHeight = this.toolbar ? (this.toolbar.attr("height") || 30) : 0,
+ tabHeight = this.tab ? (this.tab.attr("height") || 25) : 0,
+ toolHeight = ((this.tool && this.tool.attr("height")) || 25) * ((this.tool && this.tool.isVisible()) ? 1 : 0);
+ this.view.resetHeight ? this.view.resetHeight(h - tbHeight - tabHeight - toolHeight - 2) :
+ this.view.element.css({"max-height": (h - tbHeight - tabHeight - toolHeight - 2) + "px"})
+ },
+
+ setEnable: function (arg) {
+ BI.PopupView.superclass.setEnable.apply(this, arguments);
+ this.view && this.view.setEnable(arg);
+ },
+
+ setValue: function (selectedValues) {
+ this.tab && this.tab.setValue(selectedValues);
+ this.button_group.setValue(selectedValues);
+ },
+
+ getValue: function () {
+ return this.button_group.getValue();
+ }
+});
+BI.PopupView.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.popup_view", BI.PopupView);/**
+ * guy
+ * @class BI.ScrollView
+ * @extends BI.Widget
+ */
+BI.ScrollView = BI.inherit(BI.Widget, {
+
+ _const: {
+ dropDownHeight: 15,
+ expandIcon: "column-next-page-h-font",
+ collapseIcon: "column-pre-page-h-font"
+ },
+
+ _defaultConfig: function() {
+ return BI.extend(BI.ScrollView.superclass._defaultConfig.apply(this, arguments), {
+ baseCls:"bi-scroll-view",
+ scrollHeight: 50,
+ maxHeight: 300
+ })
+ },
+
+ _init : function() {
+ BI.ScrollView.superclass._init.apply(this, arguments);
+
+ this.scrollUp = false;
+ this.scroll = BI.createWidget({
+ type: "bi.vertical",
+ cls: "scroll-container",
+ scrolly: true
+ })
+ BI.createWidget({
+ type: "bi.vertical",
+ element: this,
+ scrolly: false,
+ items: [this.scroll]
+ })
+
+ this.dropdown = BI.createWidget({
+ type: "bi.icon_button",
+ height: this._const.dropDownHeight,
+ cls: "scroll-drop-down-icon " + this._const.expandIcon,
+ handler: BI.bind(this._dropDownOrUp, this)
+ })
+
+ BI.createWidget({
+ type: "bi.absolute",
+ element: this,
+ items: [{
+ el: this.dropdown,
+ left: 0,
+ right: 0,
+ bottom: -1 * this._const.dropDownHeight
+ }]
+ })
+ this.populate(this.options.items);
+ },
+
+ _dropDownOrUp: function(){
+ if(!this.scrollUp){
+ var height = this.element.height();
+ height += this.options.scrollHeight;
+ height = Math.min(height, this.scroll.element[0].scrollHeight, this.options.maxHeight);
+ this.element.height(height);
+ this._checkDropDownState();
+ } else {
+ var height = this.element.height();
+ height -= this.options.scrollHeight;
+ height = Math.max(height, this.options.height);
+ this.element.height(height);
+ this._checkDropDownState();
+ }
+ },
+
+ _checkDropDownState: function(){
+ var height = this.element.height();
+ if(!this._checkScroll() || height >= this.options.maxHeight){
+ this.scrollUp = true;
+ this.dropdown.element.removeClass(this._const.expandIcon).addClass(this._const.collapseIcon);
+ } else if(height <= this.options.height){
+ this.scrollUp = false;
+ this.dropdown.element.addClass(this._const.expandIcon);
+ } else {
+ this.dropdown.element.addClass(this.scrollUp ? this._const.collapseIcon : this._const.expandIcon);
+ }
+ },
+
+ _checkScroll: function(){
+ this.scroll.element.height(this.element.height());
+ return this.scroll.element[0].scrollHeight > this.scroll.element[0].clientHeight;
+ },
+
+ _checkDropDown: function(){
+ if(this._checkScroll()){
+ this.dropdown.visible();
+ //this.scrollUp = false;
+ this._checkDropDownState();
+ } else {
+ this.dropdown.invisible();
+ }
+ },
+
+ populate: function(){
+ this.scroll.populate.apply(this.scroll, arguments);
+ this.resize();
+ },
+
+ resize: function(){
+ this.element.height(this.options.height);
+ BI.nextTick(BI.bind(this._checkDropDown, this));
+ },
+
+ addItem: function(){
+ this.scroll.addItem.apply(this.scroll, arguments);
+ BI.nextTick(BI.bind(this._checkDropDown, this));
+ }
+});
+
+$.shortcut("bi.scroll_view", BI.ScrollView);/**
+ * 搜索面板
+ *
+ * Created by GUY on 2015/9/28.
+ * @class BI.SearcherView
+ * @extends BI.Pane
+ */
+
+BI.SearcherView = BI.inherit(BI.Pane, {
+ _defaultConfig: function () {
+ var conf = BI.SearcherView.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-searcher-view",
+ tipText: BI.i18nText("BI-No_Select"),
+ chooseType: BI.Selection.Single,
+
+ matcher: {//完全匹配的构造器
+ type: "bi.button_group",
+ behaviors: {
+ redmark: function () {
+ return true;
+ }
+ },
+ items: [],
+ layouts: [{
+ type: "bi.vertical"
+ }]
+ },
+ searcher: {
+ type: "bi.button_group",
+ behaviors: {
+ redmark: function () {
+ return true;
+ }
+ },
+ items: [],
+ layouts: [{
+ type: "bi.vertical"
+ }]
+ }
+ })
+ },
+
+ _init: function () {
+ BI.SearcherView.superclass._init.apply(this, arguments);
+ var self = this, o = this.options;
+
+ this.matcher = BI.createWidget(o.matcher, {
+ type: "bi.button_group",
+ chooseType: o.chooseType,
+ behaviors: {
+ redmark: function () {
+ return true;
+ }
+ },
+ layouts: [{
+ type: "bi.vertical"
+ }]
+ });
+ this.matcher.on(BI.Controller.EVENT_CHANGE, function (type, val, ob) {
+ self.fireEvent(BI.Controller.EVENT_CHANGE, arguments);
+ if (type === BI.Events.CLICK) {
+ self.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob);
+ }
+ });
+ this.spliter = BI.createWidget({
+ type: "bi.vertical",
+ height: 1,
+ hgap: 10,
+ items: [{
+ type: "bi.layout",
+ height: 1,
+ cls: "searcher-view-spliter"
+ }]
+ });
+ this.searcher = BI.createWidget(o.searcher, {
+ type: "bi.button_group",
+ chooseType: o.chooseType,
+ behaviors: {
+ redmark: function () {
+ return true;
+ }
+ },
+ layouts: [{
+ type: "bi.vertical"
+ }]
+ });
+ this.searcher.on(BI.Controller.EVENT_CHANGE, function (type, val, ob) {
+ self.fireEvent(BI.Controller.EVENT_CHANGE, arguments);
+ if (type === BI.Events.CLICK) {
+ self.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob);
+ }
+ });
+
+ BI.createWidget({
+ type: "bi.vertical",
+ element: this,
+ items: [this.matcher, this.spliter, this.searcher]
+ });
+ },
+
+ startSearch: function () {
+
+ },
+
+ stopSearch: function () {
+
+ },
+
+ setValue: function (v) {
+ this.matcher.setValue(v);
+ this.searcher.setValue(v);
+ },
+
+ getValue: function () {
+ return this.matcher.getValue().concat(this.searcher.getValue());
+ },
+
+ populate: function (searchResult, matchResult, keyword) {
+ searchResult || (searchResult = []);
+ matchResult || (matchResult = []);
+ this.setTipVisible(searchResult.length + matchResult.length === 0);
+ this.spliter.setVisible(BI.isNotEmptyArray(matchResult) && BI.isNotEmptyArray(searchResult));
+ this.matcher.populate(matchResult, keyword);
+ this.searcher.populate(searchResult, keyword);
+ },
+
+ empty: function () {
+ this.searcher.empty();
+ this.matcher.empty();
+ },
+
+ hasMatched: function () {
+ return this.matcher.getAllButtons().length > 0;
+ }
+});
+BI.SearcherView.EVENT_CHANGE = "EVENT_CHANGE";
+
+$.shortcut("bi.searcher_view", BI.SearcherView);/**
+ * 分页控件
+ *
+ * Created by GUY on 2015/8/31.
+ * @class BI.Pager
+ * @extends BI.Widget
+ */
+BI.Pager = BI.inherit(BI.Widget, {
+ _defaultConfig: function () {
+ return BI.extend(BI.Pager.superclass._defaultConfig.apply(this, arguments), {
+ baseCls: "bi-pager",
+ behaviors: {},
+ layouts: [{
+ type: "bi.horizontal",
+ hgap: 10,
+ vgap: 0
+ }],
+
+ dynamicShow: true, //是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态
+ //dynamicShow为false时以下两个有用
+ dynamicShowFirstLast: false,//是否动态显示首页、尾页
+ dynamicShowPrevNext: false,//是否动态显示上一页、下一页
+ pages: false, //总页数
+ curr: function () {
+ return 1;
+ }, //初始化当前页
+ groups: 0, //连续显示分页数
+ jump: BI.emptyFn, //分页的回调函数
+
+ first: false, //是否显示首页
+ last: false, //是否显示尾页
+ prev: "上一页",
+ next: "下一页",
+
+ firstPage: 1,
+ lastPage: function () { //在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法
+ return 1;
+ },
+ hasPrev: BI.emptyFn, //pages不可用时有效
+ hasNext: BI.emptyFn //pages不可用时有效
+ })
+ },
+ _init: function () {
+ BI.Pager.superclass._init.apply(this, arguments);
+ var self = this;
+ this.currPage = BI.result(this.options, "curr");
+ //翻页太灵敏
+ this._lock = false;
+ this._debouce = BI.debounce(function () {
+ self._lock = false;
+ }, 300);
+ this._populate();
+ },
+
+ _populate: function () {
+ var self = this, o = this.options, view = [], dict = {};
+ this.empty();
+ var pages = BI.result(o, "pages");
+ var curr = BI.result(this, "currPage");
+ var groups = BI.result(o, "groups");
+ var first = BI.result(o, "first");
+ var last = BI.result(o, "last");
+ var prev = BI.result(o, "prev");
+ var next = BI.result(o, "next");
+
+ if (pages === false) {
+ groups = 0;
+ first = false;
+ last = false;
+ } else {
+ groups > pages && (groups = pages);
+ }
+
+ //计算当前组
+ dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups));
+
+ //当前页非首页,则输出上一页
+ if (((!o.dynamicShow && !o.dynamicShowPrevNext) || curr > 1) && prev !== false) {
+ if (BI.isKey(prev)) {
+ view.push({
+ text: prev,
+ value: "prev",
+ disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false)
+ })
+ } else {
+ view.push(BI.extend({
+ disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false)
+ }, prev));
+ }
+ }
+
+ //当前组非首组,则输出首页
+ if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) {
+ view.push({
+ text: first,
+ value: "first",
+ disabled: !(dict.index > 1 && groups !== 0)
+ });
+ if (dict.index > 1 && groups !== 0) {
+ view.push({
+ type: "bi.label",
+ cls: "page-ellipsis",
+ text: "\u2026"
+ });
+ }
+ }
+
+ //输出当前页组
+ dict.poor = Math.floor((groups - 1) / 2);
+ dict.start = dict.index > 1 ? curr - dict.poor : 1;
+ dict.end = dict.index > 1 ? (function () {
+ var max = curr + (groups - dict.poor - 1);
+ return max > pages ? pages : max;
+ }()) : groups;
+ if (dict.end - dict.start < groups - 1) { //最后一组状态
+ dict.start = dict.end - groups + 1;
+ }
+ var s = dict.start, e = dict.end;
+ if (first && last && (dict.index > 1 && groups !== 0) && (pages > groups && dict.end < pages && groups !== 0)) {
+ s++;
+ e--;
+ }
+ for (; s <= e; s++) {
+ if (s === curr) {
+ view.push({
+ text: s,
+ value: s,
+ selected: true
+ })
+ } else {
+ view.push({
+ text: s,
+ value: s
+ })
+ }
+ }
+
+ //总页数大于连续分页数,且当前组最大页小于总页,输出尾页
+ if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) {
+ if (pages > groups && dict.end < pages && groups !== 0) {
+ view.push({
+ type: "bi.label",
+ cls: "page-ellipsis",
+ text: "\u2026"
+ });
+ }
+ view.push({
+ text: last,
+ value: "last",
+ disabled: !(pages > groups && dict.end < pages && groups !== 0)
+ })
+ }
+
+ //当前页不为尾页时,输出下一页
+ dict.flow = !prev && groups === 0;
+ if (((!o.dynamicShow && !o.dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) {
+ view.push((function () {
+ if (BI.isKey(next)) {
+ if (pages === false) {
+ return {text: next, value: "next", disabled: o.hasNext(curr) === false}
+ }
+ return (dict.flow && curr === pages)
+ ?
+ {text: next, value: "next", disabled: true}
+ :
+ {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)};
+ } else {
+ return BI.extend({
+ disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow)
+ }, next);
+ }
+ }()));
+ }
+
+ this.button_group = BI.createWidget({
+ type: "bi.button_group",
+ element: this,
+ items: BI.createItems(view, {
+ cls: "page-item",
+ height: 23,
+ hgap: 10
+ }),
+ behaviors: o.behaviors,
+ layouts: o.layouts
+ });
+ this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) {
+ if (self._lock === true) {
+ return;
+ }
+ self._lock = true;
+ self._debouce();
+ if (type === BI.Events.CLICK) {
+ var v = self.button_group.getValue()[0];
+ switch (v) {
+ case "first":
+ self.currPage = 1;
break;
- case bottomright:
- colgroupTds = self.bottomRightColGroupTds;
- bodyTds = self.bottomRightBodyTds;
- bodyItems = self.bottomRightBodyItems;
- sizes = columnRight;
+ case "last":
+ self.currPage = pages;
+ break;
+ case "prev":
+ self.currPage--;
+ break;
+ case "next":
+ self.currPage++;
+ break;
+ default:
+ self.currPage = v;
+ break;
+ }
+ o.jump.apply(self, [{
+ pages: pages,
+ curr: self.currPage
+ }]);
+ self._populate();
+ self.fireEvent(BI.Pager.EVENT_CHANGE, obj);
+ }
+ self.fireEvent(BI.Controller.EVENT_CHANGE, arguments);
+ });
+ this.fireEvent(BI.Pager.EVENT_AFTER_POPULATE);
+ },
+
+ getCurrentPage: function () {
+ return this.currPage;
+ },
+
+ setAllPages: function (pages) {
+ this.options.pages = pages;
+ },
+
+ hasPrev: function (v) {
+ v || (v = 1);
+ var o = this.options;
+ var pages = this.options.pages;
+ return pages === false ? o.hasPrev(v) : v > 1;
+ },
+
+ hasNext: function (v) {
+ v || (v = 1);
+ var o = this.options;
+ var pages = this.options.pages;
+ return pages === false ? o.hasNext(v) : v < pages;
+ },
+
+ setValue: function (v) {
+ var o = this.options;
+ v = v | 0;
+ v = v < 1 ? 1 : v;
+ if (o.pages === false) {
+ var lastPage = BI.result(o, "lastPage"), firstPage = 1;
+ this.currPage = v > lastPage ? lastPage : ((firstPage = BI.result(o, "firstPage")), (v < firstPage ? firstPage : v));
+ } else {
+ v = v > o.pages ? o.pages : v;
+ this.currPage = v;
+ }
+ this._populate();
+ },
+
+ getValue: function () {
+ var val = this.button_group.getValue()[0];
+ switch (val) {
+ case "prev":
+ return -1;
+ case "next":
+ return 1;
+ case "first":
+ return BI.MIN;
+ case "last":
+ return BI.MAX;
+ default :
+ return val;
+ }
+ },
+
+ attr: function (key, value) {
+ BI.Pager.superclass.attr.apply(this, arguments);
+ if (key === "curr") {
+ this.currPage = BI.result(this.options, "curr");
+ }
+ },
+
+ populate: function () {
+ this._populate();
+ }
+});
+BI.Pager.EVENT_CHANGE = "EVENT_CHANGE";
+BI.Pager.EVENT_AFTER_POPULATE = "EVENT_AFTER_POPULATE";
+$.shortcut("bi.pager", BI.Pager);/**
+ * Created by Young's on 2016/8/17.
+ * 加载面板,一般只用于 requestAsync 中
+ */
+BI.RequstLoading = BI.inherit(BI.Widget, {
+ _defaultConfig: function () {
+ return BI.extend(BI.RequstLoading.superclass._defaultConfig.apply(this, arguments), {});
+ },
+
+ _init: function () {
+ BI.RequstLoading.superclass._init.apply(this, arguments);
+ var self = this, o = this.options;
+ var mask = BI.Maskers.create(BI.RequstLoading.MASK_ID);
+ this.callback = o.callback;
+ this.paneTab = BI.createWidget({
+ type: "bi.tab",
+ cardCreator: BI.bind(this._cardCreator, this),
+ defaultShowIndex: BI.RequstLoading.ERROR,
+ width: 400,
+ height: 300
+ });
+ var tempIcon = BI.createWidget({
+ type: "bi.icon_button",
+ cls: "data-link-test-fail-icon",
+ width: 0,
+ height: 0
+ });
+ BI.createWidget({
+ type: "bi.absolute",
+ element: $('body'),
+ items: [{
+ el: tempIcon,
+ bottom: 0
+ }]
+ });
+
+ BI.createWidget({
+ type: "bi.absolute",
+ element: mask,
+ cls: "bi-request-loading",
+ items: [{
+ el: {
+ type: "bi.layout",
+ cls: "mask-pane"
+ },
+ top: 0,
+ left: 0,
+ bottom: 0,
+ right: 0
+ }, {
+ el: {
+ type: "bi.center_adapt",
+ items: [this.paneTab]
+ },
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0
+ }]
+ });
+ },
+
+ _cardCreator: function (v) {
+ var self = this;
+ var cancel = BI.createWidget({
+ type: "bi.button",
+ text: BI.i18nText("BI-Basic_Cancel"),
+ title: BI.i18nText("BI-Basic_Cancel"),
+ level: "ignore",
+ height: 28,
+ width: 90,
+ handler: function () {
+ BI.Maskers.hide(BI.RequstLoading.MASK_ID);
+ }
+ });
+ var retry = BI.createWidget({
+ type: "bi.button",
+ text: BI.i18nText("BI-Basic_Retry"),
+ title: BI.i18nText("BI-Basic_Retry"),
+ level: "common",
+ height: 28,
+ width: 90,
+ handler: function () {
+ self.paneTab.setSelect(BI.RequstLoading.LOADING);
+ self.callback();
+ }
+ });
+ switch (v) {
+ case BI.RequstLoading.LOADING:
+ return BI.createWidget({
+ type: "bi.vertical",
+ items: [{
+ type: "bi.center_adapt",
+ cls: "loading-bar-icon",
+ items: [{
+ type: "bi.icon",
+ width: 208,
+ height: 15
+ }]
+ }, {
+ type: "bi.label",
+ cls: "loading-comment",
+ text: BI.i18nText("BI-Basic_Loading"),
+ height: 30
+ }],
+ width: 208,
+ height: 200,
+ vgap: 10
+ });
+ case BI.RequstLoading.LOADING_TIMEOUT:
+ return BI.createWidget({
+ type: "bi.vertical",
+ items: [{
+ type: "bi.center_adapt",
+ cls: "loading-bar-icon",
+ items: [{
+ type: "bi.icon",
+ width: 208,
+ height: 15
+ }]
+ }, {
+ type: "bi.label",
+ cls: "loading-comment",
+ text: BI.i18nText("BI-Basic_Loading"),
+ height: 30
+ }, {
+ type: "bi.label",
+ text: BI.i18nText("BI-Request_Time_Out_Toast_Tip"),
+ cls: "load-timeout-warning"
+ }, {
+ type: "bi.left_right_vertical_adapt",
+ items: {
+ left: [cancel],
+ right: [retry]
+ },
+ height: 30,
+ llgap: 100,
+ rrgap: 100
+ }],
+ vgap: 10
+ });
+ case BI.RequstLoading.ERROR:
+ return BI.createWidget({
+ type: "bi.vertical",
+ items: [{
+ type: "bi.center_adapt",
+ cls: "data-link-test-fail-icon",
+ items: [{
+ type: "bi.icon",
+ width: 126,
+ height: 126
+ }]
+ }, {
+ type: "bi.label",
+ text: BI.i18nText("BI-Connection_Lost"),
+ cls: "load-fail-comment"
+ }, {
+ type: "bi.left_right_vertical_adapt",
+ items: {
+ left: [cancel],
+ right: [retry]
+ },
+ height: 30,
+ llgap: 100,
+ rrgap: 100
+ }],
+ vgap: 20
+ });
+ }
+ },
+
+ showLoading: function () {
+ BI.Maskers.show(BI.RequstLoading.MASK_ID);
+ this.paneTab.setSelect(BI.RequstLoading.LOADING);
+ },
+
+ showError: function () {
+ BI.Maskers.show(BI.RequstLoading.MASK_ID);
+ this.paneTab.setSelect(BI.RequstLoading.ERROR);
+ },
+
+ setCallback: function (callback) {
+ this.callback = callback;
+ }
+});
+BI.extend(BI.RequstLoading, {
+ MASK_ID: "___request__loading___",
+ LOADING: 1,
+ LOADING_TIMEOUT: 2,
+ ERROR: 3
+});
+$.shortcut("bi.request_loading", BI.RequstLoading);/**
+ * 超链接
+ *
+ * Created by GUY on 2015/9/9.
+ * @class BI.A
+ * @extends BI.Text
+ * @abstract
+ */
+BI.A = BI.inherit(BI.Text, {
+ _defaultConfig: function () {
+ var conf = BI.A.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-a display-block",
+ href: "",
+ target: "_blank",
+ el: null,
+ element: " "
+ })
+ },
+ _init: function () {
+ var o = this.options;
+ BI.A.superclass._init.apply(this, arguments);
+ this.element.attr({href: o.href, target: o.target});
+ if (o.el) {
+ BI.createWidget(o.el, {
+ element: this
+ });
+ }
+ }
+});
+
+$.shortcut("bi.a", BI.A);/**
+ * guy
+ * 加载条
+ * @type {*|void|Object}
+ */
+BI.LoadingBar = BI.inherit(BI.Single, {
+ consts: {
+ loadedText: BI.i18nText("BI-Load_More"),
+ endText: BI.i18nText("BI-No_More_Data")
+ },
+ _defaultConfig: function() {
+ var conf = BI.LoadingBar.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend( conf, {
+ baseCls : (conf.baseCls ||"")+' bi-loading-bar',
+ height: 30,
+ handler: BI.emptyFn
+ })
+ },
+ _init : function() {
+ BI.LoadingBar.superclass._init.apply(this, arguments);
+ var self = this;
+ this.loaded = BI.createWidget({
+ type: "bi.text_button",
+ cls: "loading-text",
+ text: this.consts.loadedText,
+ width: 120,
+ handler: this.options.handler
+ })
+ this.loaded.on(BI.Controller.EVENT_CHANGE, function(type){
+ self.fireEvent(BI.Controller.EVENT_CHANGE, arguments);
+ })
+
+ this.loading = BI.createWidget({
+ type: "bi.layout",
+ height:this.options.height,
+ cls: "loading-background cursor-default"
+ })
+ var loaded = BI.createWidget({
+ type: "bi.center_adapt",
+ items: [this.loaded]
+ })
+ var loading = BI.createWidget({
+ type: "bi.center_adapt",
+ items: [this.loading]
+ })
+ this.cardLayout = BI.createWidget({
+ type: "bi.card",
+ element: this,
+ items: [{
+ el: loaded,
+ cardName: "loaded"
+ }, {
+ el: loading,
+ cardName: "loading"
+ }]
+ })
+ this.invisible();
+ },
+
+ _reset: function(){
+ this.visible();
+ this.loaded.setText(this.consts.loadedText);
+ this.loaded.enable();
+ },
+
+ setLoaded: function(){
+ this._reset();
+ this.cardLayout.showCardByName("loaded");
+ },
+
+ setEnd: function(){
+ this.setLoaded();
+ this.loaded.setText(this.consts.endText);
+ this.loaded.disable();
+ },
+
+ setLoading: function(){
+ this._reset();
+ this.cardLayout.showCardByName("loading");
+ }
+});
+
+$.shortcut("bi.loading_bar", BI.LoadingBar);/**
+ * @class BI.IconButton
+ * @extends BI.BasicButton
+ * 图标的button
+ */
+BI.IconButton = BI.inherit(BI.BasicButton, {
+ _defaultConfig: function () {
+ var conf = BI.IconButton.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-icon-button horizon-center",
+ iconWidth: null,
+ iconHeight: null
+ })
+ },
+
+ _init: function () {
+ BI.IconButton.superclass._init.apply(this, arguments);
+ var o = this.options;
+ this.element.css({
+ textAlign: 'center'
+ });
+ this.icon = BI.createWidget({
+ type: 'bi.icon',
+ width: o.iconWidth,
+ height: o.iconHeight
+ });
+ if (BI.isNumber(o.height) && o.height > 0 && BI.isNull(o.iconWidth) && BI.isNull(o.iconHeight)) {
+ this.element.css("lineHeight", o.height + "px");
+ BI.createWidget({
+ type: "bi.default",
+ element: this,
+ items: [this.icon]
+ })
+ } else {
+ BI.createWidget({
+ element: this,
+ type: 'bi.center_adapt',
+ items: [this.icon]
+ });
+ }
+ },
+
+ doClick: function () {
+ BI.IconButton.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.IconButton.EVENT_CHANGE, this);
+ }
+ }
+});
+BI.IconButton.EVENT_CHANGE = "IconButton.EVENT_CHANGE";
+$.shortcut("bi.icon_button", BI.IconButton);/**
+ * 图片的button
+ *
+ * Created by GUY on 2016/1/27.
+ * @class BI.ImageButton
+ * @extends BI.BasicButton
+ */
+BI.ImageButton = BI.inherit(BI.BasicButton, {
+ _defaultConfig: function () {
+ var conf = BI.ImageButton.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-image-button",
+ src: "",
+ iconWidth: "100%",
+ iconHeight: "100%"
+ })
+ },
+
+ _init: function () {
+ BI.ImageButton.superclass._init.apply(this, arguments);
+ var o = this.options;
+ this.image = BI.createWidget({
+ type: "bi.img",
+ width: o.iconWidth,
+ height: o.iconHeight,
+ src: o.src
+ });
+ if (BI.isNumber(o.iconWidth) || BI.isNumber(o.iconHeight)) {
+ BI.createWidget({
+ type: "bi.center_adapt",
+ element: this,
+ items: [this.image]
+ })
+ } else {
+ BI.createWidget({
+ type: "bi.adaptive",
+ element: this,
+ items: [this.image],
+ scrollable: false
+ })
+ }
+ },
+
+ setWidth: function (w) {
+ BI.ImageButton.superclass.setWidth.apply(this, arguments);
+ this.options.width = w;
+ },
+
+ setHeight: function (h) {
+ BI.ImageButton.superclass.setHeight.apply(this, arguments);
+ this.options.height = h;
+ },
+
+ setImageWidth: function (w) {
+ this.image.setWidth(w);
+ },
+
+ setImageHeight: function (h) {
+ this.image.setHeight(h);
+ },
+
+ getImageWidth: function () {
+ return this.image.element.width();
+ },
+
+ getImageHeight: function () {
+ return this.image.element.height();
+ },
+
+ setSrc: function (src) {
+ this.options.src = src;
+ this.image.setSrc(src);
+ },
+
+ getSrc: function () {
+ return this.image.getSrc();
+ },
+
+ doClick: function () {
+ BI.ImageButton.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.ImageButton.EVENT_CHANGE, this);
+ }
+ }
+});
+BI.ImageButton.EVENT_CHANGE = "ImageButton.EVENT_CHANGE";
+$.shortcut("bi.image_button", BI.ImageButton);(function ($) {
+
+ /**
+ * 文字类型的按钮
+ * @class BI.Button
+ * @extends BI.BasicButton
+ *
+ * @cfg {JSON} options 配置属性
+ * @cfg {'common'/'success'/'warning'/'ignore'} [options.level='common'] 按钮类型,用不同颜色强调不同的场景
+ */
+ BI.Button = BI.inherit(BI.BasicButton, {
+ _const: {
+ minWidth: 90
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.Button.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + ' bi-button',
+ shadow: true,
+ isShadowShowingOnSelected: true,
+ readonly: true,
+ iconClass: "",
+ level: 'common',
+ textAlign: "center",
+ whiteSpace: "nowrap",
+ forceCenter: false,
+ textWidth: null,
+ textHeight: null,
+ hgap: 10,
+ vgap: 0,
+ tgap: 0,
+ bgap: 0,
+ lgap: 0,
+ rgap: 0
+ })
+ },
+
+ _init: function () {
+ BI.Button.superclass._init.apply(this, arguments);
+ var o = this.options, self = this;
+ if (BI.isNumber(o.height)) {
+ this.element.css({height: o.height - 2, lineHeight: (o.height - 2) + 'px'});
+ }
+ if (BI.isKey(o.iconClass)) {
+ this.icon = BI.createWidget({
+ type: "bi.icon",
+ width: 18
+ });
+ this.text = BI.createWidget({
+ type: "bi.label",
+ text: o.text,
+ value: o.value
+ });
+ BI.createWidget({
+ type: "bi.horizontal_auto",
+ cls: "button-" + o.level + " " + o.iconClass,
+ element: this,
+ hgap: o.hgap,
+ vgap: o.vgap,
+ tgap: o.tgap,
+ bgap: o.bgap,
+ lgap: o.lgap,
+ rgap: o.rgap,
+ items: [{
+ type: "bi.horizontal",
+ items: [this.icon, this.text]
+ }]
+ })
+ } else {
+ this.text = BI.createWidget({
+ type: "bi.label",
+ cls: "button-" + o.level,
+ textAlign: o.textAlign,
+ whiteSpace: o.whiteSpace,
+ forceCenter: o.forceCenter,
+ textWidth: o.textWidth,
+ textHeight: o.textHeight,
+ hgap: o.hgap,
+ vgap: o.vgap,
+ tgap: o.tgap,
+ bgap: o.bgap,
+ lgap: o.lgap,
+ rgap: o.rgap,
+ element: this,
+ text: o.text,
+ value: o.value
+ });
+ }
+ this.element.css({"min-width": this._const.minWidth - 2 + "px"});
+ },
+
+ doClick: function () {
+ BI.Button.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.Button.EVENT_CHANGE, this);
+ }
+ },
+
+ setText: function (text) {
+ BI.Button.superclass.setText.apply(this, arguments);
+ this.text.setText(text);
+ },
+
+ setValue: function (text) {
+ BI.Button.superclass.setValue.apply(this, arguments);
+ if (!this.isReadOnly()) {
+ this.text.setValue(text);
+ }
+ },
+
+ setEnable: function (b) {
+ BI.Button.superclass.setEnable.apply(this, arguments);
+ this.text.setEnable(b);
+ this.icon && this.icon.setEnable(b);
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ doHighLight: function () {
+ this.text.doHighLight.apply(this.text, arguments);
+ },
+
+ unHighLight: function () {
+ this.text.unHighLight.apply(this.text, arguments);
+ },
+
+ destroy: function () {
+ BI.Button.superclass.destroy.apply(this, arguments);
+ }
+ });
+ $.shortcut('bi.button', BI.Button);
+ BI.Button.EVENT_CHANGE = "EVENT_CHANGE";
+})(jQuery);/**
+ * guy
+ * 可以点击的一行文字
+ * @class BI.TextButton
+ * @extends BI.BasicButton
+ * 文字button
+ */
+BI.TextButton = BI.inherit(BI.BasicButton, {
+ _defaultConfig: function () {
+ var conf = BI.TextButton.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-text-button",
+ textAlign: "center",
+ whiteSpace: "nowrap",
+ forceCenter: false,
+ textWidth: null,
+ textHeight: null,
+ hgap: 0,
+ lgap: 0,
+ rgap: 0,
+ text: "",
+ py: ""
+ })
+ },
+
+ _init: function () {
+ BI.TextButton.superclass._init.apply(this, arguments);
+ var o = this.options;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ element: this,
+ textAlign: o.textAlign,
+ whiteSpace: o.whiteSpace,
+ textWidth: o.textWidth,
+ textHeight: o.textHeight,
+ forceCenter: o.forceCenter,
+ width: o.width,
+ height: o.height,
+ hgap: o.hgap,
+ lgap: o.lgap,
+ rgap: o.rgap,
+ text: o.text,
+ value: o.value,
+ py: o.py
+ });
+ },
+
+ doClick: function () {
+ BI.TextButton.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.TextButton.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ doHighLight: function () {
+ this.text.doHighLight.apply(this.text, arguments);
+ },
+
+ unHighLight: function () {
+ this.text.unHighLight.apply(this.text, arguments);
+ },
+
+ setText: function (text) {
+ BI.TextButton.superclass.setText.apply(this, arguments);
+ text = BI.isArray(text) ? text.join(",") : text;
+ this.text.setText(text);
+ },
+
+ setStyle: function (style) {
+ this.text.setStyle(style);
+ },
+
+ setValue: function (text) {
+ BI.TextButton.superclass.setValue.apply(this, arguments);
+ if (!this.isReadOnly()) {
+ text = BI.isArray(text) ? text.join(",") : text;
+ this.text.setValue(text);
+ }
+ }
+});
+BI.TextButton.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.text_button", BI.TextButton);/**
+ * 带有一个占位
+ *
+ * Created by GUY on 2015/9/11.
+ * @class BI.BlankIconIconTextItem
+ * @extends BI.BasicButton
+ */
+BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, {
+ _const: {
+ commonWidth: 25
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.BlankIconIconTextItem.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-blank-icon-text-item",
+ logic: {
+ dynamic: false
+ },
+ iconCls1: "close-ha-font",
+ iconCls2: "close-ha-font",
+ blankWidth: 0,
+ iconHeight: null,
+ iconWidth: null,
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.BlankIconIconTextItem.superclass._init.apply(this, arguments);
+ var o = this.options, c = this._const;
+ var blank = BI.createWidget({
+ type: "bi.layout",
+ width: o.blankWidth
+ })
+ this.text = BI.createWidget({
+ type: "bi.label",
+ cls: "list-item-text",
+ textAlign: "left",
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ height: o.height
+ });
+ this.icon1 = BI.createWidget({
+ type: "bi.icon_button",
+ cls: o.iconCls1,
+ forceNotSelected: true,
+ width: c.commonWidth
+ });
+ this.icon2 = BI.createWidget({
+ type: "bi.icon_button",
+ cls: o.iconCls2,
+ forceNotSelected: true,
+ width: c.commonWidth
+ });
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection("left", blank, this.icon1, this.icon2, this.text)
+ }))));
+ },
+
+ doClick: function () {
+ BI.BlankIconIconTextItem.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.BlankIconIconTextItem.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ setSelected: function (b) {
+ BI.BlankIconIconTextItem.superclass.setSelected.apply(this, arguments);
+ this.icon1.setSelected(b);
+ this.icon2.setSelected(b);
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ doHighLight: function () {
+ this.text.doHighLight.apply(this.text, arguments);
+ },
+
+ unHighLight: function () {
+ this.text.unHighLight.apply(this.text, arguments);
+ }
+});
+BI.BlankIconIconTextItem.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.blank_icon_icon_text_item", BI.BlankIconIconTextItem);/**
+ * guy
+ * 一个占位符和两个icon和一行数 组成的一行listitem
+ *
+ * Created by GUY on 2015/9/15.
+ * @class BI.BlankIconTextIconItem
+ * @extends BI.BasicButton
+ */
+BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, {
+ _const: {
+ commonWidth: 25
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.BlankIconTextIconItem.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-blank-icon-text-icon-item",
+ logic: {
+ dynamic: false
+ },
+ iconCls1: "close-ha-font",
+ iconCls2: "close-ha-font",
+ blankWidth: 0,
+ iconHeight: null,
+ iconWidth: null,
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.BlankIconTextIconItem.superclass._init.apply(this, arguments);
+ var o = this.options, c = this._const;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ textAlign: "left",
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ height: o.height
+ })
+
+ var icon1 = BI.createWidget({
+ type: "bi.center_adapt",
+ cls: o.iconCls1,
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ })
+ BI.createWidget({
+ type: "bi.absolute",
+ element: this,
+ items: [{
+ el: {
+ type: "bi.center_adapt",
+ cls: o.iconCls2,
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ },
+ top: 0,
+ bottom: 0,
+ right: 0
+ }]
+ })
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection("left", {
+ type: "bi.layout",
+ width: o.blankWidth
+ }, icon1, this.text, {
+ type: "bi.layout",
+ width: c.commonWidth
+ })
+ }))));
+ },
+
+ doClick: function () {
+ BI.BlankIconTextIconItem.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.BlankIconTextIconItem.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ doHighLight: function () {
+ this.text.doHighLight.apply(this.text, arguments);
+ },
+
+ unHighLight: function () {
+ this.text.unHighLight.apply(this.text, arguments);
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ }
+});
+BI.BlankIconTextIconItem.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.blank_icon_text_icon_item", BI.BlankIconTextIconItem);/**
+ * 带有一个占位
+ *
+ * Created by GUY on 2015/9/11.
+ * @class BI.BlankIconTextItem
+ * @extends BI.BasicButton
+ */
+BI.BlankIconTextItem = BI.inherit(BI.BasicButton, {
+ _const: {
+ commonWidth: 25
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.BlankIconTextItem.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-blank-icon-text-item",
+ logic: {
+ dynamic: false
+ },
+ cls: "close-ha-font",
+ blankWidth: 0,
+ iconHeight: null,
+ iconWidth: null,
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.BlankIconTextItem.superclass._init.apply(this, arguments);
+ var o = this.options, c = this._const;
+ var blank = BI.createWidget({
+ type: "bi.layout",
+ width: o.blankWidth
+ })
+ this.text = BI.createWidget({
+ type: "bi.label",
+ cls: "list-item-text",
+ textAlign: "left",
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ height: o.height
+ })
+ this.icon = BI.createWidget({
+ type: "bi.center_adapt",
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ });
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection("left", blank, this.icon, this.text)
+ }))));
+ },
+
+ doClick: function () {
+ BI.BlankIconTextItem.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.BlankIconTextItem.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ doHighLight: function () {
+ this.text.doHighLight.apply(this.text, arguments);
+ },
+
+ unHighLight: function () {
+ this.text.unHighLight.apply(this.text, arguments);
+ }
+});
+BI.BlankIconTextItem.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.blank_icon_text_item", BI.BlankIconTextItem);/**
+ * guy
+ * 两个icon和一行数 组成的一行listitem
+ *
+ * Created by GUY on 2015/9/9.
+ * @class BI.IconTextIconItem
+ * @extends BI.BasicButton
+ */
+BI.IconTextIconItem = BI.inherit(BI.BasicButton, {
+ _const: {
+ commonWidth: 25
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.IconTextIconItem.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-icon-text-icon-item",
+ logic: {
+ dynamic: false
+ },
+ iconCls1: "close-ha-font",
+ iconCls2: "close-ha-font",
+ iconHeight: null,
+ iconWidth: null,
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.IconTextIconItem.superclass._init.apply(this, arguments);
+ var o = this.options, c = this._const;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ textAlign: "left",
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ height: o.height
+ })
+
+ var icon1 = BI.createWidget({
+ type: "bi.center_adapt",
+ cls: o.iconCls1,
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ })
+ var blank = BI.createWidget({
+ type: "bi.layout",
+ width: c.commonWidth
+ })
+ BI.createWidget({
+ type: "bi.absolute",
+ element: this,
+ items: [{
+ el: {
+ type: "bi.center_adapt",
+ cls: o.iconCls2,
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ },
+ top: 0,
+ bottom: 0,
+ right: 0
+ }]
+ })
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection("left", icon1, this.text, blank)
+ }))));
+ },
+
+ doClick: function () {
+ BI.IconTextIconItem.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.IconTextIconItem.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ doHighLight: function () {
+ this.text.doHighLight.apply(this.text, arguments);
+ },
+
+ unHighLight: function () {
+ this.text.unHighLight.apply(this.text, arguments);
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ }
+});
+BI.IconTextIconItem.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.icon_text_icon_item", BI.IconTextIconItem);/**
+ * guy
+ *
+ * Created by GUY on 2015/9/9.
+ * @class BI.IconTextItem
+ * @extends BI.BasicButton
+ */
+BI.IconTextItem = BI.inherit(BI.BasicButton, {
+ _const: {
+ commonWidth: 25
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.IconTextItem.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-icon-text-item",
+ direction: BI.Direction.Left,
+ logic: {
+ dynamic: false
+ },
+ iconHeight: null,
+ iconWidth: null,
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.IconTextItem.superclass._init.apply(this, arguments);
+ var o = this.options, c = this._const;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ cls: "list-item-text",
+ textAlign: "left",
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ height: o.height
+ });
+ this.icon = BI.createWidget({
+ type: "bi.center_adapt",
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ });
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend(o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.icon, this.text)
+ }))));
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ },
+
+ doClick: function () {
+ BI.IconTextItem.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.IconTextItem.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ doHighLight: function () {
+ this.text.doHighLight.apply(this.text, arguments);
+ },
+
+ unHighLight: function () {
+ this.text.unHighLight.apply(this.text, arguments);
+ }
+});
+BI.IconTextItem.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.icon_text_item", BI.IconTextItem);/**
+ *
+ * 图标的button
+ *
+ * Created by GUY on 2015/9/9.
+ * @class BI.TextIconItem
+ * @extends BI.BasicButton
+ */
+BI.TextIconItem = BI.inherit(BI.BasicButton, {
+ _const: {
+ commonWidth: 25
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.TextIconItem.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-text-icon-item",
+ logic: {
+ dynamic: false
+ },
+ cls: "close-ha-font",
+ iconHeight: null,
+ iconWidth: null,
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.TextIconItem.superclass._init.apply(this, arguments);
+ var o = this.options, c = this._const;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ cls: "list-item-text",
+ textAlign: "left",
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ height: o.height
+ });
+ this.icon = BI.createWidget({
+ type: "bi.center_adapt",
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ });
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection("left", this.text, this.icon)
+ }))));
+ },
+
+ doClick: function () {
+ BI.TextIconItem.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.TextIconItem.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ doHighLight: function () {
+ this.text.doHighLight.apply(this.text, arguments);
+ },
+
+ unHighLight: function () {
+ this.text.unHighLight.apply(this.text, arguments);
+ }
+});
+BI.TextIconItem.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.text_icon_item", BI.TextIconItem);/**
+ * guy
+ * 一个button和一行数 组成的一行listitem
+ *
+ * Created by GUY on 2015/9/9.
+ * @class BI.TextItem
+ * @extends BI.BasicButton
+ */
+BI.TextItem = BI.inherit(BI.BasicButton, {
+
+ _defaultConfig: function () {
+ var conf = BI.TextItem.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-text-item",
+ textAlign: "left",
+ whiteSpace: "nowrap",
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.TextItem.superclass._init.apply(this, arguments);
+ var o = this.options;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ element: this,
+ textAlign: o.textAlign,
+ whiteSpace: o.whiteSpace,
+ textHeight: o.whiteSpace == "nowrap" ? o.height : o.textHeight,
+ height: o.height,
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ py: o.py
+ });
+ },
+
+ doClick: function () {
+ BI.TextItem.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.TextItem.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ doHighLight: function () {
+ this.text.doHighLight.apply(this.text, arguments);
+ },
+
+ unHighLight: function () {
+ this.text.unHighLight.apply(this.text, arguments);
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ }
+});
+BI.TextItem.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.text_item", BI.TextItem);/**
+ * guy
+ * Created by GUY on 2015/9/9.
+ * @class BI.IconTextIconNode
+ * @extends BI.NodeButton
+ */
+BI.IconTextIconNode = BI.inherit(BI.NodeButton, {
+ _const: {
+ commonWidth: 25
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.IconTextIconNode.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-icon-text-icon-node",
+ logic: {
+ dynamic: false
+ },
+ iconCls1: "close-ha-font",
+ iconCls2: "close-ha-font",
+ iconHeight: null,
+ iconWidth: null,
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.IconTextIconNode.superclass._init.apply(this, arguments);
+ var o = this.options, c = this._const;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ textAlign: "left",
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ height: o.height
+ })
+
+ var icon1 = BI.createWidget({
+ type: "bi.center_adapt",
+ cls: o.iconCls1,
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ })
+ var blank = BI.createWidget({
+ type: "bi.layout",
+ width: c.commonWidth
+ })
+ BI.createWidget({
+ type: "bi.absolute",
+ element: this,
+ items: [{
+ el: {
+ type: "bi.center_adapt",
+ cls: o.iconCls2,
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ },
+ top: 0,
+ bottom: 0,
+ right: 0
+ }]
+ })
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection("left", icon1, this.text, blank)
+ }))));
+ },
+
+ doClick: function () {
+ BI.IconTextIconNode.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.IconTextIconNode.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ }
+});
+BI.IconTextIconNode.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.icon_text_icon_node", BI.IconTextIconNode);/**
+ * guy
+ * Created by GUY on 2015/9/9.
+ * @class BI.IconTextNode
+ * @extends BI.NodeButton
+ */
+BI.IconTextNode = BI.inherit(BI.NodeButton, {
+ _const: {
+ commonWidth: 25
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.IconTextNode.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-icon-text-node",
+ logic: {
+ dynamic: false
+ },
+ cls: "close-ha-font",
+ iconHeight: null,
+ iconWidth: null,
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.IconTextNode.superclass._init.apply(this, arguments);
+ var o = this.options, c = this._const;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ cls: "list-item-text",
+ textAlign: "left",
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ height: o.height
+ })
+ this.icon = BI.createWidget({
+ type: "bi.center_adapt",
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ })
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection("left", this.icon, this.text)
+ }))));
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ },
+
+ doClick: function () {
+ BI.IconTextNode.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.IconTextNode.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ }
+});
+BI.IconTextNode.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.icon_text_node", BI.IconTextNode);/**
+ * Created by GUY on 2015/9/9.
+ * @class BI.TextIconNode
+ * @extends BI.NodeButton
+ */
+BI.TextIconNode = BI.inherit(BI.NodeButton, {
+ _const: {
+ commonWidth: 25
+ },
+
+ _defaultConfig: function () {
+ var conf = BI.TextIconNode.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-text-icon-node",
+ logic: {
+ dynamic: false
+ },
+ cls: "close-ha-font",
+ iconHeight: null,
+ iconWidth: null,
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.TextIconNode.superclass._init.apply(this, arguments);
+ var o = this.options, c = this._const;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ cls: "list-item-text",
+ textAlign: "left",
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ height: o.height
+ })
+ this.icon = BI.createWidget({
+ type: "bi.center_adapt",
+ width: c.commonWidth,
+ items: [{
+ el: {
+ type: "bi.icon",
+ width: o.iconWidth,
+ height: o.iconHeight
+ }
+ }]
+ });
+
+ BI.createWidget(BI.extend({
+ element: this
+ }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, {
+ items: BI.LogicFactory.createLogicItemsByDirection("left", this.text, this.icon)
+ }))));
+ },
+
+ doClick: function () {
+ BI.TextIconNode.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.TextIconNode.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ }
+});
+BI.TextIconNode.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.text_icon_node", BI.TextIconNode);/**
+ * guy
+ *
+ * Created by GUY on 2015/9/9.
+ * @class BI.TextNode
+ * @extends BI.NodeButton
+ */
+BI.TextNode = BI.inherit(BI.NodeButton, {
+
+ _defaultConfig: function () {
+ var conf = BI.TextNode.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-text-node",
+ textAlign: "left",
+ whiteSpace: "nowrap",
+ textHgap: 0,
+ textVgap: 0,
+ textLgap: 0,
+ textRgap: 0
+ })
+ },
+ _init: function () {
+ BI.TextNode.superclass._init.apply(this, arguments);
+ var o = this.options;
+ this.text = BI.createWidget({
+ type: "bi.label",
+ element: this,
+ textAlign: o.textAlign,
+ whiteSpace: o.whiteSpace,
+ textHeight: o.whiteSpace == "nowrap" ? o.height : o.textHeight,
+ height: o.height,
+ hgap: o.textHgap,
+ vgap: o.textVgap,
+ lgap: o.textLgap,
+ rgap: o.textRgap,
+ text: o.text,
+ value: o.value,
+ keyword: o.keyword,
+ py: o.py
+ });
+ },
+
+ doClick: function () {
+ BI.TextNode.superclass.doClick.apply(this, arguments);
+ if (this.isValid()) {
+ this.fireEvent(BI.TextNode.EVENT_CHANGE, this.getValue(), this);
+ }
+ },
+
+ doRedMark: function () {
+ this.text.doRedMark.apply(this.text, arguments);
+ },
+
+ unRedMark: function () {
+ this.text.unRedMark.apply(this.text, arguments);
+ },
+
+ setValue: function () {
+ if (!this.isReadOnly()) {
+ this.text.setValue.apply(this.text, arguments);
+ }
+ },
+
+ getValue: function () {
+ return this.text.getValue();
+ },
+
+ setText: function () {
+ this.text.setText.apply(this.text, arguments);
+ },
+
+ getText: function () {
+ return this.text.getText();
+ }
+});
+BI.TextNode.EVENT_CHANGE = "EVENT_CHANGE";
+$.shortcut("bi.text_node", BI.TextNode);/**
+ *
+ * Created by GUY on 2016/1/15.
+ * @class BI.CodeEditor
+ * @extends BI.Single
+ */
+BI.CodeEditor = BI.inherit(BI.Single, {
+ _defaultConfig: function () {
+ return $.extend(BI.CodeEditor.superclass._defaultConfig.apply(), {
+ baseCls: 'bi-code-editor',
+ value: '',
+ watermark: ""
+ });
+ },
+ _init: function () {
+ BI.CodeEditor.superclass._init.apply(this, arguments);
+ var o = this.options, self = this;
+ this.editor = CodeMirror(this.element[0], {
+ textWrapping: true,
+ lineWrapping: true,
+ lineNumbers: false
+ });
+ this.editor.on("change", function (cm, change) {
+ BI.nextTick(function () {
+ self.fireEvent(BI.CodeEditor.EVENT_CHANGE)
+ });
+ });
+
+ this.editor.on("focus", function () {
+ watermark.setVisible(false);
+ self.fireEvent(BI.CodeEditor.EVENT_FOCUS);
+ });
+
+ this.editor.on("blur", function () {
+ watermark.setVisible(BI.isEmptyString(self.getValue()));
+ self.fireEvent(BI.CodeEditor.EVENT_BLUR);
+ });
+
+ // this.editor.on("blur", function () {
+ // self.editor.execCommand("goLineEnd");
+ // });
+
+ //水印
+ var watermark = BI.createWidget({
+ type: "bi.label",
+ text: o.watermark,
+ cls: "bi-water-mark",
+ whiteSpace: "nowrap",
+ textAlign: "left"
+ });
+ watermark.element.bind(
+ "mousedown", function (e) {
+ self.insertString("");
+ self.editor.focus();
+ e.stopEvent();
+ }
+ );
+ watermark.element.bind("click", function (e) {
+ self.editor.focus();
+ e.stopEvent();
+ });
+ BI.createWidget({
+ type: "bi.absolute",
+ element: this,
+ items: [{
+ el: watermark,
+ top: 0,
+ left: 5
+ }]
+ });
+
+ if (BI.isKey(o.value)) {
+ BI.nextTick(function () {
+ self.setValue(o.value);
+ });
+ }
+ },
+
+ setEnable: function (b) {
+ BI.CodeEditor.superclass.setEnable.apply(this, arguments);
+ this.editor.setOption("readOnly", b === true ? false : "nocursor")
+ },
+
+ insertParam: function(param){
+ var from = this.editor.getCursor();
+ this.editor.replaceSelection(param);
+ var to = this.editor.getCursor();
+ this.editor.markText(from, to, {className: 'param', atomic: true});
+ this.editor.replaceSelection(" ");
+ this.editor.focus();
+ },
+
+ insertString: function(str){
+ this.editor.replaceSelection(str);
+ this.editor.focus();
+ },
+
+ getValue: function () {
+ return this.editor.getValue("\n", function (line) {
+ var rawText = line.text, value = line.text, num = 0;
+ value.text = rawText;
+ _.forEach(line.markedSpans, function (i, ms) {
+ switch (i.marker.className) {
+ case "param":
+ var fieldNameLength = i.to - i.from;
+ value = value.substr(0, i.from + num) + "$\{" + value.substr(i.from + num, fieldNameLength) + "\}" + value.substr(i.to + num, value.length);
+ num += 3;
break;
}
- BI.each(colgroupTds, function (i, colgroup) {
- var width = colgroup.attr("width") | 0;
- if (width !== sizes[i]) {
- var w = self._calculateWidth(sizes[i]);
- colgroup.attr("width", w).css("width", w);
- BI.each(bodyTds, function (j, items) {
- if (items[i]) {
- if (items[i].__mergeCols.length > 1) {
- var wid = 0;
- BI.each(sizes, function (t, s) {
- if (items[i].__mergeCols.contains(t)) {
- wid += s;
- }
- });
- wid = self._calculateWidth(wid);
- if (wid > 1) {
- wid += items[i].__mergeCols.length - 1;
- }
- if (BI.isNumeric(wid)) {
- if (i == BI.size(items) - 1) {
- items[i].attr("width", wid - 1).css("width", wid - 1);
- } else {
- items[i].attr("width", wid).css("width", wid);
- }
- } else {
- items[i].attr("width", "").css("width", "");
- }
- } else {
- if (i == BI.size(items) - 1) {
- items[i].attr("width", w - 1).css("width", w - 1);
- } else {
- items[i].attr("width", w).css("width", w);
- }
- }
- }
- });
- BI.each(bodyItems, function (j, items) {
- if (items[i]) {
- if (bodyTds[j][i].__mergeCols.length > 1) {
- var wid = 0;
- BI.each(sizes, function (t, s) {
- if (bodyTds[j][i].__mergeCols.contains(t)) {
- wid += s;
- }
- });
- wid = self._calculateWidth(wid);
- if (wid > 1) {
- wid += bodyTds[j][i].__mergeCols.length - 1;
- }
- if (BI.isNumeric(wid)) {
- if (i == BI.size(items) - 1) {
- items[i].element.attr("width", wid - 1).css("width", wid - 1);
- } else {
- items[i].element.attr("width", wid).css("width", wid);
- }
- } else {
- items[i].element.attr("width", "").css("width", "");
- }
- } else {
- if (BI.isNumeric(w)) {
- if (i == BI.size(items) - 1) {
- items[i].element.attr("width", w - 1).css("width", w - 1);
- } else {
- items[i].element.attr("width", w).css("width", w);
- }
- } else {
- items[i].element.attr("width", "").css("width", "");
- }
- }
- }
- });
- }
- })
- };
- run(topleft);
- run(topright);
- run(bottomleft);
- run(bottomright);
+ });
+ return value;
+ });
+ },
+
+ _analyzeContent: function (v) {
+ var regx = /\$[\{][^\}]*[\}]|(\s+)|\w*\w|\$\{[^\$\(\)\+\-\*\/)\$,]*\w\}|\$\{[^\$\(\)\+\-\*\/]*\w\}|\$\{[^\$\(\)\+\-\*\/]*[\u4e00-\u9fa5]\}|\w|(.)|\n/g;
+ return v.match(regx);
+ },
+
+ setValue: function (v) {
+ var self = this, result;
+ this.refresh();
+ self.editor.setValue("");
+ result = this._analyzeContent(v || "");
+ BI.each(result, function (i, item) {
+ var fieldRegx = /\$[\{][^\}]*[\}]/;
+ var str = item.match(fieldRegx);
+ if (BI.isNotEmptyArray(str)) {
+ self.insertParam(str[0].substring(2, item.length - 1));
+ } else {
+ self.insertString(item);
+ }
+ })
+ },
+
+ refresh: function(){
+ var self = this;
+ BI.nextTick(function () {
+ self.editor.refresh();
+ });
+ }
+});
+BI.CodeEditor.EVENT_CHANGE = "EVENT_CHANGE";
+BI.CodeEditor.EVENT_BLUR = "EVENT_BLUR";
+BI.CodeEditor.EVENT_FOCUS = "EVENT_FOCUS";
+$.shortcut("bi.code_editor", BI.CodeEditor);/**
+ * Created by GUY on 2015/4/15.
+ * @class BI.Editor
+ * @extends BI.Single
+ */
+BI.Editor = BI.inherit(BI.Single, {
+ _defaultConfig: function () {
+ var conf = BI.Editor.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: "bi-editor",
+ hgap: 4,
+ vgap: 2,
+ lgap: 0,
+ rgap: 0,
+ tgap: 0,
+ bgap: 0,
+ tipType: "warning",
+ inputType: "text",
+ validationChecker: BI.emptyFn,
+ quitChecker: BI.emptyFn,
+ mouseOut: false,
+ allowBlank: false,
+ watermark: "",
+ errorText: ""
+ })
+ },
+
+ _init: function () {
+ BI.Editor.superclass._init.apply(this, arguments);
+ var self = this, o = this.options;
+ this.editor = this.addWidget(BI.createWidget({
+ type: "bi.input",
+ element: " ",
+ watermark: o.watermark,
+ validationChecker: o.validationChecker,
+ quitChecker: o.quitChecker,
+ mouseOut: o.mouseOut,
+ allowBlank: o.allowBlank
+ }));
+ this.editor.element.css({
+ "width": "100%",
+ "height": "100%",
+ "border": "none",
+ "outline": "none",
+ "padding": "0",
+ "margin": "0"
+ });
+ if (BI.isKey(this.options.watermark)) {
+ this.watermark = BI.createWidget({
+ type: "bi.label",
+ cls: "bi-water-mark",
+ text: this.options.watermark,
+ height: this.options.height,
+ forceCenter: true,
+ height: o.height - 2 * (o.vgap + o.tgap),
+ whiteSpace: "nowrap",
+ textAlign: "left"
+ });
+ this.watermark.element.bind({
+ mousedown: function (e) {
+ if (self.isEnabled()) {
+ self.editor.isEditing() || self.editor.focus();
+ } else {
+ self.editor.isEditing() && self.editor.blur();
+ }
+ e.stopEvent();
+ }
+ });
+ this.watermark.element.bind("click", function (e) {
+ if (self.isEnabled()) {
+ self.editor.isEditing() || self.editor.focus();
+ } else {
+ self.editor.isEditing() && self.editor.blur();
+ }
+ e.stopEvent();
+ });
+ this.watermark.element.css({
+ position: "absolute",
+ left: "3px",
+ right: "3px",
+ top: "0px",
+ bottom: "0px"
+ });
+ }
+ var items = [{
+ el: {
+ type: "bi.default",
+ items: this.watermark ? [this.editor, this.watermark] : [this.editor]
+ },
+ left: o.hgap + o.lgap,
+ right: o.hgap + o.rgap,
+ top: o.vgap + o.tgap,
+ bottom: o.vgap + o.bgap
+ }];
+
+ BI.createWidget({
+ type: "bi.absolute",
+ element: this,
+ items: items
+ });
+ this.editor.on(BI.Controller.EVENT_CHANGE, function () {
+ self.fireEvent(BI.Controller.EVENT_CHANGE, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_FOCUS, function () {
+ self._checkError();
+ self.element.addClass("bi-editor-focus");
+ self.fireEvent(BI.Editor.EVENT_FOCUS, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_BLUR, function () {
+ self.setErrorVisible(false);
+ self.element.removeClass("bi-editor-focus");
+ self.fireEvent(BI.Editor.EVENT_BLUR, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_CLICK, function () {
+ self.fireEvent(BI.Editor.EVENT_CLICK, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_CHANGE, function () {
+ self.fireEvent(BI.Editor.EVENT_CHANGE, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_KEY_DOWN, function (v) {
+ self.fireEvent(BI.Editor.EVENT_KEY_DOWN, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_QUICK_DOWN, function (v) {
+ self.watermark && self.watermark.invisible();
+ });
+
+ this.editor.on(BI.Input.EVENT_VALID, function () {
+ self._checkWaterMark();
+ self.setErrorVisible(false);
+ self.fireEvent(BI.Editor.EVENT_VALID, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_ERROR, function () {
+ self._checkWaterMark();
+ self.fireEvent(BI.Editor.EVENT_ERROR, arguments);
+ self.setErrorVisible(self.isEditing());
+ });
+ this.editor.on(BI.Input.EVENT_RESTRICT, function () {
+ self._checkWaterMark();
+ var tip = self.setErrorVisible(true);
+ tip && tip.element.fadeOut(100, function () {
+ tip.element.fadeIn(100);
+ });
+ self.fireEvent(BI.Editor.EVENT_RESTRICT, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_EMPTY, function () {
+ self._checkWaterMark();
+ self.fireEvent(BI.Editor.EVENT_EMPTY, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_ENTER, function () {
+ self.fireEvent(BI.Editor.EVENT_ENTER, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_SPACE, function () {
+ self.fireEvent(BI.Editor.EVENT_SPACE, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_BACKSPACE, function () {
+ self.fireEvent(BI.Editor.EVENT_BACKSPACE, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_REMOVE, function () {
+ self.fireEvent(BI.Editor.EVENT_REMOVE, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_START, function () {
+ self.fireEvent(BI.Editor.EVENT_START, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_PAUSE, function () {
+ self.fireEvent(BI.Editor.EVENT_PAUSE, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_STOP, function () {
+ self.fireEvent(BI.Editor.EVENT_STOP, arguments);
+ });
+ this.editor.on(BI.Input.EVENT_CONFIRM, function () {
+ self.fireEvent(BI.Editor.EVENT_CONFIRM, arguments);
+ });
+ this.element.click(function (e) {
+ e.stopPropagation();
+ return false;
+ });
+ if (BI.isKey(this.options.value) || BI.isEmptyString(this.options.value)) {
+ this.setValue(this.options.value);
+ } else {
+ this._checkWaterMark();
+ }
+ },
+
+ _checkToolTip: function () {
+ var o = this.options;
+ var errorText = o.errorText;
+ if (BI.isFunction(errorText)) {
+ errorText = errorText(this.editor.getValue());
+ }
+ if (BI.isKey(errorText)) {
+ if (!this.isEnabled() || this.isValid() || (BI.Bubbles.has(this.getName()) && BI.Bubbles.get(this.getName()).isVisible())) {
+ this.setTitle("");
+ } else {
+ this.setTitle(errorText);
+ }
+ }
+ },
+
+ _checkError: function () {
+ this.setErrorVisible(this.isEnabled() && !this.isValid());
+ this._checkToolTip();
+ },
+
+ _checkWaterMark: function () {
+ var o = this.options;
+ if (!this.disabledWarterMark && this.editor.getValue() === "" && BI.isKey(o.watermark)) {
+ this.watermark && this.watermark.visible();
+ } else {
+ this.watermark && this.watermark.invisible();
+ }
+ },
+
+ setErrorText: function (text) {
+ this.options.errorText = text;
+ },
+
+ getErrorText: function () {
+ return this.options.errorText;
+ },
+
+ setErrorVisible: function (b) {
+ var o = this.options;
+ var errorText = o.errorText;
+ if (BI.isFunction(errorText)) {
+ errorText = errorText(this.editor.getValue());
+ }
+ if (!this.disabledError && BI.isKey(errorText)) {
+ BI.Bubbles[b ? "show" : "hide"](this.getName(), errorText, this);
+ this._checkToolTip();
+ return BI.Bubbles.get(this.getName());
+ }
+ },
+
+ disableError: function () {
+ this.disabledError = true;
+ this._checkError();
+ },
+
+ enableError: function () {
+ this.disabledError = false;
+ this._checkError();
+ },
+
+ disableWarterMark: function () {
+ this.disabledWarterMark = true;
+ this._checkWaterMark();
+ },
+
+ enableWarterMark: function () {
+ this.disabledWarterMark = false;
+ this._checkWaterMark();
+ },
+
+ focus: function () {
+ this.element.addClass("text-editor-focus");
+ this.editor.focus();
+ },
+
+ blur: function () {
+ this.element.removeClass("text-editor-focus");
+ this.editor.blur();
+ },
+
+ selectAll: function () {
+ this.editor.selectAll();
+ },
+
+ onKeyDown: function (k) {
+ this.editor.onKeyDown(k);
+ },
+
+ setValue: function (v) {
+ BI.Editor.superclass.setValue.apply(this, arguments);
+ this.editor.setValue(v);
+ this._checkError();
+ this._checkWaterMark();
+ },
+
+ getLastValidValue: function () {
+ return this.editor.getLastValidValue();
+ },
+
+ resetLastValidValue: function () {
+ this.editor.resetLastValidValue();
+ },
+
+ getValue: function () {
+ if (!this.isValid()) {
+ return BI.trim(this.editor.getLastValidValue());
+ }
+ return BI.trim(this.editor.getValue());
+ },
+
+ setValid: function (b) {
+ BI.Editor.superclass.setValid.apply(this, arguments);
+ this.editor.setValid(b);
+ },
+
+ isEditing: function () {
+ return this.editor.isEditing();
+ },
+
+ isValid: function () {
+ return this.editor.isValid();
+ },
+
+ setEnable: function (b) {
+ BI.Editor.superclass.setEnable.apply(this, arguments);
+ this.editor && this.editor.setEnable(b);
+ this.watermark && this.watermark.setEnable(b);
+ }
+});
+BI.Editor.EVENT_CHANGE = "EVENT_CHANGE";
+BI.Editor.EVENT_FOCUS = "EVENT_FOCUS";
+BI.Editor.EVENT_BLUR = "EVENT_BLUR";
+BI.Editor.EVENT_CLICK = "EVENT_CLICK";
+BI.Editor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN";
+BI.Editor.EVENT_SPACE = "EVENT_SPACE";
+BI.Editor.EVENT_BACKSPACE = "EVENT_BACKSPACE";
+
+BI.Editor.EVENT_START = "EVENT_START";
+BI.Editor.EVENT_PAUSE = "EVENT_PAUSE";
+BI.Editor.EVENT_STOP = "EVENT_STOP";
+BI.Editor.EVENT_CONFIRM = "EVENT_CONFIRM";
+BI.Editor.EVENT_VALID = "EVENT_VALID";
+BI.Editor.EVENT_ERROR = "EVENT_ERROR";
+BI.Editor.EVENT_ENTER = "EVENT_ENTER";
+BI.Editor.EVENT_RESTRICT = "EVENT_RESTRICT";
+BI.Editor.EVENT_REMOVE = "EVENT_REMOVE";
+BI.Editor.EVENT_EMPTY = "EVENT_EMPTY";
+
+$.shortcut("bi.editor", BI.Editor);/**
+ * 多文件
+ *
+ * Created by GUY on 2016/4/13.
+ * @class BI.MultifileEditor
+ * @extends BI.Single
+ * @abstract
+ */
+BI.MultifileEditor = BI.inherit(BI.Single, {
+ _defaultConfig: function () {
+ var conf = BI.MultifileEditor.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-multifile-editor",
+ multiple: false,
+ maxSize: 1024 * 1024,
+ accept: "",
+ url: ""
+ })
+ },
+
+ _init: function () {
+ var self = this, o = this.options;
+ BI.MultifileEditor.superclass._init.apply(this, arguments);
+ this.file = BI.createWidget({
+ type: "bi.file",
+ cls: "multifile-editor",
+ width: "100%",
+ height: "100%",
+ name: o.name,
+ url: o.url,
+ multiple: o.multiple,
+ accept: o.accept,
+ maxSize: o.maxSize
+ });
+ this.file.on(BI.File.EVENT_CHANGE, function () {
+ self.fireEvent(BI.MultifileEditor.EVENT_CHANGE, arguments);
+ });
+ this.file.on(BI.File.EVENT_UPLOADSTART, function () {
+ self.fireEvent(BI.MultifileEditor.EVENT_UPLOADSTART, arguments);
+ });
+ this.file.on(BI.File.EVENT_ERROR, function () {
+ self.fireEvent(BI.MultifileEditor.EVENT_ERROR, arguments);
+ });
+ this.file.on(BI.File.EVENT_PROGRESS, function () {
+ self.fireEvent(BI.MultifileEditor.EVENT_PROGRESS, arguments);
+ });
+ this.file.on(BI.File.EVENT_UPLOADED, function () {
+ self.fireEvent(BI.MultifileEditor.EVENT_UPLOADED, arguments);
+ });
+
+ BI.createWidget({
+ type: "bi.absolute",
+ element: this,
+ items: [{
+ el: {
+ type: "bi.adaptive",
+ scrollable: false,
+ items: [this.file]
+ },
+ top: 0,
+ right: 0,
+ left: 0,
+ bottom: 0
+ }]
+ });
+ },
+
+ select: function () {
+ this.file.select();
+ },
+
+ getValue: function () {
+ return this.file.getValue();
+ },
+
+ upload: function () {
+ this.file.upload();
+ },
+
+ reset: function () {
+ this.file.reset();
+ },
+
+ setEnable: function (enable) {
+ BI.MultiFile.superclass.setEnable.apply(this, arguments);
+ this.file.setEnable(enable);
+ }
+});
+BI.MultifileEditor.EVENT_CHANGE = "MultifileEditor.EVENT_CHANGE";
+BI.MultifileEditor.EVENT_UPLOADSTART = "MultifileEditor.EVENT_UPLOADSTART";
+BI.MultifileEditor.EVENT_ERROR = "MultifileEditor.EVENT_ERROR";
+BI.MultifileEditor.EVENT_PROGRESS = "MultifileEditor.EVENT_PROGRESS";
+BI.MultifileEditor.EVENT_UPLOADED = "MultifileEditor.EVENT_UPLOADED";
+$.shortcut("bi.multifile_editor", BI.MultifileEditor);/**
+ *
+ * Created by GUY on 2016/1/18.
+ * @class BI.TextAreaEditor
+ * @extends BI.Single
+ */
+BI.TextAreaEditor = BI.inherit(BI.Single, {
+ _defaultConfig: function () {
+ return $.extend(BI.TextAreaEditor.superclass._defaultConfig.apply(), {
+ baseCls: 'bi-textarea-editor',
+ value: ''
+ });
+ },
+ _init: function () {
+ BI.TextAreaEditor.superclass._init.apply(this, arguments);
+ var o = this.options, self = this;
+ this.content = BI.createWidget({
+ type: "bi.layout",
+ tagName: "textarea",
+ width: "100%",
+ height: "100%",
+ cls: "textarea-editor-content display-block"
+ });
+ this.content.element.css({"resize": "none"});
+ BI.createWidget({
+ type: "bi.absolute",
+ element: this,
+ items: [{
+ el: {
+ type: "bi.adaptive",
+ items: [this.content]
+ },
+ left: 0,
+ right: 3,
+ top: 0,
+ bottom: 5
+ }]
+ });
+
+ this.content.element.on("input propertychange", function (e) {
+ self._checkWaterMark();
+ self.fireEvent(BI.TextAreaEditor.EVENT_CHANGE);
+ });
+
+ this.content.element.focus(function () {
+ if (self.isValid()) {
+ self._focus();
+ self.fireEvent(BI.TextAreaEditor.EVENT_FOCUS);
+ }
+ $(document).bind("mousedown." + self.getName(), function (e) {
+ if (BI.DOM.isExist(self) && !self.element.__isMouseInBounds__(e)) {
+ $(document).unbind("mousedown." + self.getName());
+ self.content.element.blur();
+ }
+ });
+ });
+ this.content.element.blur(function () {
+ if (self.isValid()) {
+ self._blur();
+ self.fireEvent(BI.TextAreaEditor.EVENT_BLUR);
+ }
+ $(document).unbind("mousedown." + self.getName());
+ });
+ if (BI.isKey(o.value)) {
+ self.setValue(o.value);
+ }
+ if (BI.isNotNull(o.style)) {
+ self.setValue(o.style);
+ }
+ this._checkWaterMark();
+ },
+
+ _checkWaterMark: function () {
+ var self = this, o = this.options;
+ var val = this.getValue();
+ if (BI.isNotEmptyString(val)) {
+ this.watermark && this.watermark.destroy();
+ this.watermark = null;
+ } else {
+ if (BI.isNotEmptyString(o.watermark)) {
+ if (!this.watermark) {
+ this.watermark = BI.createWidget({
+ type: "bi.text_button",
+ cls: "bi-water-mark",
+ textAlign: "left",
+ height: 30,
+ text: o.watermark,
+ invalid: o.invalid,
+ disabled: o.disabled
+ });
+ this.watermark.on(BI.TextButton.EVENT_CHANGE, function () {
+ self.focus();
+ });
+ BI.createWidget({
+ type: 'bi.absolute',
+ element: this,
+ items: [{
+ el: this.watermark,
+ left: 0,
+ top: 0,
+ right: 0
+ }]
+ })
+ } else {
+ this.watermark.setText(o.watermark);
+ this.watermark.setValid(!o.invalid);
+ this.watermark.setEnable(!o.disabled);
+ }
+ }
+ }
+ },
+
+ _focus: function () {
+ this.content.element.addClass("textarea-editor-focus");
+ this._checkWaterMark();
+ },
+
+ _blur: function () {
+ this.content.element.removeClass("textarea-editor-focus");
+ this._checkWaterMark();
+ },
+
+ focus: function () {
+ this._focus();
+ this.content.element.focus();
+ },
+
+ blur: function () {
+ this._blur();
+ this.content.element.blur();
+ },
+
+ getValue: function () {
+ return this.content.element.val();
+ },
+
+ setValue: function (value) {
+ this.content.element.val(value);
+ },
+
+ setStyle: function (style) {
+ this.style = style;
+ this.element.css(style);
+ this.content.element.css(style)
+ },
+
+ getStyle: function () {
+ return this.style;
+ },
+
+ setValid: function (b) {
+ BI.TextAreaEditor.superclass.setValid.apply(this, arguments);
+ this.content.setValid(b);
+ this.watermark && this.watermark.setValid(b);
+ },
+
+ setEnable: function (b) {
+ BI.TextAreaEditor.superclass.setEnable.apply(this, arguments);
+ this.content.setEnable(b);
+ this.watermark && this.watermark.setEnable(b);
+ }
+});
+BI.TextAreaEditor.EVENT_CHANGE = "EVENT_CHANGE";
+BI.TextAreaEditor.EVENT_BLUR = "EVENT_BLUR";
+BI.TextAreaEditor.EVENT_FOCUS = "EVENT_FOCUS";
+$.shortcut("bi.textarea_editor", BI.TextAreaEditor);/**
+ * guy 图标
+ * @class BI.Icon
+ * @extends BI.Single
+ */
+BI.Icon = BI.inherit(BI.Single, {
+ _defaultConfig: function () {
+ var conf = BI.Icon.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ tagName: "i",
+ baseCls: (conf.baseCls || "") + " x-icon b-font horizon-center display-block"
+ })
+ },
+ _init: function () {
+ BI.Icon.superclass._init.apply(this, arguments);
+ }
+});
+$.shortcut("bi.icon", BI.Icon);/**
+ * @class BI.Iframe
+ * @extends BI.Single
+ * @abstract
+ * Created by GameJian on 2016/3/2.
+ */
+BI.Iframe = BI.inherit(BI.Single, {
+ _defaultConfig: function () {
+ var conf = BI.Iframe.superclass._defaultConfig.apply(this, arguments);
+ return BI.extend(conf, {
+ baseCls: (conf.baseCls || "") + " bi-iframe",
+ src: "",
+ width: "100%",
+ height: "100%"
+ })
+ },
+
+ _init: function () {
+ var o = this.options;
+ this.options.element = $(" |