";
};
if (options.codeBlockRenderer) {
renderer.code = function (code, lang) {
var value = options.codeBlockRenderer(lang, code);
// when code-block rendering is async we return sync
// but update the node with the real result later.
var id = idGenerator_1.defaultGenerator.nextId();
var promise = Promise.all([value, withInnerHTML]).then(function (values) {
var strValue = values[0];
var span = element.querySelector("div[data-code=\"" + id + "\"]");
if (span) {
span.innerHTML = strValue;
}
}).catch(function (err) {
// ignore
});
if (options.codeBlockRenderCallback) {
promise.then(options.codeBlockRenderCallback);
}
return "
" + strings_1.escape(code) + "
";
};
}
var actionHandler = options.actionHandler;
if (actionHandler) {
actionHandler.disposeables.add(DOM.addStandardDisposableListener(element, 'click', function (event) {
var target = event.target;
if (target.tagName !== 'A') {
target = target.parentElement;
if (!target || target.tagName !== 'A') {
return;
}
}
try {
var href = target.dataset['href'];
if (href) {
actionHandler.callback(href, event);
}
}
catch (err) {
errors_1.onUnexpectedError(err);
}
finally {
event.preventDefault();
}
}));
}
var markedOptions = {
sanitize: true,
renderer: renderer
};
var allowedSchemes = [network_1.Schemas.http, network_1.Schemas.https, network_1.Schemas.mailto, network_1.Schemas.data, network_1.Schemas.file, network_1.Schemas.vscodeRemote, network_1.Schemas.vscodeRemoteResource];
if (markdown.isTrusted) {
allowedSchemes.push(network_1.Schemas.command);
}
var renderedMarkdown = marked.parse(markdown.supportThemeIcons
? codicons_1.markdownEscapeEscapedCodicons(markdown.value)
: markdown.value, markedOptions);
element.innerHTML = insane_1.insane(renderedMarkdown, {
allowedSchemes: allowedSchemes,
allowedAttributes: {
'a': ['href', 'name', 'target', 'data-href'],
'iframe': ['allowfullscreen', 'frameborder', 'src'],
'img': ['src', 'title', 'alt', 'width', 'height'],
'div': ['class', 'data-code'],
'span': ['class']
}
});
signalInnerHTML();
return element;
}
exports.renderMarkdown = renderMarkdown;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
define(__m[57/*vs/base/browser/touch*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,6/*vs/base/browser/dom*/,101/*vs/base/common/decorators*/]), function (require, exports, arrays, lifecycle_1, DomUtils, decorators_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var EventType;
(function (EventType) {
EventType.Tap = '-monaco-gesturetap';
EventType.Change = '-monaco-gesturechange';
EventType.Start = '-monaco-gesturestart';
EventType.End = '-monaco-gesturesend';
EventType.Contextmenu = '-monaco-gesturecontextmenu';
})(EventType = exports.EventType || (exports.EventType = {}));
var Gesture = /** @class */ (function (_super) {
__extends(Gesture, _super);
function Gesture() {
var _this = _super.call(this) || this;
_this.dispatched = false;
_this.activeTouches = {};
_this.handle = null;
_this.targets = [];
_this.ignoreTargets = [];
_this._lastSetTapCountTime = 0;
_this._register(DomUtils.addDisposableListener(document, 'touchstart', function (e) { return _this.onTouchStart(e); }));
_this._register(DomUtils.addDisposableListener(document, 'touchend', function (e) { return _this.onTouchEnd(e); }));
_this._register(DomUtils.addDisposableListener(document, 'touchmove', function (e) { return _this.onTouchMove(e); }));
return _this;
}
Gesture.addTarget = function (element) {
if (!Gesture.isTouchDevice()) {
return lifecycle_1.Disposable.None;
}
if (!Gesture.INSTANCE) {
Gesture.INSTANCE = new Gesture();
}
Gesture.INSTANCE.targets.push(element);
return {
dispose: function () {
Gesture.INSTANCE.targets = Gesture.INSTANCE.targets.filter(function (t) { return t !== element; });
}
};
};
Gesture.ignoreTarget = function (element) {
if (!Gesture.isTouchDevice()) {
return lifecycle_1.Disposable.None;
}
if (!Gesture.INSTANCE) {
Gesture.INSTANCE = new Gesture();
}
Gesture.INSTANCE.ignoreTargets.push(element);
return {
dispose: function () {
Gesture.INSTANCE.ignoreTargets = Gesture.INSTANCE.ignoreTargets.filter(function (t) { return t !== element; });
}
};
};
Gesture.isTouchDevice = function () {
return 'ontouchstart' in window || navigator.maxTouchPoints > 0 || window.navigator.msMaxTouchPoints > 0;
};
Gesture.prototype.dispose = function () {
if (this.handle) {
this.handle.dispose();
this.handle = null;
}
_super.prototype.dispose.call(this);
};
Gesture.prototype.onTouchStart = function (e) {
var timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
if (this.handle) {
this.handle.dispose();
this.handle = null;
}
for (var i = 0, len = e.targetTouches.length; i < len; i++) {
var touch = e.targetTouches.item(i);
this.activeTouches[touch.identifier] = {
id: touch.identifier,
initialTarget: touch.target,
initialTimeStamp: timestamp,
initialPageX: touch.pageX,
initialPageY: touch.pageY,
rollingTimestamps: [timestamp],
rollingPageX: [touch.pageX],
rollingPageY: [touch.pageY]
};
var evt = this.newGestureEvent(EventType.Start, touch.target);
evt.pageX = touch.pageX;
evt.pageY = touch.pageY;
this.dispatchEvent(evt);
}
if (this.dispatched) {
e.preventDefault();
e.stopPropagation();
this.dispatched = false;
}
};
Gesture.prototype.onTouchEnd = function (e) {
var timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
var activeTouchCount = Object.keys(this.activeTouches).length;
var _loop_1 = function (i, len) {
var touch = e.changedTouches.item(i);
if (!this_1.activeTouches.hasOwnProperty(String(touch.identifier))) {
console.warn('move of an UNKNOWN touch', touch);
return "continue";
}
var data = this_1.activeTouches[touch.identifier], holdTime = Date.now() - data.initialTimeStamp;
if (holdTime < Gesture.HOLD_DELAY
&& Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)) < 30
&& Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)) < 30) {
var evt = this_1.newGestureEvent(EventType.Tap, data.initialTarget);
evt.pageX = arrays.tail(data.rollingPageX);
evt.pageY = arrays.tail(data.rollingPageY);
this_1.dispatchEvent(evt);
}
else if (holdTime >= Gesture.HOLD_DELAY
&& Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)) < 30
&& Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)) < 30) {
var evt = this_1.newGestureEvent(EventType.Contextmenu, data.initialTarget);
evt.pageX = arrays.tail(data.rollingPageX);
evt.pageY = arrays.tail(data.rollingPageY);
this_1.dispatchEvent(evt);
}
else if (activeTouchCount === 1) {
var finalX = arrays.tail(data.rollingPageX);
var finalY = arrays.tail(data.rollingPageY);
var deltaT = arrays.tail(data.rollingTimestamps) - data.rollingTimestamps[0];
var deltaX = finalX - data.rollingPageX[0];
var deltaY = finalY - data.rollingPageY[0];
// We need to get all the dispatch targets on the start of the inertia event
var dispatchTo = this_1.targets.filter(function (t) { return data.initialTarget instanceof Node && t.contains(data.initialTarget); });
this_1.inertia(dispatchTo, timestamp, // time now
Math.abs(deltaX) / deltaT, // speed
deltaX > 0 ? 1 : -1, // x direction
finalX, // x now
Math.abs(deltaY) / deltaT, // y speed
deltaY > 0 ? 1 : -1, // y direction
finalY // y now
);
}
this_1.dispatchEvent(this_1.newGestureEvent(EventType.End, data.initialTarget));
// forget about this touch
delete this_1.activeTouches[touch.identifier];
};
var this_1 = this;
for (var i = 0, len = e.changedTouches.length; i < len; i++) {
_loop_1(i, len);
}
if (this.dispatched) {
e.preventDefault();
e.stopPropagation();
this.dispatched = false;
}
};
Gesture.prototype.newGestureEvent = function (type, initialTarget) {
var event = document.createEvent('CustomEvent');
event.initEvent(type, false, true);
event.initialTarget = initialTarget;
event.tapCount = 0;
return event;
};
Gesture.prototype.dispatchEvent = function (event) {
var _this = this;
if (event.type === EventType.Tap) {
var currentTime = (new Date()).getTime();
var setTapCount = 0;
if (currentTime - this._lastSetTapCountTime > Gesture.CLEAR_TAP_COUNT_TIME) {
setTapCount = 1;
}
else {
setTapCount = 2;
}
this._lastSetTapCountTime = currentTime;
event.tapCount = setTapCount;
}
else if (event.type === EventType.Change || event.type === EventType.Contextmenu) {
// tap is canceled by scrolling or context menu
this._lastSetTapCountTime = 0;
}
for (var i = 0; i < this.ignoreTargets.length; i++) {
if (event.initialTarget instanceof Node && this.ignoreTargets[i].contains(event.initialTarget)) {
return;
}
}
this.targets.forEach(function (target) {
if (event.initialTarget instanceof Node && target.contains(event.initialTarget)) {
target.dispatchEvent(event);
_this.dispatched = true;
}
});
};
Gesture.prototype.inertia = function (dispatchTo, t1, vX, dirX, x, vY, dirY, y) {
var _this = this;
this.handle = DomUtils.scheduleAtNextAnimationFrame(function () {
var now = Date.now();
// velocity: old speed + accel_over_time
var deltaT = now - t1, delta_pos_x = 0, delta_pos_y = 0, stopped = true;
vX += Gesture.SCROLL_FRICTION * deltaT;
vY += Gesture.SCROLL_FRICTION * deltaT;
if (vX > 0) {
stopped = false;
delta_pos_x = dirX * vX * deltaT;
}
if (vY > 0) {
stopped = false;
delta_pos_y = dirY * vY * deltaT;
}
// dispatch translation event
var evt = _this.newGestureEvent(EventType.Change);
evt.translationX = delta_pos_x;
evt.translationY = delta_pos_y;
dispatchTo.forEach(function (d) { return d.dispatchEvent(evt); });
if (!stopped) {
_this.inertia(dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);
}
});
};
Gesture.prototype.onTouchMove = function (e) {
var timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
for (var i = 0, len = e.changedTouches.length; i < len; i++) {
var touch = e.changedTouches.item(i);
if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
console.warn('end of an UNKNOWN touch', touch);
continue;
}
var data = this.activeTouches[touch.identifier];
var evt = this.newGestureEvent(EventType.Change, data.initialTarget);
evt.translationX = touch.pageX - arrays.tail(data.rollingPageX);
evt.translationY = touch.pageY - arrays.tail(data.rollingPageY);
evt.pageX = touch.pageX;
evt.pageY = touch.pageY;
this.dispatchEvent(evt);
// only keep a few data points, to average the final speed
if (data.rollingPageX.length > 3) {
data.rollingPageX.shift();
data.rollingPageY.shift();
data.rollingTimestamps.shift();
}
data.rollingPageX.push(touch.pageX);
data.rollingPageY.push(touch.pageY);
data.rollingTimestamps.push(timestamp);
}
if (this.dispatched) {
e.preventDefault();
e.stopPropagation();
this.dispatched = false;
}
};
Gesture.SCROLL_FRICTION = -0.005;
Gesture.HOLD_DELAY = 700;
Gesture.CLEAR_TAP_COUNT_TIME = 400; // ms
__decorate([
decorators_1.memoize
], Gesture, "isTouchDevice", null);
return Gesture;
}(lifecycle_1.Disposable));
exports.Gesture = Gesture;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[249/*vs/base/browser/ui/list/rowCache*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/]), function (require, exports, dom_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function removeFromParent(element) {
try {
if (element.parentElement) {
element.parentElement.removeChild(element);
}
}
catch (e) {
// this will throw if this happens due to a blur event, nasty business
}
}
var RowCache = /** @class */ (function () {
function RowCache(renderers) {
this.renderers = renderers;
this.cache = new Map();
}
/**
* Returns a row either by creating a new one or reusing
* a previously released row which shares the same templateId.
*/
RowCache.prototype.alloc = function (templateId) {
var result = this.getTemplateCache(templateId).pop();
if (!result) {
var domNode = dom_1.$('.monaco-list-row');
var renderer = this.getRenderer(templateId);
var templateData = renderer.renderTemplate(domNode);
result = { domNode: domNode, templateId: templateId, templateData: templateData };
}
return result;
};
/**
* Releases the row for eventual reuse.
*/
RowCache.prototype.release = function (row) {
if (!row) {
return;
}
this.releaseRow(row);
};
RowCache.prototype.releaseRow = function (row) {
var domNode = row.domNode, templateId = row.templateId;
if (domNode) {
dom_1.removeClass(domNode, 'scrolling');
removeFromParent(domNode);
}
var cache = this.getTemplateCache(templateId);
cache.push(row);
};
RowCache.prototype.getTemplateCache = function (templateId) {
var result = this.cache.get(templateId);
if (!result) {
result = [];
this.cache.set(templateId, result);
}
return result;
};
RowCache.prototype.dispose = function () {
var _this = this;
this.cache.forEach(function (cachedRows, templateId) {
for (var _i = 0, cachedRows_1 = cachedRows; _i < cachedRows_1.length; _i++) {
var cachedRow = cachedRows_1[_i];
var renderer = _this.getRenderer(templateId);
renderer.disposeTemplate(cachedRow.templateData);
cachedRow.domNode = null;
cachedRow.templateData = null;
}
});
this.cache.clear();
};
RowCache.prototype.getRenderer = function (templateId) {
var renderer = this.renderers.get(templateId);
if (!renderer) {
throw new Error("No renderer found for " + templateId);
}
return renderer;
};
return RowCache;
}());
exports.RowCache = RowCache;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[47/*vs/base/browser/ui/widget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,56/*vs/base/browser/keyboardEvent*/,45/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/,57/*vs/base/browser/touch*/]), function (require, exports, dom, keyboardEvent_1, mouseEvent_1, lifecycle_1, touch_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Widget = /** @class */ (function (_super) {
__extends(Widget, _super);
function Widget() {
return _super !== null && _super.apply(this, arguments) || this;
}
Widget.prototype.onclick = function (domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.CLICK, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); }));
};
Widget.prototype.onmousedown = function (domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_DOWN, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); }));
};
Widget.prototype.onmouseover = function (domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_OVER, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); }));
};
Widget.prototype.onnonbubblingmouseout = function (domNode, listener) {
this._register(dom.addDisposableNonBubblingMouseOutListener(domNode, function (e) { return listener(new mouseEvent_1.StandardMouseEvent(e)); }));
};
Widget.prototype.onkeydown = function (domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, function (e) { return listener(new keyboardEvent_1.StandardKeyboardEvent(e)); }));
};
Widget.prototype.onkeyup = function (domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_UP, function (e) { return listener(new keyboardEvent_1.StandardKeyboardEvent(e)); }));
};
Widget.prototype.oninput = function (domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.INPUT, listener));
};
Widget.prototype.onblur = function (domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.BLUR, listener));
};
Widget.prototype.onfocus = function (domNode, listener) {
this._register(dom.addDisposableListener(domNode, dom.EventType.FOCUS, listener));
};
Widget.prototype.ignoreGesture = function (domNode) {
touch_1.Gesture.ignoreTarget(domNode);
};
return Widget;
}(lifecycle_1.Disposable));
exports.Widget = Widget;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[135/*vs/base/browser/ui/scrollbar/scrollbarArrow*/], __M([0/*require*/,1/*exports*/,78/*vs/base/browser/globalMouseMoveMonitor*/,47/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/]), function (require, exports, globalMouseMoveMonitor_1, widget_1, async_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* The arrow image size.
*/
exports.ARROW_IMG_SIZE = 11;
var ScrollbarArrow = /** @class */ (function (_super) {
__extends(ScrollbarArrow, _super);
function ScrollbarArrow(opts) {
var _this = _super.call(this) || this;
_this._onActivate = opts.onActivate;
_this.bgDomNode = document.createElement('div');
_this.bgDomNode.className = 'arrow-background';
_this.bgDomNode.style.position = 'absolute';
_this.bgDomNode.style.width = opts.bgWidth + 'px';
_this.bgDomNode.style.height = opts.bgHeight + 'px';
if (typeof opts.top !== 'undefined') {
_this.bgDomNode.style.top = '0px';
}
if (typeof opts.left !== 'undefined') {
_this.bgDomNode.style.left = '0px';
}
if (typeof opts.bottom !== 'undefined') {
_this.bgDomNode.style.bottom = '0px';
}
if (typeof opts.right !== 'undefined') {
_this.bgDomNode.style.right = '0px';
}
_this.domNode = document.createElement('div');
_this.domNode.className = opts.className;
_this.domNode.style.position = 'absolute';
_this.domNode.style.width = exports.ARROW_IMG_SIZE + 'px';
_this.domNode.style.height = exports.ARROW_IMG_SIZE + 'px';
if (typeof opts.top !== 'undefined') {
_this.domNode.style.top = opts.top + 'px';
}
if (typeof opts.left !== 'undefined') {
_this.domNode.style.left = opts.left + 'px';
}
if (typeof opts.bottom !== 'undefined') {
_this.domNode.style.bottom = opts.bottom + 'px';
}
if (typeof opts.right !== 'undefined') {
_this.domNode.style.right = opts.right + 'px';
}
_this._mouseMoveMonitor = _this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor());
_this.onmousedown(_this.bgDomNode, function (e) { return _this._arrowMouseDown(e); });
_this.onmousedown(_this.domNode, function (e) { return _this._arrowMouseDown(e); });
_this._mousedownRepeatTimer = _this._register(new async_1.IntervalTimer());
_this._mousedownScheduleRepeatTimer = _this._register(new async_1.TimeoutTimer());
return _this;
}
ScrollbarArrow.prototype._arrowMouseDown = function (e) {
var _this = this;
var scheduleRepeater = function () {
_this._mousedownRepeatTimer.cancelAndSet(function () { return _this._onActivate(); }, 1000 / 24);
};
this._onActivate();
this._mousedownRepeatTimer.cancel();
this._mousedownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200);
this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, function (mouseMoveData) {
/* Intentional empty */
}, function () {
_this._mousedownRepeatTimer.cancel();
_this._mousedownScheduleRepeatTimer.cancel();
});
e.preventDefault();
};
return ScrollbarArrow;
}(widget_1.Widget));
exports.ScrollbarArrow = ScrollbarArrow;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[181/*vs/base/browser/ui/scrollbar/abstractScrollbar*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,78/*vs/base/browser/globalMouseMoveMonitor*/,135/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,244/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/,47/*vs/base/browser/ui/widget*/,16/*vs/base/common/platform*/]), function (require, exports, dom, fastDomNode_1, globalMouseMoveMonitor_1, scrollbarArrow_1, scrollbarVisibilityController_1, widget_1, platform) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* The orthogonal distance to the slider at which dragging "resets". This implements "snapping"
*/
var MOUSE_DRAG_RESET_DISTANCE = 140;
var AbstractScrollbar = /** @class */ (function (_super) {
__extends(AbstractScrollbar, _super);
function AbstractScrollbar(opts) {
var _this = _super.call(this) || this;
_this._lazyRender = opts.lazyRender;
_this._host = opts.host;
_this._scrollable = opts.scrollable;
_this._scrollbarState = opts.scrollbarState;
_this._visibilityController = _this._register(new scrollbarVisibilityController_1.ScrollbarVisibilityController(opts.visibility, 'visible scrollbar ' + opts.extraScrollbarClassName, 'invisible scrollbar ' + opts.extraScrollbarClassName));
_this._visibilityController.setIsNeeded(_this._scrollbarState.isNeeded());
_this._mouseMoveMonitor = _this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor());
_this._shouldRender = true;
_this.domNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
_this.domNode.setAttribute('role', 'presentation');
_this.domNode.setAttribute('aria-hidden', 'true');
_this._visibilityController.setDomNode(_this.domNode);
_this.domNode.setPosition('absolute');
_this.onmousedown(_this.domNode.domNode, function (e) { return _this._domNodeMouseDown(e); });
return _this;
}
// ----------------- creation
/**
* Creates the dom node for an arrow & adds it to the container
*/
AbstractScrollbar.prototype._createArrow = function (opts) {
var arrow = this._register(new scrollbarArrow_1.ScrollbarArrow(opts));
this.domNode.domNode.appendChild(arrow.bgDomNode);
this.domNode.domNode.appendChild(arrow.domNode);
};
/**
* Creates the slider dom node, adds it to the container & hooks up the events
*/
AbstractScrollbar.prototype._createSlider = function (top, left, width, height) {
var _this = this;
this.slider = fastDomNode_1.createFastDomNode(document.createElement('div'));
this.slider.setClassName('slider');
this.slider.setPosition('absolute');
this.slider.setTop(top);
this.slider.setLeft(left);
if (typeof width === 'number') {
this.slider.setWidth(width);
}
if (typeof height === 'number') {
this.slider.setHeight(height);
}
this.slider.setLayerHinting(true);
this.slider.setContain('strict');
this.domNode.domNode.appendChild(this.slider.domNode);
this.onmousedown(this.slider.domNode, function (e) {
if (e.leftButton) {
e.preventDefault();
_this._sliderMouseDown(e, function () { });
}
});
this.onclick(this.slider.domNode, function (e) {
if (e.leftButton) {
e.stopPropagation();
}
});
};
// ----------------- Update state
AbstractScrollbar.prototype._onElementSize = function (visibleSize) {
if (this._scrollbarState.setVisibleSize(visibleSize)) {
this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
this._shouldRender = true;
if (!this._lazyRender) {
this.render();
}
}
return this._shouldRender;
};
AbstractScrollbar.prototype._onElementScrollSize = function (elementScrollSize) {
if (this._scrollbarState.setScrollSize(elementScrollSize)) {
this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
this._shouldRender = true;
if (!this._lazyRender) {
this.render();
}
}
return this._shouldRender;
};
AbstractScrollbar.prototype._onElementScrollPosition = function (elementScrollPosition) {
if (this._scrollbarState.setScrollPosition(elementScrollPosition)) {
this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
this._shouldRender = true;
if (!this._lazyRender) {
this.render();
}
}
return this._shouldRender;
};
// ----------------- rendering
AbstractScrollbar.prototype.beginReveal = function () {
this._visibilityController.setShouldBeVisible(true);
};
AbstractScrollbar.prototype.beginHide = function () {
this._visibilityController.setShouldBeVisible(false);
};
AbstractScrollbar.prototype.render = function () {
if (!this._shouldRender) {
return;
}
this._shouldRender = false;
this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize());
this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition());
};
// ----------------- DOM events
AbstractScrollbar.prototype._domNodeMouseDown = function (e) {
if (e.target !== this.domNode.domNode) {
return;
}
this._onMouseDown(e);
};
AbstractScrollbar.prototype.delegateMouseDown = function (e) {
var domTop = this.domNode.domNode.getClientRects()[0].top;
var sliderStart = domTop + this._scrollbarState.getSliderPosition();
var sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize();
var mousePos = this._sliderMousePosition(e);
if (sliderStart <= mousePos && mousePos <= sliderStop) {
// Act as if it was a mouse down on the slider
if (e.leftButton) {
e.preventDefault();
this._sliderMouseDown(e, function () { });
}
}
else {
// Act as if it was a mouse down on the scrollbar
this._onMouseDown(e);
}
};
AbstractScrollbar.prototype._onMouseDown = function (e) {
var offsetX;
var offsetY;
if (e.target === this.domNode.domNode && typeof e.browserEvent.offsetX === 'number' && typeof e.browserEvent.offsetY === 'number') {
offsetX = e.browserEvent.offsetX;
offsetY = e.browserEvent.offsetY;
}
else {
var domNodePosition = dom.getDomNodePagePosition(this.domNode.domNode);
offsetX = e.posx - domNodePosition.left;
offsetY = e.posy - domNodePosition.top;
}
this._setDesiredScrollPositionNow(this._scrollbarState.getDesiredScrollPositionFromOffset(this._mouseDownRelativePosition(offsetX, offsetY)));
if (e.leftButton) {
e.preventDefault();
this._sliderMouseDown(e, function () { });
}
};
AbstractScrollbar.prototype._sliderMouseDown = function (e, onDragFinished) {
var _this = this;
var initialMousePosition = this._sliderMousePosition(e);
var initialMouseOrthogonalPosition = this._sliderOrthogonalMousePosition(e);
var initialScrollbarState = this._scrollbarState.clone();
this.slider.toggleClassName('active', true);
this._mouseMoveMonitor.startMonitoring(e.target, e.buttons, globalMouseMoveMonitor_1.standardMouseMoveMerger, function (mouseMoveData) {
var mouseOrthogonalPosition = _this._sliderOrthogonalMousePosition(mouseMoveData);
var mouseOrthogonalDelta = Math.abs(mouseOrthogonalPosition - initialMouseOrthogonalPosition);
if (platform.isWindows && mouseOrthogonalDelta > MOUSE_DRAG_RESET_DISTANCE) {
// The mouse has wondered away from the scrollbar => reset dragging
_this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition());
return;
}
var mousePosition = _this._sliderMousePosition(mouseMoveData);
var mouseDelta = mousePosition - initialMousePosition;
_this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(mouseDelta));
}, function () {
_this.slider.toggleClassName('active', false);
_this._host.onDragEnd();
onDragFinished();
});
this._host.onDragStart();
};
AbstractScrollbar.prototype._setDesiredScrollPositionNow = function (_desiredScrollPosition) {
var desiredScrollPosition = {};
this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition);
this._scrollable.setScrollPositionNow(desiredScrollPosition);
};
return AbstractScrollbar;
}(widget_1.Widget));
exports.AbstractScrollbar = AbstractScrollbar;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[250/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/], __M([0/*require*/,1/*exports*/,45/*vs/base/browser/mouseEvent*/,181/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,135/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,175/*vs/base/browser/ui/scrollbar/scrollbarState*/]), function (require, exports, mouseEvent_1, abstractScrollbar_1, scrollbarArrow_1, scrollbarState_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var HorizontalScrollbar = /** @class */ (function (_super) {
__extends(HorizontalScrollbar, _super);
function HorizontalScrollbar(scrollable, options, host) {
var _this = this;
var scrollDimensions = scrollable.getScrollDimensions();
var scrollPosition = scrollable.getCurrentScrollPosition();
_this = _super.call(this, {
lazyRender: options.lazyRender,
host: host,
scrollbarState: new scrollbarState_1.ScrollbarState((options.horizontalHasArrows ? options.arrowSize : 0), (options.horizontal === 2 /* Hidden */ ? 0 : options.horizontalScrollbarSize), (options.vertical === 2 /* Hidden */ ? 0 : options.verticalScrollbarSize), scrollDimensions.width, scrollDimensions.scrollWidth, scrollPosition.scrollLeft),
visibility: options.horizontal,
extraScrollbarClassName: 'horizontal',
scrollable: scrollable
}) || this;
if (options.horizontalHasArrows) {
var arrowDelta = (options.arrowSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2;
var scrollbarDelta = (options.horizontalScrollbarSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2;
_this._createArrow({
className: 'left-arrow',
top: scrollbarDelta,
left: arrowDelta,
bottom: undefined,
right: undefined,
bgWidth: options.arrowSize,
bgHeight: options.horizontalScrollbarSize,
onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 1, 0)); },
});
_this._createArrow({
className: 'right-arrow',
top: scrollbarDelta,
left: undefined,
bottom: undefined,
right: arrowDelta,
bgWidth: options.arrowSize,
bgHeight: options.horizontalScrollbarSize,
onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, -1, 0)); },
});
}
_this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, undefined, options.horizontalSliderSize);
return _this;
}
HorizontalScrollbar.prototype._updateSlider = function (sliderSize, sliderPosition) {
this.slider.setWidth(sliderSize);
this.slider.setLeft(sliderPosition);
};
HorizontalScrollbar.prototype._renderDomNode = function (largeSize, smallSize) {
this.domNode.setWidth(largeSize);
this.domNode.setHeight(smallSize);
this.domNode.setLeft(0);
this.domNode.setBottom(0);
};
HorizontalScrollbar.prototype.onDidScroll = function (e) {
this._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender;
this._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender;
this._shouldRender = this._onElementSize(e.width) || this._shouldRender;
return this._shouldRender;
};
HorizontalScrollbar.prototype._mouseDownRelativePosition = function (offsetX, offsetY) {
return offsetX;
};
HorizontalScrollbar.prototype._sliderMousePosition = function (e) {
return e.posx;
};
HorizontalScrollbar.prototype._sliderOrthogonalMousePosition = function (e) {
return e.posy;
};
HorizontalScrollbar.prototype.writeScrollPosition = function (target, scrollPosition) {
target.scrollLeft = scrollPosition;
};
return HorizontalScrollbar;
}(abstractScrollbar_1.AbstractScrollbar));
exports.HorizontalScrollbar = HorizontalScrollbar;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[251/*vs/base/browser/ui/scrollbar/verticalScrollbar*/], __M([0/*require*/,1/*exports*/,45/*vs/base/browser/mouseEvent*/,181/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,135/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,175/*vs/base/browser/ui/scrollbar/scrollbarState*/]), function (require, exports, mouseEvent_1, abstractScrollbar_1, scrollbarArrow_1, scrollbarState_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var VerticalScrollbar = /** @class */ (function (_super) {
__extends(VerticalScrollbar, _super);
function VerticalScrollbar(scrollable, options, host) {
var _this = this;
var scrollDimensions = scrollable.getScrollDimensions();
var scrollPosition = scrollable.getCurrentScrollPosition();
_this = _super.call(this, {
lazyRender: options.lazyRender,
host: host,
scrollbarState: new scrollbarState_1.ScrollbarState((options.verticalHasArrows ? options.arrowSize : 0), (options.vertical === 2 /* Hidden */ ? 0 : options.verticalScrollbarSize),
// give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom
0, scrollDimensions.height, scrollDimensions.scrollHeight, scrollPosition.scrollTop),
visibility: options.vertical,
extraScrollbarClassName: 'vertical',
scrollable: scrollable
}) || this;
if (options.verticalHasArrows) {
var arrowDelta = (options.arrowSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2;
var scrollbarDelta = (options.verticalScrollbarSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2;
_this._createArrow({
className: 'up-arrow',
top: arrowDelta,
left: scrollbarDelta,
bottom: undefined,
right: undefined,
bgWidth: options.verticalScrollbarSize,
bgHeight: options.arrowSize,
onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, 1)); },
});
_this._createArrow({
className: 'down-arrow',
top: undefined,
left: scrollbarDelta,
bottom: arrowDelta,
right: undefined,
bgWidth: options.verticalScrollbarSize,
bgHeight: options.arrowSize,
onActivate: function () { return _this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, -1)); },
});
}
_this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, undefined);
return _this;
}
VerticalScrollbar.prototype._updateSlider = function (sliderSize, sliderPosition) {
this.slider.setHeight(sliderSize);
this.slider.setTop(sliderPosition);
};
VerticalScrollbar.prototype._renderDomNode = function (largeSize, smallSize) {
this.domNode.setWidth(smallSize);
this.domNode.setHeight(largeSize);
this.domNode.setRight(0);
this.domNode.setTop(0);
};
VerticalScrollbar.prototype.onDidScroll = function (e) {
this._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender;
this._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender;
this._shouldRender = this._onElementSize(e.height) || this._shouldRender;
return this._shouldRender;
};
VerticalScrollbar.prototype._mouseDownRelativePosition = function (offsetX, offsetY) {
return offsetY;
};
VerticalScrollbar.prototype._sliderMousePosition = function (e) {
return e.posy;
};
VerticalScrollbar.prototype._sliderOrthogonalMousePosition = function (e) {
return e.posx;
};
VerticalScrollbar.prototype.writeScrollPosition = function (target, scrollPosition) {
target.scrollTop = scrollPosition;
};
return VerticalScrollbar;
}(abstractScrollbar_1.AbstractScrollbar));
exports.VerticalScrollbar = VerticalScrollbar;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[39/*vs/base/common/resources*/], __M([0/*require*/,1/*exports*/,177/*vs/base/common/extpath*/,77/*vs/base/common/path*/,25/*vs/base/common/uri*/,5/*vs/base/common/strings*/,46/*vs/base/common/network*/,16/*vs/base/common/platform*/]), function (require, exports, extpath, paths, uri_1, strings_1, network_1, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function hasToIgnoreCase(resource) {
// A file scheme resource is in the same platform as code, so ignore case for non linux platforms
// Resource can be from another platform. Lowering the case as an hack. Should come from File system provider
return resource && resource.scheme === network_1.Schemas.file ? !platform_1.isLinux : true;
}
exports.hasToIgnoreCase = hasToIgnoreCase;
function basenameOrAuthority(resource) {
return basename(resource) || resource.authority;
}
exports.basenameOrAuthority = basenameOrAuthority;
/**
* Tests wheter the two authorities are the same
*/
function isEqualAuthority(a1, a2) {
return a1 === a2 || strings_1.equalsIgnoreCase(a1, a2);
}
exports.isEqualAuthority = isEqualAuthority;
function isEqual(first, second, ignoreCase) {
if (ignoreCase === void 0) { ignoreCase = hasToIgnoreCase(first); }
if (first === second) {
return true;
}
if (!first || !second) {
return false;
}
if (first.scheme !== second.scheme || !isEqualAuthority(first.authority, second.authority)) {
return false;
}
var p1 = first.path || '/', p2 = second.path || '/';
return p1 === p2 || ignoreCase && strings_1.equalsIgnoreCase(p1 || '/', p2 || '/');
}
exports.isEqual = isEqual;
function basename(resource) {
return paths.posix.basename(resource.path);
}
exports.basename = basename;
/**
* Return a URI representing the directory of a URI path.
*
* @param resource The input URI.
* @returns The URI representing the directory of the input URI.
*/
function dirname(resource) {
if (resource.path.length === 0) {
return resource;
}
if (resource.scheme === network_1.Schemas.file) {
return uri_1.URI.file(paths.dirname(originalFSPath(resource)));
}
var dirname = paths.posix.dirname(resource.path);
if (resource.authority && dirname.length && dirname.charCodeAt(0) !== 47 /* Slash */) {
console.error("dirname(\"" + resource.toString + ")) resulted in a relative path");
dirname = '/'; // If a URI contains an authority component, then the path component must either be empty or begin with a CharCode.Slash ("/") character
}
return resource.with({
path: dirname
});
}
exports.dirname = dirname;
/**
* Join a URI path with path fragments and normalizes the resulting path.
*
* @param resource The input URI.
* @param pathFragment The path fragment to add to the URI path.
* @returns The resulting URI.
*/
function joinPath(resource) {
var _a;
var pathFragment = [];
for (var _i = 1; _i < arguments.length; _i++) {
pathFragment[_i - 1] = arguments[_i];
}
var joinedPath;
if (resource.scheme === network_1.Schemas.file) {
joinedPath = uri_1.URI.file(paths.join.apply(paths, __spreadArrays([originalFSPath(resource)], pathFragment))).path;
}
else {
joinedPath = (_a = paths.posix).join.apply(_a, __spreadArrays([resource.path || '/'], pathFragment));
}
return resource.with({
path: joinedPath
});
}
exports.joinPath = joinPath;
/**
* Normalizes the path part of a URI: Resolves `.` and `..` elements with directory names.
*
* @param resource The URI to normalize the path.
* @returns The URI with the normalized path.
*/
function normalizePath(resource) {
if (!resource.path.length) {
return resource;
}
var normalizedPath;
if (resource.scheme === network_1.Schemas.file) {
normalizedPath = uri_1.URI.file(paths.normalize(originalFSPath(resource))).path;
}
else {
normalizedPath = paths.posix.normalize(resource.path);
}
return resource.with({
path: normalizedPath
});
}
exports.normalizePath = normalizePath;
/**
* Returns the fsPath of an URI where the drive letter is not normalized.
* See #56403.
*/
function originalFSPath(uri) {
var value;
var uriPath = uri.path;
if (uri.authority && uriPath.length > 1 && uri.scheme === network_1.Schemas.file) {
// unc path: file://shares/c$/far/boo
value = "//" + uri.authority + uriPath;
}
else if (platform_1.isWindows
&& uriPath.charCodeAt(0) === 47 /* Slash */
&& extpath.isWindowsDriveLetter(uriPath.charCodeAt(1))
&& uriPath.charCodeAt(2) === 58 /* Colon */) {
value = uriPath.substr(1);
}
else {
// other path
value = uriPath;
}
if (platform_1.isWindows) {
value = value.replace(/\//g, '\\');
}
return value;
}
exports.originalFSPath = originalFSPath;
/**
* Returns a relative path between two URIs. If the URIs don't have the same schema or authority, `undefined` is returned.
* The returned relative path always uses forward slashes.
*/
function relativePath(from, to, ignoreCase) {
if (ignoreCase === void 0) { ignoreCase = hasToIgnoreCase(from); }
if (from.scheme !== to.scheme || !isEqualAuthority(from.authority, to.authority)) {
return undefined;
}
if (from.scheme === network_1.Schemas.file) {
var relativePath_1 = paths.relative(from.path, to.path);
return platform_1.isWindows ? extpath.toSlashes(relativePath_1) : relativePath_1;
}
var fromPath = from.path || '/', toPath = to.path || '/';
if (ignoreCase) {
// make casing of fromPath match toPath
var i = 0;
for (var len = Math.min(fromPath.length, toPath.length); i < len; i++) {
if (fromPath.charCodeAt(i) !== toPath.charCodeAt(i)) {
if (fromPath.charAt(i).toLowerCase() !== toPath.charAt(i).toLowerCase()) {
break;
}
}
}
fromPath = toPath.substr(0, i) + fromPath.substr(i);
}
return paths.posix.relative(fromPath, toPath);
}
exports.relativePath = relativePath;
/**
* Data URI related helpers.
*/
var DataUri;
(function (DataUri) {
DataUri.META_DATA_LABEL = 'label';
DataUri.META_DATA_DESCRIPTION = 'description';
DataUri.META_DATA_SIZE = 'size';
DataUri.META_DATA_MIME = 'mime';
function parseMetaData(dataUri) {
var metadata = new Map();
// Given a URI of: data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5...
// the metadata is: size:2313;label:SomeLabel;description:SomeDescription
var meta = dataUri.path.substring(dataUri.path.indexOf(';') + 1, dataUri.path.lastIndexOf(';'));
meta.split(';').forEach(function (property) {
var _a = property.split(':'), key = _a[0], value = _a[1];
if (key && value) {
metadata.set(key, value);
}
});
// Given a URI of: data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5...
// the mime is: image/png
var mime = dataUri.path.substring(0, dataUri.path.indexOf(';'));
if (mime) {
metadata.set(DataUri.META_DATA_MIME, mime);
}
return metadata;
}
DataUri.parseMetaData = parseMetaData;
})(DataUri = exports.DataUri || (exports.DataUri = {}));
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[136/*vs/base/common/labels*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,77/*vs/base/common/path*/,5/*vs/base/common/strings*/,46/*vs/base/common/network*/,16/*vs/base/common/platform*/,39/*vs/base/common/resources*/]), function (require, exports, uri_1, path_1, strings_1, network_1, platform_1, resources_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @deprecated use LabelService instead
*/
function getPathLabel(resource, userHomeProvider, rootProvider) {
if (typeof resource === 'string') {
resource = uri_1.URI.file(resource);
}
// return early if we can resolve a relative path label from the root
if (rootProvider) {
var baseResource = rootProvider.getWorkspaceFolder(resource);
if (baseResource) {
var hasMultipleRoots = rootProvider.getWorkspace().folders.length > 1;
var pathLabel = void 0;
if (resources_1.isEqual(baseResource.uri, resource)) {
pathLabel = ''; // no label if paths are identical
}
else {
pathLabel = resources_1.relativePath(baseResource.uri, resource);
}
if (hasMultipleRoots) {
var rootName = baseResource.name ? baseResource.name : resources_1.basename(baseResource.uri);
pathLabel = pathLabel ? (rootName + ' • ' + pathLabel) : rootName; // always show root basename if there are multiple
}
return pathLabel;
}
}
// return if the resource is neither file:// nor untitled:// and no baseResource was provided
if (resource.scheme !== network_1.Schemas.file && resource.scheme !== network_1.Schemas.untitled) {
return resource.with({ query: null, fragment: null }).toString(true);
}
// convert c:\something => C:\something
if (hasDriveLetter(resource.fsPath)) {
return path_1.normalize(normalizeDriveLetter(resource.fsPath));
}
// normalize and tildify (macOS, Linux only)
var res = path_1.normalize(resource.fsPath);
if (!platform_1.isWindows && userHomeProvider) {
res = tildify(res, userHomeProvider.userHome);
}
return res;
}
exports.getPathLabel = getPathLabel;
function getBaseLabel(resource) {
if (!resource) {
return undefined;
}
if (typeof resource === 'string') {
resource = uri_1.URI.file(resource);
}
var base = resources_1.basename(resource) || (resource.scheme === network_1.Schemas.file ? resource.fsPath : resource.path) /* can be empty string if '/' is passed in */;
// convert c: => C:
if (hasDriveLetter(base)) {
return normalizeDriveLetter(base);
}
return base;
}
exports.getBaseLabel = getBaseLabel;
function hasDriveLetter(path) {
return !!(platform_1.isWindows && path && path[1] === ':');
}
function normalizeDriveLetter(path) {
if (hasDriveLetter(path)) {
return path.charAt(0).toUpperCase() + path.slice(1);
}
return path;
}
exports.normalizeDriveLetter = normalizeDriveLetter;
var normalizedUserHomeCached = Object.create(null);
function tildify(path, userHome) {
if (platform_1.isWindows || !path || !userHome) {
return path; // unsupported
}
// Keep a normalized user home path as cache to prevent accumulated string creation
var normalizedUserHome = normalizedUserHomeCached.original === userHome ? normalizedUserHomeCached.normalized : undefined;
if (!normalizedUserHome) {
normalizedUserHome = "" + strings_1.rtrim(userHome, path_1.posix.sep) + path_1.posix.sep;
normalizedUserHomeCached = { original: userHome, normalized: normalizedUserHome };
}
// Linux: case sensitive, macOS: case insensitive
if (platform_1.isLinux ? strings_1.startsWith(path, normalizedUserHome) : strings_1.startsWithIgnoreCase(path, normalizedUserHome)) {
path = "~/" + path.substr(normalizedUserHome.length);
}
return path;
}
exports.tildify = tildify;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[252/*vs/base/common/mime*/], __M([0/*require*/,1/*exports*/,77/*vs/base/common/path*/,5/*vs/base/common/strings*/,178/*vs/base/common/glob*/,46/*vs/base/common/network*/,39/*vs/base/common/resources*/]), function (require, exports, path_1, strings_1, glob_1, network_1, resources_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MIME_TEXT = 'text/plain';
exports.MIME_UNKNOWN = 'application/unknown';
var registeredAssociations = [];
var nonUserRegisteredAssociations = [];
var userRegisteredAssociations = [];
/**
* Associate a text mime to the registry.
*/
function registerTextMime(association, warnOnOverwrite) {
if (warnOnOverwrite === void 0) { warnOnOverwrite = false; }
// Register
var associationItem = toTextMimeAssociationItem(association);
registeredAssociations.push(associationItem);
if (!associationItem.userConfigured) {
nonUserRegisteredAssociations.push(associationItem);
}
else {
userRegisteredAssociations.push(associationItem);
}
// Check for conflicts unless this is a user configured association
if (warnOnOverwrite && !associationItem.userConfigured) {
registeredAssociations.forEach(function (a) {
if (a.mime === associationItem.mime || a.userConfigured) {
return; // same mime or userConfigured is ok
}
if (associationItem.extension && a.extension === associationItem.extension) {
console.warn("Overwriting extension <<" + associationItem.extension + ">> to now point to mime <<" + associationItem.mime + ">>");
}
if (associationItem.filename && a.filename === associationItem.filename) {
console.warn("Overwriting filename <<" + associationItem.filename + ">> to now point to mime <<" + associationItem.mime + ">>");
}
if (associationItem.filepattern && a.filepattern === associationItem.filepattern) {
console.warn("Overwriting filepattern <<" + associationItem.filepattern + ">> to now point to mime <<" + associationItem.mime + ">>");
}
if (associationItem.firstline && a.firstline === associationItem.firstline) {
console.warn("Overwriting firstline <<" + associationItem.firstline + ">> to now point to mime <<" + associationItem.mime + ">>");
}
});
}
}
exports.registerTextMime = registerTextMime;
function toTextMimeAssociationItem(association) {
return {
id: association.id,
mime: association.mime,
filename: association.filename,
extension: association.extension,
filepattern: association.filepattern,
firstline: association.firstline,
userConfigured: association.userConfigured,
filenameLowercase: association.filename ? association.filename.toLowerCase() : undefined,
extensionLowercase: association.extension ? association.extension.toLowerCase() : undefined,
filepatternLowercase: association.filepattern ? association.filepattern.toLowerCase() : undefined,
filepatternOnPath: association.filepattern ? association.filepattern.indexOf(path_1.posix.sep) >= 0 : false
};
}
/**
* Given a file, return the best matching mime type for it
*/
function guessMimeTypes(resource, firstLine) {
var path;
if (resource) {
switch (resource.scheme) {
case network_1.Schemas.file:
path = resource.fsPath;
break;
case network_1.Schemas.data:
var metadata = resources_1.DataUri.parseMetaData(resource);
path = metadata.get(resources_1.DataUri.META_DATA_LABEL);
break;
default:
path = resource.path;
}
}
if (!path) {
return [exports.MIME_UNKNOWN];
}
path = path.toLowerCase();
var filename = path_1.basename(path);
// 1.) User configured mappings have highest priority
var configuredMime = guessMimeTypeByPath(path, filename, userRegisteredAssociations);
if (configuredMime) {
return [configuredMime, exports.MIME_TEXT];
}
// 2.) Registered mappings have middle priority
var registeredMime = guessMimeTypeByPath(path, filename, nonUserRegisteredAssociations);
if (registeredMime) {
return [registeredMime, exports.MIME_TEXT];
}
// 3.) Firstline has lowest priority
if (firstLine) {
var firstlineMime = guessMimeTypeByFirstline(firstLine);
if (firstlineMime) {
return [firstlineMime, exports.MIME_TEXT];
}
}
return [exports.MIME_UNKNOWN];
}
exports.guessMimeTypes = guessMimeTypes;
function guessMimeTypeByPath(path, filename, associations) {
var filenameMatch = null;
var patternMatch = null;
var extensionMatch = null;
// We want to prioritize associations based on the order they are registered so that the last registered
// association wins over all other. This is for https://github.com/Microsoft/vscode/issues/20074
for (var i = associations.length - 1; i >= 0; i--) {
var association = associations[i];
// First exact name match
if (filename === association.filenameLowercase) {
filenameMatch = association;
break; // take it!
}
// Longest pattern match
if (association.filepattern) {
if (!patternMatch || association.filepattern.length > patternMatch.filepattern.length) {
var target = association.filepatternOnPath ? path : filename; // match on full path if pattern contains path separator
if (glob_1.match(association.filepatternLowercase, target)) {
patternMatch = association;
}
}
}
// Longest extension match
if (association.extension) {
if (!extensionMatch || association.extension.length > extensionMatch.extension.length) {
if (strings_1.endsWith(filename, association.extensionLowercase)) {
extensionMatch = association;
}
}
}
}
// 1.) Exact name match has second highest prio
if (filenameMatch) {
return filenameMatch.mime;
}
// 2.) Match on pattern
if (patternMatch) {
return patternMatch.mime;
}
// 3.) Match on extension comes next
if (extensionMatch) {
return extensionMatch.mime;
}
return null;
}
function guessMimeTypeByFirstline(firstLine) {
if (strings_1.startsWithUTF8BOM(firstLine)) {
firstLine = firstLine.substr(1);
}
if (firstLine.length > 0) {
// We want to prioritize associations based on the order they are registered so that the last registered
// association wins over all other. This is for https://github.com/Microsoft/vscode/issues/20074
for (var i = registeredAssociations.length - 1; i >= 0; i--) {
var association = registeredAssociations[i];
if (!association.firstline) {
continue;
}
var matches = firstLine.match(association.firstline);
if (matches && matches.length > 0) {
return association.mime;
}
}
}
return null;
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[182/*vs/base/common/worker/simpleWorker*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,21/*vs/base/common/types*/]), function (require, exports, errors_1, lifecycle_1, platform_1, types) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var INITIALIZE = '$initialize';
var webWorkerWarningLogged = false;
function logOnceWebWorkerWarning(err) {
if (!platform_1.isWeb) {
// running tests
return;
}
if (!webWorkerWarningLogged) {
webWorkerWarningLogged = true;
console.warn('Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/Microsoft/monaco-editor#faq');
}
console.warn(err.message);
}
exports.logOnceWebWorkerWarning = logOnceWebWorkerWarning;
var SimpleWorkerProtocol = /** @class */ (function () {
function SimpleWorkerProtocol(handler) {
this._workerId = -1;
this._handler = handler;
this._lastSentReq = 0;
this._pendingReplies = Object.create(null);
}
SimpleWorkerProtocol.prototype.setWorkerId = function (workerId) {
this._workerId = workerId;
};
SimpleWorkerProtocol.prototype.sendMessage = function (method, args) {
var _this = this;
var req = String(++this._lastSentReq);
return new Promise(function (resolve, reject) {
_this._pendingReplies[req] = {
resolve: resolve,
reject: reject
};
_this._send({
vsWorker: _this._workerId,
req: req,
method: method,
args: args
});
});
};
SimpleWorkerProtocol.prototype.handleMessage = function (message) {
if (!message || !message.vsWorker) {
return;
}
if (this._workerId !== -1 && message.vsWorker !== this._workerId) {
return;
}
this._handleMessage(message);
};
SimpleWorkerProtocol.prototype._handleMessage = function (msg) {
var _this = this;
if (msg.seq) {
var replyMessage = msg;
if (!this._pendingReplies[replyMessage.seq]) {
console.warn('Got reply to unknown seq');
return;
}
var reply = this._pendingReplies[replyMessage.seq];
delete this._pendingReplies[replyMessage.seq];
if (replyMessage.err) {
var err = replyMessage.err;
if (replyMessage.err.$isError) {
err = new Error();
err.name = replyMessage.err.name;
err.message = replyMessage.err.message;
err.stack = replyMessage.err.stack;
}
reply.reject(err);
return;
}
reply.resolve(replyMessage.res);
return;
}
var requestMessage = msg;
var req = requestMessage.req;
var result = this._handler.handleMessage(requestMessage.method, requestMessage.args);
result.then(function (r) {
_this._send({
vsWorker: _this._workerId,
seq: req,
res: r,
err: undefined
});
}, function (e) {
if (e.detail instanceof Error) {
// Loading errors have a detail property that points to the actual error
e.detail = errors_1.transformErrorForSerialization(e.detail);
}
_this._send({
vsWorker: _this._workerId,
seq: req,
res: undefined,
err: errors_1.transformErrorForSerialization(e)
});
});
};
SimpleWorkerProtocol.prototype._send = function (msg) {
var transfer = [];
if (msg.req) {
var m = msg;
for (var i = 0; i < m.args.length; i++) {
if (m.args[i] instanceof ArrayBuffer) {
transfer.push(m.args[i]);
}
}
}
else {
var m = msg;
if (m.res instanceof ArrayBuffer) {
transfer.push(m.res);
}
}
this._handler.sendMessage(msg, transfer);
};
return SimpleWorkerProtocol;
}());
/**
* Main thread side
*/
var SimpleWorkerClient = /** @class */ (function (_super) {
__extends(SimpleWorkerClient, _super);
function SimpleWorkerClient(workerFactory, moduleId, host) {
var _this = _super.call(this) || this;
var lazyProxyReject = null;
_this._worker = _this._register(workerFactory.create('vs/base/common/worker/simpleWorker', function (msg) {
_this._protocol.handleMessage(msg);
}, function (err) {
// in Firefox, web workers fail lazily :(
// we will reject the proxy
if (lazyProxyReject) {
lazyProxyReject(err);
}
}));
_this._protocol = new SimpleWorkerProtocol({
sendMessage: function (msg, transfer) {
_this._worker.postMessage(msg, transfer);
},
handleMessage: function (method, args) {
if (typeof host[method] !== 'function') {
return Promise.reject(new Error('Missing method ' + method + ' on main thread host.'));
}
try {
return Promise.resolve(host[method].apply(host, args));
}
catch (e) {
return Promise.reject(e);
}
}
});
_this._protocol.setWorkerId(_this._worker.getId());
// Gather loader configuration
var loaderConfiguration = null;
if (typeof self.require !== 'undefined' && typeof self.require.getConfig === 'function') {
// Get the configuration from the Monaco AMD Loader
loaderConfiguration = self.require.getConfig();
}
else if (typeof self.requirejs !== 'undefined') {
// Get the configuration from requirejs
loaderConfiguration = self.requirejs.s.contexts._.config;
}
var hostMethods = types.getAllMethodNames(host);
// Send initialize message
_this._onModuleLoaded = _this._protocol.sendMessage(INITIALIZE, [
_this._worker.getId(),
JSON.parse(JSON.stringify(loaderConfiguration)),
moduleId,
hostMethods,
]);
// Create proxy to loaded code
var proxyMethodRequest = function (method, args) {
return _this._request(method, args);
};
_this._lazyProxy = new Promise(function (resolve, reject) {
lazyProxyReject = reject;
_this._onModuleLoaded.then(function (availableMethods) {
resolve(types.createProxyObject(availableMethods, proxyMethodRequest));
}, function (e) {
reject(e);
_this._onError('Worker failed to load ' + moduleId, e);
});
});
return _this;
}
SimpleWorkerClient.prototype.getProxyObject = function () {
return this._lazyProxy;
};
SimpleWorkerClient.prototype._request = function (method, args) {
var _this = this;
return new Promise(function (resolve, reject) {
_this._onModuleLoaded.then(function () {
_this._protocol.sendMessage(method, args).then(resolve, reject);
}, reject);
});
};
SimpleWorkerClient.prototype._onError = function (message, error) {
console.error(message);
console.info(error);
};
return SimpleWorkerClient;
}(lifecycle_1.Disposable));
exports.SimpleWorkerClient = SimpleWorkerClient;
/**
* Worker side
*/
var SimpleWorkerServer = /** @class */ (function () {
function SimpleWorkerServer(postMessage, requestHandlerFactory) {
var _this = this;
this._requestHandlerFactory = requestHandlerFactory;
this._requestHandler = null;
this._protocol = new SimpleWorkerProtocol({
sendMessage: function (msg, transfer) {
postMessage(msg, transfer);
},
handleMessage: function (method, args) { return _this._handleMessage(method, args); }
});
}
SimpleWorkerServer.prototype.onmessage = function (msg) {
this._protocol.handleMessage(msg);
};
SimpleWorkerServer.prototype._handleMessage = function (method, args) {
if (method === INITIALIZE) {
return this.initialize(args[0], args[1], args[2], args[3]);
}
if (!this._requestHandler || typeof this._requestHandler[method] !== 'function') {
return Promise.reject(new Error('Missing requestHandler or method: ' + method));
}
try {
return Promise.resolve(this._requestHandler[method].apply(this._requestHandler, args));
}
catch (e) {
return Promise.reject(e);
}
};
SimpleWorkerServer.prototype.initialize = function (workerId, loaderConfig, moduleId, hostMethods) {
var _this = this;
this._protocol.setWorkerId(workerId);
var proxyMethodRequest = function (method, args) {
return _this._protocol.sendMessage(method, args);
};
var hostProxy = types.createProxyObject(hostMethods, proxyMethodRequest);
if (this._requestHandlerFactory) {
// static request handler
this._requestHandler = this._requestHandlerFactory(hostProxy);
return Promise.resolve(types.getAllMethodNames(this._requestHandler));
}
if (loaderConfig) {
// Remove 'baseUrl', handling it is beyond scope for now
if (typeof loaderConfig.baseUrl !== 'undefined') {
delete loaderConfig['baseUrl'];
}
if (typeof loaderConfig.paths !== 'undefined') {
if (typeof loaderConfig.paths.vs !== 'undefined') {
delete loaderConfig.paths['vs'];
}
}
// Since this is in a web worker, enable catching errors
loaderConfig.catchError = true;
self.require.config(loaderConfig);
}
return new Promise(function (resolve, reject) {
// Use the global require to be sure to get the global config
self.require([moduleId], function (module) {
_this._requestHandler = module.create(hostProxy);
if (!_this._requestHandler) {
reject(new Error("No RequestHandler!"));
return;
}
resolve(types.getAllMethodNames(_this._requestHandler));
}, reject);
});
};
return SimpleWorkerServer;
}());
exports.SimpleWorkerServer = SimpleWorkerServer;
/**
* Called on the worker side
*/
function create(postMessage) {
return new SimpleWorkerServer(postMessage, null);
}
exports.create = create;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[253/*vs/base/parts/quickopen/browser/quickOpenViewer*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/]), function (require, exports, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DataSource = /** @class */ (function () {
function DataSource(arg) {
this.modelProvider = types_1.isFunction(arg.getModel) ? arg : { getModel: function () { return arg; } };
}
DataSource.prototype.getId = function (tree, element) {
if (!element) {
return null;
}
var model = this.modelProvider.getModel();
return model === element ? '__root__' : model.dataSource.getId(element);
};
DataSource.prototype.hasChildren = function (tree, element) {
var model = this.modelProvider.getModel();
return !!(model && model === element && model.entries.length > 0);
};
DataSource.prototype.getChildren = function (tree, element) {
var model = this.modelProvider.getModel();
return Promise.resolve(model === element ? model.entries : []);
};
DataSource.prototype.getParent = function (tree, element) {
return Promise.resolve(null);
};
return DataSource;
}());
exports.DataSource = DataSource;
var AccessibilityProvider = /** @class */ (function () {
function AccessibilityProvider(modelProvider) {
this.modelProvider = modelProvider;
}
AccessibilityProvider.prototype.getAriaLabel = function (tree, element) {
var model = this.modelProvider.getModel();
return model.accessibilityProvider ? model.accessibilityProvider.getAriaLabel(element) : null;
};
AccessibilityProvider.prototype.getPosInSet = function (tree, element) {
var model = this.modelProvider.getModel();
var i = 0;
if (model.filter) {
for (var _i = 0, _a = model.entries; _i < _a.length; _i++) {
var entry = _a[_i];
if (model.filter.isVisible(entry)) {
i++;
}
if (entry === element) {
break;
}
}
}
else {
i = model.entries.indexOf(element) + 1;
}
return String(i);
};
AccessibilityProvider.prototype.getSetSize = function () {
var model = this.modelProvider.getModel();
var n = 0;
if (model.filter) {
for (var _i = 0, _a = model.entries; _i < _a.length; _i++) {
var entry = _a[_i];
if (model.filter.isVisible(entry)) {
n++;
}
}
}
else {
n = model.entries.length;
}
return String(n);
};
return AccessibilityProvider;
}());
exports.AccessibilityProvider = AccessibilityProvider;
var Filter = /** @class */ (function () {
function Filter(modelProvider) {
this.modelProvider = modelProvider;
}
Filter.prototype.isVisible = function (tree, element) {
var model = this.modelProvider.getModel();
if (!model.filter) {
return true;
}
return model.filter.isVisible(element);
};
return Filter;
}());
exports.Filter = Filter;
var Renderer = /** @class */ (function () {
function Renderer(modelProvider, styles) {
this.modelProvider = modelProvider;
this.styles = styles;
}
Renderer.prototype.updateStyles = function (styles) {
this.styles = styles;
};
Renderer.prototype.getHeight = function (tree, element) {
var model = this.modelProvider.getModel();
return model.renderer.getHeight(element);
};
Renderer.prototype.getTemplateId = function (tree, element) {
var model = this.modelProvider.getModel();
return model.renderer.getTemplateId(element);
};
Renderer.prototype.renderTemplate = function (tree, templateId, container) {
var model = this.modelProvider.getModel();
return model.renderer.renderTemplate(templateId, container, this.styles);
};
Renderer.prototype.renderElement = function (tree, element, templateId, templateData) {
var model = this.modelProvider.getModel();
model.renderer.renderElement(element, templateId, templateData, this.styles);
};
Renderer.prototype.disposeTemplate = function (tree, templateId, templateData) {
var model = this.modelProvider.getModel();
model.renderer.disposeTemplate(templateId, templateData);
};
return Renderer;
}());
exports.Renderer = Renderer;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[254/*vs/base/parts/tree/browser/tree*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ContextMenuEvent = /** @class */ (function () {
function ContextMenuEvent(posx, posy, target) {
this._posx = posx;
this._posy = posy;
this._target = target;
}
ContextMenuEvent.prototype.preventDefault = function () {
// no-op
};
ContextMenuEvent.prototype.stopPropagation = function () {
// no-op
};
Object.defineProperty(ContextMenuEvent.prototype, "target", {
get: function () {
return this._target;
},
enumerable: true,
configurable: true
});
return ContextMenuEvent;
}());
exports.ContextMenuEvent = ContextMenuEvent;
var MouseContextMenuEvent = /** @class */ (function (_super) {
__extends(MouseContextMenuEvent, _super);
function MouseContextMenuEvent(originalEvent) {
var _this = _super.call(this, originalEvent.posx, originalEvent.posy, originalEvent.target) || this;
_this.originalEvent = originalEvent;
return _this;
}
MouseContextMenuEvent.prototype.preventDefault = function () {
this.originalEvent.preventDefault();
};
MouseContextMenuEvent.prototype.stopPropagation = function () {
this.originalEvent.stopPropagation();
};
return MouseContextMenuEvent;
}(ContextMenuEvent));
exports.MouseContextMenuEvent = MouseContextMenuEvent;
var KeyboardContextMenuEvent = /** @class */ (function (_super) {
__extends(KeyboardContextMenuEvent, _super);
function KeyboardContextMenuEvent(posx, posy, originalEvent) {
var _this = _super.call(this, posx, posy, originalEvent.target) || this;
_this.originalEvent = originalEvent;
return _this;
}
KeyboardContextMenuEvent.prototype.preventDefault = function () {
this.originalEvent.preventDefault();
};
KeyboardContextMenuEvent.prototype.stopPropagation = function () {
this.originalEvent.stopPropagation();
};
return KeyboardContextMenuEvent;
}(ContextMenuEvent));
exports.KeyboardContextMenuEvent = KeyboardContextMenuEvent;
});
define(__m[137/*vs/base/parts/tree/browser/treeDefaults*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,10/*vs/base/common/errors*/,6/*vs/base/browser/dom*/,36/*vs/base/common/keyCodes*/]), function (require, exports, platform, errors, dom, keyCodes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var KeybindingDispatcher = /** @class */ (function () {
function KeybindingDispatcher() {
this._arr = [];
}
KeybindingDispatcher.prototype.set = function (keybinding, callback) {
this._arr.push({
keybinding: keyCodes_1.createKeybinding(keybinding, platform.OS),
callback: callback
});
};
KeybindingDispatcher.prototype.dispatch = function (keybinding) {
// Loop from the last to the first to handle overwrites
for (var i = this._arr.length - 1; i >= 0; i--) {
var item = this._arr[i];
if (keybinding.toChord().equals(item.keybinding)) {
return item.callback;
}
}
return null;
};
return KeybindingDispatcher;
}());
exports.KeybindingDispatcher = KeybindingDispatcher;
var DefaultController = /** @class */ (function () {
function DefaultController(options) {
var _this = this;
if (options === void 0) { options = { clickBehavior: 0 /* ON_MOUSE_DOWN */, keyboardSupport: true, openMode: 0 /* SINGLE_CLICK */ }; }
this.options = options;
this.downKeyBindingDispatcher = new KeybindingDispatcher();
this.upKeyBindingDispatcher = new KeybindingDispatcher();
if (typeof options.keyboardSupport !== 'boolean' || options.keyboardSupport) {
this.downKeyBindingDispatcher.set(16 /* UpArrow */, function (t, e) { return _this.onUp(t, e); });
this.downKeyBindingDispatcher.set(18 /* DownArrow */, function (t, e) { return _this.onDown(t, e); });
this.downKeyBindingDispatcher.set(15 /* LeftArrow */, function (t, e) { return _this.onLeft(t, e); });
this.downKeyBindingDispatcher.set(17 /* RightArrow */, function (t, e) { return _this.onRight(t, e); });
if (platform.isMacintosh) {
this.downKeyBindingDispatcher.set(2048 /* CtrlCmd */ | 16 /* UpArrow */, function (t, e) { return _this.onLeft(t, e); });
this.downKeyBindingDispatcher.set(256 /* WinCtrl */ | 44 /* KEY_N */, function (t, e) { return _this.onDown(t, e); });
this.downKeyBindingDispatcher.set(256 /* WinCtrl */ | 46 /* KEY_P */, function (t, e) { return _this.onUp(t, e); });
}
this.downKeyBindingDispatcher.set(11 /* PageUp */, function (t, e) { return _this.onPageUp(t, e); });
this.downKeyBindingDispatcher.set(12 /* PageDown */, function (t, e) { return _this.onPageDown(t, e); });
this.downKeyBindingDispatcher.set(14 /* Home */, function (t, e) { return _this.onHome(t, e); });
this.downKeyBindingDispatcher.set(13 /* End */, function (t, e) { return _this.onEnd(t, e); });
this.downKeyBindingDispatcher.set(10 /* Space */, function (t, e) { return _this.onSpace(t, e); });
this.downKeyBindingDispatcher.set(9 /* Escape */, function (t, e) { return _this.onEscape(t, e); });
this.upKeyBindingDispatcher.set(3 /* Enter */, this.onEnter.bind(this));
this.upKeyBindingDispatcher.set(2048 /* CtrlCmd */ | 3 /* Enter */, this.onEnter.bind(this));
}
}
DefaultController.prototype.onMouseDown = function (tree, element, event, origin) {
if (origin === void 0) { origin = 'mouse'; }
if (this.options.clickBehavior === 0 /* ON_MOUSE_DOWN */ && (event.leftButton || event.middleButton)) {
if (event.target) {
if (event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return false; // Ignore event if target is a form input field (avoids browser specific issues)
}
if (dom.findParentWithClass(event.target, 'scrollbar', 'monaco-tree')) {
return false;
}
if (dom.findParentWithClass(event.target, 'monaco-action-bar', 'row')) { // TODO@Joao not very nice way of checking for the action bar (implicit knowledge)
return false; // Ignore event if target is over an action bar of the row
}
}
// Propagate to onLeftClick now
return this.onLeftClick(tree, element, event, origin);
}
return false;
};
DefaultController.prototype.onClick = function (tree, element, event) {
var isMac = platform.isMacintosh;
// A Ctrl click on the Mac is a context menu event
if (isMac && event.ctrlKey) {
event.preventDefault();
event.stopPropagation();
return false;
}
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return false; // Ignore event if target is a form input field (avoids browser specific issues)
}
if (this.options.clickBehavior === 0 /* ON_MOUSE_DOWN */ && (event.leftButton || event.middleButton)) {
return false; // Already handled by onMouseDown
}
return this.onLeftClick(tree, element, event);
};
DefaultController.prototype.onLeftClick = function (tree, element, eventish, origin) {
if (origin === void 0) { origin = 'mouse'; }
var event = eventish;
var payload = { origin: origin, originalEvent: eventish, didClickOnTwistie: this.isClickOnTwistie(event) };
if (tree.getInput() === element) {
tree.clearFocus(payload);
tree.clearSelection(payload);
}
else {
var isSingleMouseDown = eventish && event.browserEvent && event.browserEvent.type === 'mousedown' && event.browserEvent.detail === 1;
if (!isSingleMouseDown) {
eventish.preventDefault(); // we cannot preventDefault onMouseDown with single click because this would break DND otherwise
}
eventish.stopPropagation();
tree.domFocus();
tree.setSelection([element], payload);
tree.setFocus(element, payload);
if (this.shouldToggleExpansion(element, event, origin)) {
if (tree.isExpanded(element)) {
tree.collapse(element).then(undefined, errors.onUnexpectedError);
}
else {
tree.expand(element).then(undefined, errors.onUnexpectedError);
}
}
}
return true;
};
DefaultController.prototype.shouldToggleExpansion = function (element, event, origin) {
var isDoubleClick = (origin === 'mouse' && event.detail === 2);
return this.openOnSingleClick || isDoubleClick || this.isClickOnTwistie(event);
};
Object.defineProperty(DefaultController.prototype, "openOnSingleClick", {
get: function () {
return this.options.openMode === 0 /* SINGLE_CLICK */;
},
enumerable: true,
configurable: true
});
DefaultController.prototype.isClickOnTwistie = function (event) {
var element = event.target;
if (!dom.hasClass(element, 'content')) {
return false;
}
var twistieStyle = window.getComputedStyle(element, ':before');
if (twistieStyle.backgroundImage === 'none' || twistieStyle.display === 'none') {
return false;
}
var twistieWidth = parseInt(twistieStyle.width) + parseInt(twistieStyle.paddingRight);
return event.browserEvent.offsetX <= twistieWidth;
};
DefaultController.prototype.onContextMenu = function (tree, element, event) {
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return false; // allow context menu on input fields
}
// Prevent native context menu from showing up
if (event) {
event.preventDefault();
event.stopPropagation();
}
return false;
};
DefaultController.prototype.onTap = function (tree, element, event) {
var target = event.initialTarget;
if (target && target.tagName && target.tagName.toLowerCase() === 'input') {
return false; // Ignore event if target is a form input field (avoids browser specific issues)
}
return this.onLeftClick(tree, element, event, 'touch');
};
DefaultController.prototype.onKeyDown = function (tree, event) {
return this.onKey(this.downKeyBindingDispatcher, tree, event);
};
DefaultController.prototype.onKeyUp = function (tree, event) {
return this.onKey(this.upKeyBindingDispatcher, tree, event);
};
DefaultController.prototype.onKey = function (bindings, tree, event) {
var handler = bindings.dispatch(event.toKeybinding());
if (handler) {
// TODO: TS 3.1 upgrade. Why are we checking against void?
if (handler(tree, event)) {
event.preventDefault();
event.stopPropagation();
return true;
}
}
return false;
};
DefaultController.prototype.onUp = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
tree.clearHighlight(payload);
}
else {
tree.focusPrevious(1, payload);
tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError);
}
return true;
};
DefaultController.prototype.onPageUp = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
tree.clearHighlight(payload);
}
else {
tree.focusPreviousPage(payload);
tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError);
}
return true;
};
DefaultController.prototype.onDown = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
tree.clearHighlight(payload);
}
else {
tree.focusNext(1, payload);
tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError);
}
return true;
};
DefaultController.prototype.onPageDown = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
tree.clearHighlight(payload);
}
else {
tree.focusNextPage(payload);
tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError);
}
return true;
};
DefaultController.prototype.onHome = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
tree.clearHighlight(payload);
}
else {
tree.focusFirst(payload);
tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError);
}
return true;
};
DefaultController.prototype.onEnd = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
tree.clearHighlight(payload);
}
else {
tree.focusLast(payload);
tree.reveal(tree.getFocus()).then(undefined, errors.onUnexpectedError);
}
return true;
};
DefaultController.prototype.onLeft = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
tree.clearHighlight(payload);
}
else {
var focus_1 = tree.getFocus();
tree.collapse(focus_1).then(function (didCollapse) {
if (focus_1 && !didCollapse) {
tree.focusParent(payload);
return tree.reveal(tree.getFocus());
}
return undefined;
}).then(undefined, errors.onUnexpectedError);
}
return true;
};
DefaultController.prototype.onRight = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
tree.clearHighlight(payload);
}
else {
var focus_2 = tree.getFocus();
tree.expand(focus_2).then(function (didExpand) {
if (focus_2 && !didExpand) {
tree.focusFirstChild(payload);
return tree.reveal(tree.getFocus());
}
return undefined;
}).then(undefined, errors.onUnexpectedError);
}
return true;
};
DefaultController.prototype.onEnter = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
return false;
}
var focus = tree.getFocus();
if (focus) {
tree.setSelection([focus], payload);
}
return true;
};
DefaultController.prototype.onSpace = function (tree, event) {
if (tree.getHighlight()) {
return false;
}
var focus = tree.getFocus();
if (focus) {
tree.toggleExpansion(focus);
}
return true;
};
DefaultController.prototype.onEscape = function (tree, event) {
var payload = { origin: 'keyboard', originalEvent: event };
if (tree.getHighlight()) {
tree.clearHighlight(payload);
return true;
}
if (tree.getSelection().length) {
tree.clearSelection(payload);
return true;
}
if (tree.getFocus()) {
tree.clearFocus(payload);
return true;
}
return false;
};
return DefaultController;
}());
exports.DefaultController = DefaultController;
var DefaultDragAndDrop = /** @class */ (function () {
function DefaultDragAndDrop() {
}
DefaultDragAndDrop.prototype.getDragURI = function (tree, element) {
return null;
};
DefaultDragAndDrop.prototype.onDragStart = function (tree, data, originalEvent) {
return;
};
DefaultDragAndDrop.prototype.onDragOver = function (tree, data, targetElement, originalEvent) {
return null;
};
DefaultDragAndDrop.prototype.drop = function (tree, data, targetElement, originalEvent) {
return;
};
return DefaultDragAndDrop;
}());
exports.DefaultDragAndDrop = DefaultDragAndDrop;
var DefaultFilter = /** @class */ (function () {
function DefaultFilter() {
}
DefaultFilter.prototype.isVisible = function (tree, element) {
return true;
};
return DefaultFilter;
}());
exports.DefaultFilter = DefaultFilter;
var DefaultAccessibilityProvider = /** @class */ (function () {
function DefaultAccessibilityProvider() {
}
DefaultAccessibilityProvider.prototype.getAriaLabel = function (tree, element) {
return null;
};
return DefaultAccessibilityProvider;
}());
exports.DefaultAccessibilityProvider = DefaultAccessibilityProvider;
var DefaultTreestyler = /** @class */ (function () {
function DefaultTreestyler(styleElement, selectorSuffix) {
this.styleElement = styleElement;
this.selectorSuffix = selectorSuffix;
}
DefaultTreestyler.prototype.style = function (styles) {
var suffix = this.selectorSuffix ? "." + this.selectorSuffix : '';
var content = [];
if (styles.listFocusBackground) {
content.push(".monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { background-color: " + styles.listFocusBackground + "; }");
}
if (styles.listFocusForeground) {
content.push(".monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { color: " + styles.listFocusForeground + "; }");
}
if (styles.listActiveSelectionBackground) {
content.push(".monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: " + styles.listActiveSelectionBackground + "; }");
}
if (styles.listActiveSelectionForeground) {
content.push(".monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { color: " + styles.listActiveSelectionForeground + "; }");
}
if (styles.listFocusAndSelectionBackground) {
content.push("\n\t\t\t\t.monaco-tree-drag-image,\n\t\t\t\t.monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused.selected:not(.highlighted) { background-color: " + styles.listFocusAndSelectionBackground + "; }\n\t\t\t");
}
if (styles.listFocusAndSelectionForeground) {
content.push("\n\t\t\t\t.monaco-tree-drag-image,\n\t\t\t\t.monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused.selected:not(.highlighted) { color: " + styles.listFocusAndSelectionForeground + "; }\n\t\t\t");
}
if (styles.listInactiveSelectionBackground) {
content.push(".monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: " + styles.listInactiveSelectionBackground + "; }");
}
if (styles.listInactiveSelectionForeground) {
content.push(".monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { color: " + styles.listInactiveSelectionForeground + "; }");
}
if (styles.listHoverBackground) {
content.push(".monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { background-color: " + styles.listHoverBackground + "; }");
}
if (styles.listHoverForeground) {
content.push(".monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { color: " + styles.listHoverForeground + "; }");
}
if (styles.listDropBackground) {
content.push("\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-wrapper.drop-target,\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.drop-target { background-color: " + styles.listDropBackground + " !important; color: inherit !important; }\n\t\t\t");
}
if (styles.listFocusOutline) {
content.push("\n\t\t\t\t.monaco-tree-drag-image\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{ border: 1px solid " + styles.listFocusOutline + "; background: #000; }\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row \t\t\t\t\t\t\t\t\t\t\t\t\t\t{ border: 1px solid transparent; }\n\t\t\t\t.monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) \t\t\t\t\t\t{ border: 1px dotted " + styles.listFocusOutline + "; }\n\t\t\t\t.monaco-tree" + suffix + ".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) \t\t\t\t\t\t{ border: 1px solid " + styles.listFocusOutline + "; }\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) \t\t\t\t\t\t\t{ border: 1px solid " + styles.listFocusOutline + "; }\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) \t{ border: 1px dashed " + styles.listFocusOutline + "; }\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-wrapper.drop-target,\n\t\t\t\t.monaco-tree" + suffix + " .monaco-tree-rows > .monaco-tree-row.drop-target\t\t\t\t\t\t\t\t\t\t\t\t{ border: 1px dashed " + styles.listFocusOutline + "; }\n\t\t\t");
}
var newStyles = content.join('\n');
if (newStyles !== this.styleElement.innerHTML) {
this.styleElement.innerHTML = newStyles;
}
};
return DefaultTreestyler;
}());
exports.DefaultTreestyler = DefaultTreestyler;
});
define(__m[255/*vs/base/parts/tree/browser/treeDnd*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ElementsDragAndDropData = /** @class */ (function () {
function ElementsDragAndDropData(elements) {
this.elements = elements;
}
ElementsDragAndDropData.prototype.update = function (dataTransfer) {
// no-op
};
ElementsDragAndDropData.prototype.getData = function () {
return this.elements;
};
return ElementsDragAndDropData;
}());
exports.ElementsDragAndDropData = ElementsDragAndDropData;
var ExternalElementsDragAndDropData = /** @class */ (function () {
function ExternalElementsDragAndDropData(elements) {
this.elements = elements;
}
ExternalElementsDragAndDropData.prototype.update = function (dataTransfer) {
// no-op
};
ExternalElementsDragAndDropData.prototype.getData = function () {
return this.elements;
};
return ExternalElementsDragAndDropData;
}());
exports.ExternalElementsDragAndDropData = ExternalElementsDragAndDropData;
var DesktopDragAndDropData = /** @class */ (function () {
function DesktopDragAndDropData() {
this.types = [];
this.files = [];
}
DesktopDragAndDropData.prototype.update = function (dataTransfer) {
if (dataTransfer.types) {
this.types = [];
Array.prototype.push.apply(this.types, dataTransfer.types);
}
if (dataTransfer.files) {
this.files = [];
Array.prototype.push.apply(this.files, dataTransfer.files);
this.files = this.files.filter(function (f) { return f.size || f.type; });
}
};
DesktopDragAndDropData.prototype.getData = function () {
return {
types: this.types,
files: this.files
};
};
return DesktopDragAndDropData;
}());
exports.DesktopDragAndDropData = DesktopDragAndDropData;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[256/*vs/base/parts/tree/browser/treeModel*/], __M([0/*require*/,1/*exports*/,124/*vs/base/common/assert*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/]), function (require, exports, Assert, errors_1, lifecycle_1, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LockData = /** @class */ (function () {
function LockData(item) {
this._onDispose = new event_1.Emitter();
this.onDispose = this._onDispose.event;
this._item = item;
}
Object.defineProperty(LockData.prototype, "item", {
get: function () {
return this._item;
},
enumerable: true,
configurable: true
});
LockData.prototype.dispose = function () {
if (this._onDispose) {
this._onDispose.fire();
this._onDispose.dispose();
this._onDispose = undefined;
}
};
return LockData;
}());
exports.LockData = LockData;
var Lock = /** @class */ (function () {
function Lock() {
this.locks = Object.create({});
}
Lock.prototype.isLocked = function (item) {
return !!this.locks[item.id];
};
Lock.prototype.run = function (item, fn) {
var _this = this;
var lock = this.getLock(item);
if (lock) {
return new Promise(function (c, e) {
event_1.Event.once(lock.onDispose)(function () {
return _this.run(item, fn).then(c, e);
});
});
}
var result;
return new Promise(function (c, e) {
if (item.isDisposed()) {
return e(new Error('Item is disposed.'));
}
var lock = _this.locks[item.id] = new LockData(item);
result = fn().then(function (r) {
delete _this.locks[item.id];
lock.dispose();
return r;
}).then(c, e);
return result;
});
};
Lock.prototype.getLock = function (item) {
var key;
for (key in this.locks) {
var lock = this.locks[key];
if (item.intersects(lock.item)) {
return lock;
}
}
return null;
};
return Lock;
}());
exports.Lock = Lock;
var ItemRegistry = /** @class */ (function () {
function ItemRegistry() {
this._isDisposed = false;
this._onDidRevealItem = new event_1.EventMultiplexer();
this.onDidRevealItem = this._onDidRevealItem.event;
this._onExpandItem = new event_1.EventMultiplexer();
this.onExpandItem = this._onExpandItem.event;
this._onDidExpandItem = new event_1.EventMultiplexer();
this.onDidExpandItem = this._onDidExpandItem.event;
this._onCollapseItem = new event_1.EventMultiplexer();
this.onCollapseItem = this._onCollapseItem.event;
this._onDidCollapseItem = new event_1.EventMultiplexer();
this.onDidCollapseItem = this._onDidCollapseItem.event;
this._onDidAddTraitItem = new event_1.EventMultiplexer();
this.onDidAddTraitItem = this._onDidAddTraitItem.event;
this._onDidRemoveTraitItem = new event_1.EventMultiplexer();
this.onDidRemoveTraitItem = this._onDidRemoveTraitItem.event;
this._onDidRefreshItem = new event_1.EventMultiplexer();
this.onDidRefreshItem = this._onDidRefreshItem.event;
this._onRefreshItemChildren = new event_1.EventMultiplexer();
this.onRefreshItemChildren = this._onRefreshItemChildren.event;
this._onDidRefreshItemChildren = new event_1.EventMultiplexer();
this.onDidRefreshItemChildren = this._onDidRefreshItemChildren.event;
this._onDidDisposeItem = new event_1.EventMultiplexer();
this.onDidDisposeItem = this._onDidDisposeItem.event;
this.items = {};
}
ItemRegistry.prototype.register = function (item) {
Assert.ok(!this.isRegistered(item.id), 'item already registered: ' + item.id);
var disposable = lifecycle_1.combinedDisposable(this._onDidRevealItem.add(item.onDidReveal), this._onExpandItem.add(item.onExpand), this._onDidExpandItem.add(item.onDidExpand), this._onCollapseItem.add(item.onCollapse), this._onDidCollapseItem.add(item.onDidCollapse), this._onDidAddTraitItem.add(item.onDidAddTrait), this._onDidRemoveTraitItem.add(item.onDidRemoveTrait), this._onDidRefreshItem.add(item.onDidRefresh), this._onRefreshItemChildren.add(item.onRefreshChildren), this._onDidRefreshItemChildren.add(item.onDidRefreshChildren), this._onDidDisposeItem.add(item.onDidDispose));
this.items[item.id] = { item: item, disposable: disposable };
};
ItemRegistry.prototype.deregister = function (item) {
Assert.ok(this.isRegistered(item.id), 'item not registered: ' + item.id);
this.items[item.id].disposable.dispose();
delete this.items[item.id];
};
ItemRegistry.prototype.isRegistered = function (id) {
return this.items.hasOwnProperty(id);
};
ItemRegistry.prototype.getItem = function (id) {
var result = this.items[id];
return result ? result.item : null;
};
ItemRegistry.prototype.dispose = function () {
this.items = {};
this._onDidRevealItem.dispose();
this._onExpandItem.dispose();
this._onDidExpandItem.dispose();
this._onCollapseItem.dispose();
this._onDidCollapseItem.dispose();
this._onDidAddTraitItem.dispose();
this._onDidRemoveTraitItem.dispose();
this._onDidRefreshItem.dispose();
this._onRefreshItemChildren.dispose();
this._onDidRefreshItemChildren.dispose();
this._isDisposed = true;
};
ItemRegistry.prototype.isDisposed = function () {
return this._isDisposed;
};
return ItemRegistry;
}());
exports.ItemRegistry = ItemRegistry;
var Item = /** @class */ (function () {
function Item(id, registry, context, lock, element) {
this._onDidCreate = new event_1.Emitter();
this._onDidReveal = new event_1.Emitter();
this.onDidReveal = this._onDidReveal.event;
this._onExpand = new event_1.Emitter();
this.onExpand = this._onExpand.event;
this._onDidExpand = new event_1.Emitter();
this.onDidExpand = this._onDidExpand.event;
this._onCollapse = new event_1.Emitter();
this.onCollapse = this._onCollapse.event;
this._onDidCollapse = new event_1.Emitter();
this.onDidCollapse = this._onDidCollapse.event;
this._onDidAddTrait = new event_1.Emitter();
this.onDidAddTrait = this._onDidAddTrait.event;
this._onDidRemoveTrait = new event_1.Emitter();
this.onDidRemoveTrait = this._onDidRemoveTrait.event;
this._onDidRefresh = new event_1.Emitter();
this.onDidRefresh = this._onDidRefresh.event;
this._onRefreshChildren = new event_1.Emitter();
this.onRefreshChildren = this._onRefreshChildren.event;
this._onDidRefreshChildren = new event_1.Emitter();
this.onDidRefreshChildren = this._onDidRefreshChildren.event;
this._onDidDispose = new event_1.Emitter();
this.onDidDispose = this._onDidDispose.event;
this.registry = registry;
this.context = context;
this.lock = lock;
this.element = element;
this.id = id;
this.registry.register(this);
this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element);
this.needsChildrenRefresh = true;
this.parent = null;
this.previous = null;
this.next = null;
this.firstChild = null;
this.lastChild = null;
this.traits = {};
this.depth = 0;
this.expanded = !!(this.context.dataSource.shouldAutoexpand && this.context.dataSource.shouldAutoexpand(this.context.tree, element));
this._onDidCreate.fire(this);
this.visible = this._isVisible();
this.height = this._getHeight();
this._isDisposed = false;
}
Item.prototype.getElement = function () {
return this.element;
};
Item.prototype.hasChildren = function () {
return this.doesHaveChildren;
};
Item.prototype.getDepth = function () {
return this.depth;
};
Item.prototype.isVisible = function () {
return this.visible;
};
Item.prototype.setVisible = function (value) {
this.visible = value;
};
Item.prototype.isExpanded = function () {
return this.expanded;
};
/* protected */ Item.prototype._setExpanded = function (value) {
this.expanded = value;
};
Item.prototype.reveal = function (relativeTop) {
if (relativeTop === void 0) { relativeTop = null; }
var eventData = { item: this, relativeTop: relativeTop };
this._onDidReveal.fire(eventData);
};
Item.prototype.expand = function () {
var _this = this;
if (this.isExpanded() || !this.doesHaveChildren || this.lock.isLocked(this)) {
return Promise.resolve(false);
}
var result = this.lock.run(this, function () {
if (_this.isExpanded() || !_this.doesHaveChildren) {
return Promise.resolve(false);
}
var eventData = { item: _this };
var result;
_this._onExpand.fire(eventData);
if (_this.needsChildrenRefresh) {
result = _this.refreshChildren(false, true, true);
}
else {
result = Promise.resolve(null);
}
return result.then(function () {
_this._setExpanded(true);
_this._onDidExpand.fire(eventData);
return true;
});
});
return result.then(function (r) {
if (_this.isDisposed()) {
return false;
}
// Auto expand single child folders
if (_this.context.options.autoExpandSingleChildren && r && _this.firstChild !== null && _this.firstChild === _this.lastChild && _this.firstChild.isVisible()) {
return _this.firstChild.expand().then(function () { return true; });
}
return r;
});
};
Item.prototype.collapse = function (recursive) {
var _this = this;
if (recursive === void 0) { recursive = false; }
if (recursive) {
var collapseChildrenPromise_1 = Promise.resolve(null);
this.forEachChild(function (child) {
collapseChildrenPromise_1 = collapseChildrenPromise_1.then(function () { return child.collapse(true); });
});
return collapseChildrenPromise_1.then(function () {
return _this.collapse(false);
});
}
else {
if (!this.isExpanded() || this.lock.isLocked(this)) {
return Promise.resolve(false);
}
return this.lock.run(this, function () {
var eventData = { item: _this };
_this._onCollapse.fire(eventData);
_this._setExpanded(false);
_this._onDidCollapse.fire(eventData);
return Promise.resolve(true);
});
}
};
Item.prototype.addTrait = function (trait) {
var eventData = { item: this, trait: trait };
this.traits[trait] = true;
this._onDidAddTrait.fire(eventData);
};
Item.prototype.removeTrait = function (trait) {
var eventData = { item: this, trait: trait };
delete this.traits[trait];
this._onDidRemoveTrait.fire(eventData);
};
Item.prototype.hasTrait = function (trait) {
return this.traits[trait] || false;
};
Item.prototype.getAllTraits = function () {
var result = [];
var trait;
for (trait in this.traits) {
if (this.traits.hasOwnProperty(trait) && this.traits[trait]) {
result.push(trait);
}
}
return result;
};
Item.prototype.getHeight = function () {
return this.height;
};
Item.prototype.refreshChildren = function (recursive, safe, force) {
var _this = this;
if (safe === void 0) { safe = false; }
if (force === void 0) { force = false; }
if (!force && !this.isExpanded()) {
var setNeedsChildrenRefresh_1 = function (item) {
item.needsChildrenRefresh = true;
item.forEachChild(setNeedsChildrenRefresh_1);
};
setNeedsChildrenRefresh_1(this);
return Promise.resolve(this);
}
this.needsChildrenRefresh = false;
var doRefresh = function () {
var eventData = { item: _this, isNested: safe };
_this._onRefreshChildren.fire(eventData);
var childrenPromise;
if (_this.doesHaveChildren) {
childrenPromise = _this.context.dataSource.getChildren(_this.context.tree, _this.element);
}
else {
childrenPromise = Promise.resolve([]);
}
var result = childrenPromise.then(function (elements) {
if (_this.isDisposed() || _this.registry.isDisposed()) {
return Promise.resolve(null);
}
if (!Array.isArray(elements)) {
return Promise.reject(new Error('Please return an array of children.'));
}
elements = !elements ? [] : elements.slice(0);
elements = _this.sort(elements);
var staleItems = {};
while (_this.firstChild !== null) {
staleItems[_this.firstChild.id] = _this.firstChild;
_this.removeChild(_this.firstChild);
}
for (var i = 0, len = elements.length; i < len; i++) {
var element = elements[i];
var id = _this.context.dataSource.getId(_this.context.tree, element);
var item = staleItems[id] || new Item(id, _this.registry, _this.context, _this.lock, element);
item.element = element;
if (recursive) {
item.needsChildrenRefresh = recursive;
}
delete staleItems[id];
_this.addChild(item);
}
for (var staleItemId in staleItems) {
if (staleItems.hasOwnProperty(staleItemId)) {
staleItems[staleItemId].dispose();
}
}
if (recursive) {
return Promise.all(_this.mapEachChild(function (child) {
return child.doRefresh(recursive, true);
}));
}
else {
return Promise.all(_this.mapEachChild(function (child) {
if (child.isExpanded() && child.needsChildrenRefresh) {
return child.doRefresh(recursive, true);
}
else {
child.updateVisibility();
return Promise.resolve(null);
}
}));
}
});
return result
.then(undefined, errors_1.onUnexpectedError)
.then(function () { return _this._onDidRefreshChildren.fire(eventData); });
};
return safe ? doRefresh() : this.lock.run(this, doRefresh);
};
Item.prototype.doRefresh = function (recursive, safe) {
if (safe === void 0) { safe = false; }
this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element);
this.height = this._getHeight();
this.updateVisibility();
this._onDidRefresh.fire(this);
return this.refreshChildren(recursive, safe);
};
Item.prototype.updateVisibility = function () {
this.setVisible(this._isVisible());
};
Item.prototype.refresh = function (recursive) {
return this.doRefresh(recursive);
};
Item.prototype.getNavigator = function () {
return new TreeNavigator(this);
};
Item.prototype.intersects = function (other) {
return this.isAncestorOf(other) || other.isAncestorOf(this);
};
Item.prototype.isAncestorOf = function (startItem) {
var item = startItem;
while (item) {
if (item.id === this.id) {
return true;
}
item = item.parent;
}
return false;
};
Item.prototype.addChild = function (item, afterItem) {
if (afterItem === void 0) { afterItem = this.lastChild; }
var isEmpty = this.firstChild === null;
var atHead = afterItem === null;
var atTail = afterItem === this.lastChild;
if (isEmpty) {
this.firstChild = this.lastChild = item;
item.next = item.previous = null;
}
else if (atHead) {
if (!this.firstChild) {
throw new Error('Invalid tree state');
}
this.firstChild.previous = item;
item.next = this.firstChild;
item.previous = null;
this.firstChild = item;
}
else if (atTail) {
if (!this.lastChild) {
throw new Error('Invalid tree state');
}
this.lastChild.next = item;
item.next = null;
item.previous = this.lastChild;
this.lastChild = item;
}
else {
item.previous = afterItem;
if (!afterItem) {
throw new Error('Invalid tree state');
}
item.next = afterItem.next;
if (!afterItem.next) {
throw new Error('Invalid tree state');
}
afterItem.next.previous = item;
afterItem.next = item;
}
item.parent = this;
item.depth = this.depth + 1;
};
Item.prototype.removeChild = function (item) {
var isFirstChild = this.firstChild === item;
var isLastChild = this.lastChild === item;
if (isFirstChild && isLastChild) {
this.firstChild = this.lastChild = null;
}
else if (isFirstChild) {
if (!item.next) {
throw new Error('Invalid tree state');
}
item.next.previous = null;
this.firstChild = item.next;
}
else if (isLastChild) {
if (!item.previous) {
throw new Error('Invalid tree state');
}
item.previous.next = null;
this.lastChild = item.previous;
}
else {
if (!item.next) {
throw new Error('Invalid tree state');
}
item.next.previous = item.previous;
if (!item.previous) {
throw new Error('Invalid tree state');
}
item.previous.next = item.next;
}
item.parent = null;
item.depth = NaN;
};
Item.prototype.forEachChild = function (fn) {
var child = this.firstChild;
var next;
while (child) {
next = child.next;
fn(child);
child = next;
}
};
Item.prototype.mapEachChild = function (fn) {
var result = [];
this.forEachChild(function (child) {
result.push(fn(child));
});
return result;
};
Item.prototype.sort = function (elements) {
var _this = this;
var sorter = this.context.sorter;
if (sorter) {
return elements.sort(function (element, otherElement) {
return sorter.compare(_this.context.tree, element, otherElement);
});
}
return elements;
};
/* protected */ Item.prototype._getHeight = function () {
if (!this.context.renderer) {
return 0;
}
return this.context.renderer.getHeight(this.context.tree, this.element);
};
/* protected */ Item.prototype._isVisible = function () {
if (!this.context.filter) {
return false;
}
return this.context.filter.isVisible(this.context.tree, this.element);
};
Item.prototype.isDisposed = function () {
return this._isDisposed;
};
Item.prototype.dispose = function () {
this.forEachChild(function (child) { return child.dispose(); });
this.parent = null;
this.previous = null;
this.next = null;
this.firstChild = null;
this.lastChild = null;
this._onDidDispose.fire(this);
this.registry.deregister(this);
this._onDidCreate.dispose();
this._onDidReveal.dispose();
this._onExpand.dispose();
this._onDidExpand.dispose();
this._onCollapse.dispose();
this._onDidCollapse.dispose();
this._onDidAddTrait.dispose();
this._onDidRemoveTrait.dispose();
this._onDidRefresh.dispose();
this._onRefreshChildren.dispose();
this._onDidRefreshChildren.dispose();
this._onDidDispose.dispose();
this._isDisposed = true;
};
return Item;
}());
exports.Item = Item;
var RootItem = /** @class */ (function (_super) {
__extends(RootItem, _super);
function RootItem(id, registry, context, lock, element) {
return _super.call(this, id, registry, context, lock, element) || this;
}
RootItem.prototype.isVisible = function () {
return false;
};
RootItem.prototype.setVisible = function (value) {
// no-op
};
RootItem.prototype.isExpanded = function () {
return true;
};
/* protected */ RootItem.prototype._setExpanded = function (value) {
// no-op
};
/* protected */ RootItem.prototype._getHeight = function () {
return 0;
};
/* protected */ RootItem.prototype._isVisible = function () {
return false;
};
return RootItem;
}(Item));
var TreeNavigator = /** @class */ (function () {
function TreeNavigator(item, subTreeOnly) {
if (subTreeOnly === void 0) { subTreeOnly = true; }
this.item = item;
this.start = subTreeOnly ? item : null;
}
TreeNavigator.lastDescendantOf = function (item) {
if (!item) {
return null;
}
if (item instanceof RootItem) {
return TreeNavigator.lastDescendantOf(item.lastChild);
}
if (!item.isVisible()) {
return TreeNavigator.lastDescendantOf(item.previous);
}
if (!item.isExpanded() || item.lastChild === null) {
return item;
}
return TreeNavigator.lastDescendantOf(item.lastChild);
};
TreeNavigator.prototype.current = function () {
return this.item || null;
};
TreeNavigator.prototype.next = function () {
if (this.item) {
do {
if ((this.item instanceof RootItem || (this.item.isVisible() && this.item.isExpanded())) && this.item.firstChild) {
this.item = this.item.firstChild;
}
else if (this.item === this.start) {
this.item = null;
}
else {
// select next brother, next uncle, next great-uncle, etc...
while (this.item && this.item !== this.start && !this.item.next) {
this.item = this.item.parent;
}
if (this.item === this.start) {
this.item = null;
}
this.item = !this.item ? null : this.item.next;
}
} while (this.item && !this.item.isVisible());
}
return this.item || null;
};
TreeNavigator.prototype.previous = function () {
if (this.item) {
do {
var previous = TreeNavigator.lastDescendantOf(this.item.previous);
if (previous) {
this.item = previous;
}
else if (this.item.parent && this.item.parent !== this.start && this.item.parent.isVisible()) {
this.item = this.item.parent;
}
else {
this.item = null;
}
} while (this.item && !this.item.isVisible());
}
return this.item || null;
};
TreeNavigator.prototype.parent = function () {
if (this.item) {
var parent_1 = this.item.parent;
if (parent_1 && parent_1 !== this.start && parent_1.isVisible()) {
this.item = parent_1;
}
else {
this.item = null;
}
}
return this.item || null;
};
TreeNavigator.prototype.first = function () {
this.item = this.start;
this.next();
return this.item || null;
};
TreeNavigator.prototype.last = function () {
return TreeNavigator.lastDescendantOf(this.start);
};
return TreeNavigator;
}());
exports.TreeNavigator = TreeNavigator;
var TreeModel = /** @class */ (function () {
function TreeModel(context) {
this.registry = new ItemRegistry();
this.registryDisposable = lifecycle_1.Disposable.None;
this._onSetInput = new event_1.Emitter();
this.onSetInput = this._onSetInput.event;
this._onDidSetInput = new event_1.Emitter();
this.onDidSetInput = this._onDidSetInput.event;
this._onRefresh = new event_1.Emitter();
this.onRefresh = this._onRefresh.event;
this._onDidRefresh = new event_1.Emitter();
this.onDidRefresh = this._onDidRefresh.event;
this._onDidHighlight = new event_1.Emitter();
this.onDidHighlight = this._onDidHighlight.event;
this._onDidSelect = new event_1.Emitter();
this.onDidSelect = this._onDidSelect.event;
this._onDidFocus = new event_1.Emitter();
this.onDidFocus = this._onDidFocus.event;
this._onDidRevealItem = new event_1.Relay();
this.onDidRevealItem = this._onDidRevealItem.event;
this._onExpandItem = new event_1.Relay();
this.onExpandItem = this._onExpandItem.event;
this._onDidExpandItem = new event_1.Relay();
this.onDidExpandItem = this._onDidExpandItem.event;
this._onCollapseItem = new event_1.Relay();
this.onCollapseItem = this._onCollapseItem.event;
this._onDidCollapseItem = new event_1.Relay();
this.onDidCollapseItem = this._onDidCollapseItem.event;
this._onDidAddTraitItem = new event_1.Relay();
this.onDidAddTraitItem = this._onDidAddTraitItem.event;
this._onDidRemoveTraitItem = new event_1.Relay();
this.onDidRemoveTraitItem = this._onDidRemoveTraitItem.event;
this._onDidRefreshItem = new event_1.Relay();
this.onDidRefreshItem = this._onDidRefreshItem.event;
this._onRefreshItemChildren = new event_1.Relay();
this.onRefreshItemChildren = this._onRefreshItemChildren.event;
this._onDidRefreshItemChildren = new event_1.Relay();
this.onDidRefreshItemChildren = this._onDidRefreshItemChildren.event;
this._onDidDisposeItem = new event_1.Relay();
this.context = context;
this.input = null;
this.traitsToItems = {};
}
TreeModel.prototype.setInput = function (element) {
var _this = this;
var eventData = { item: this.input };
this._onSetInput.fire(eventData);
this.setSelection([]);
this.setFocus();
this.setHighlight();
this.lock = new Lock();
if (this.input) {
this.input.dispose();
}
if (this.registry) {
this.registry.dispose();
this.registryDisposable.dispose();
}
this.registry = new ItemRegistry();
this._onDidRevealItem.input = this.registry.onDidRevealItem;
this._onExpandItem.input = this.registry.onExpandItem;
this._onDidExpandItem.input = this.registry.onDidExpandItem;
this._onCollapseItem.input = this.registry.onCollapseItem;
this._onDidCollapseItem.input = this.registry.onDidCollapseItem;
this._onDidAddTraitItem.input = this.registry.onDidAddTraitItem;
this._onDidRemoveTraitItem.input = this.registry.onDidRemoveTraitItem;
this._onDidRefreshItem.input = this.registry.onDidRefreshItem;
this._onRefreshItemChildren.input = this.registry.onRefreshItemChildren;
this._onDidRefreshItemChildren.input = this.registry.onDidRefreshItemChildren;
this._onDidDisposeItem.input = this.registry.onDidDisposeItem;
this.registryDisposable = this.registry
.onDidDisposeItem(function (item) { return item.getAllTraits().forEach(function (trait) { return delete _this.traitsToItems[trait][item.id]; }); });
var id = this.context.dataSource.getId(this.context.tree, element);
this.input = new RootItem(id, this.registry, this.context, this.lock, element);
eventData = { item: this.input };
this._onDidSetInput.fire(eventData);
return this.refresh(this.input);
};
TreeModel.prototype.getInput = function () {
return this.input ? this.input.getElement() : null;
};
TreeModel.prototype.refresh = function (element, recursive) {
var _this = this;
if (element === void 0) { element = null; }
if (recursive === void 0) { recursive = true; }
var item = this.getItem(element);
if (!item) {
return Promise.resolve(null);
}
var eventData = { item: item, recursive: recursive };
this._onRefresh.fire(eventData);
return item.refresh(recursive).then(function () {
_this._onDidRefresh.fire(eventData);
});
};
TreeModel.prototype.expand = function (element) {
var item = this.getItem(element);
if (!item) {
return Promise.resolve(false);
}
return item.expand();
};
TreeModel.prototype.collapse = function (element, recursive) {
if (recursive === void 0) { recursive = false; }
var item = this.getItem(element);
if (!item) {
return Promise.resolve(false);
}
return item.collapse(recursive);
};
TreeModel.prototype.toggleExpansion = function (element, recursive) {
if (recursive === void 0) { recursive = false; }
return this.isExpanded(element) ? this.collapse(element, recursive) : this.expand(element);
};
TreeModel.prototype.isExpanded = function (element) {
var item = this.getItem(element);
if (!item) {
return false;
}
return item.isExpanded();
};
TreeModel.prototype.reveal = function (element, relativeTop) {
var _this = this;
if (relativeTop === void 0) { relativeTop = null; }
return this.resolveUnknownParentChain(element).then(function (chain) {
var result = Promise.resolve(null);
chain.forEach(function (e) {
result = result.then(function () { return _this.expand(e); });
});
return result;
}).then(function () {
var item = _this.getItem(element);
if (item) {
return item.reveal(relativeTop);
}
});
};
TreeModel.prototype.resolveUnknownParentChain = function (element) {
var _this = this;
return this.context.dataSource.getParent(this.context.tree, element).then(function (parent) {
if (!parent) {
return Promise.resolve([]);
}
return _this.resolveUnknownParentChain(parent).then(function (result) {
result.push(parent);
return result;
});
});
};
TreeModel.prototype.setHighlight = function (element, eventPayload) {
this.setTraits('highlighted', element ? [element] : []);
var eventData = { highlight: this.getHighlight(), payload: eventPayload };
this._onDidHighlight.fire(eventData);
};
TreeModel.prototype.getHighlight = function (includeHidden) {
if (includeHidden === void 0) { includeHidden = false; }
var result = this.getElementsWithTrait('highlighted', includeHidden);
return result.length === 0 ? null : result[0];
};
TreeModel.prototype.setSelection = function (elements, eventPayload) {
this.setTraits('selected', elements);
var eventData = { selection: this.getSelection(), payload: eventPayload };
this._onDidSelect.fire(eventData);
};
TreeModel.prototype.getSelection = function (includeHidden) {
if (includeHidden === void 0) { includeHidden = false; }
return this.getElementsWithTrait('selected', includeHidden);
};
TreeModel.prototype.setFocus = function (element, eventPayload) {
this.setTraits('focused', element ? [element] : []);
var eventData = { focus: this.getFocus(), payload: eventPayload };
this._onDidFocus.fire(eventData);
};
TreeModel.prototype.getFocus = function (includeHidden) {
if (includeHidden === void 0) { includeHidden = false; }
var result = this.getElementsWithTrait('focused', includeHidden);
return result.length === 0 ? null : result[0];
};
TreeModel.prototype.focusNext = function (count, eventPayload) {
if (count === void 0) { count = 1; }
var item = this.getFocus() || this.input;
var nextItem;
var nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
nextItem = nav.next();
if (!nextItem) {
break;
}
item = nextItem;
}
this.setFocus(item, eventPayload);
};
TreeModel.prototype.focusPrevious = function (count, eventPayload) {
if (count === void 0) { count = 1; }
var item = this.getFocus() || this.input;
var previousItem;
var nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
previousItem = nav.previous();
if (!previousItem) {
break;
}
item = previousItem;
}
this.setFocus(item, eventPayload);
};
TreeModel.prototype.focusParent = function (eventPayload) {
var item = this.getFocus() || this.input;
var nav = this.getNavigator(item, false);
var parent = nav.parent();
if (parent) {
this.setFocus(parent, eventPayload);
}
};
TreeModel.prototype.focusFirstChild = function (eventPayload) {
var item = this.getItem(this.getFocus() || this.input);
var nav = this.getNavigator(item, false);
var next = nav.next();
var parent = nav.parent();
if (parent === item) {
this.setFocus(next, eventPayload);
}
};
TreeModel.prototype.focusFirst = function (eventPayload, from) {
this.focusNth(0, eventPayload, from);
};
TreeModel.prototype.focusNth = function (index, eventPayload, from) {
var navItem = this.getParent(from);
var nav = this.getNavigator(navItem);
var item = nav.first();
for (var i = 0; i < index; i++) {
item = nav.next();
}
if (item) {
this.setFocus(item, eventPayload);
}
};
TreeModel.prototype.focusLast = function (eventPayload, from) {
var navItem = this.getParent(from);
var item;
if (from && navItem) {
item = navItem.lastChild;
}
else {
var nav = this.getNavigator(navItem);
item = nav.last();
}
if (item) {
this.setFocus(item, eventPayload);
}
};
TreeModel.prototype.getParent = function (from) {
if (from) {
var fromItem = this.getItem(from);
if (fromItem && fromItem.parent) {
return fromItem.parent;
}
}
return this.getItem(this.input);
};
TreeModel.prototype.getNavigator = function (element, subTreeOnly) {
if (element === void 0) { element = null; }
if (subTreeOnly === void 0) { subTreeOnly = true; }
return new TreeNavigator(this.getItem(element), subTreeOnly);
};
TreeModel.prototype.getItem = function (element) {
if (element === void 0) { element = null; }
if (element === null) {
return this.input;
}
else if (element instanceof Item) {
return element;
}
else if (typeof element === 'string') {
return this.registry.getItem(element);
}
else {
return this.registry.getItem(this.context.dataSource.getId(this.context.tree, element));
}
};
TreeModel.prototype.removeTraits = function (trait, elements) {
var items = this.traitsToItems[trait] || {};
var item;
var id;
if (elements.length === 0) {
for (id in items) {
if (items.hasOwnProperty(id)) {
item = items[id];
item.removeTrait(trait);
}
}
delete this.traitsToItems[trait];
}
else {
for (var i = 0, len = elements.length; i < len; i++) {
item = this.getItem(elements[i]);
if (item) {
item.removeTrait(trait);
delete items[item.id];
}
}
}
};
TreeModel.prototype.setTraits = function (trait, elements) {
if (elements.length === 0) {
this.removeTraits(trait, elements);
}
else {
var items = {};
var item = void 0;
for (var i = 0, len = elements.length; i < len; i++) {
item = this.getItem(elements[i]);
if (item) {
items[item.id] = item;
}
}
var traitItems = this.traitsToItems[trait] || {};
var itemsToRemoveTrait = [];
var id = void 0;
for (id in traitItems) {
if (traitItems.hasOwnProperty(id)) {
if (items.hasOwnProperty(id)) {
delete items[id];
}
else {
itemsToRemoveTrait.push(traitItems[id]);
}
}
}
for (var i = 0, len = itemsToRemoveTrait.length; i < len; i++) {
item = itemsToRemoveTrait[i];
item.removeTrait(trait);
delete traitItems[item.id];
}
for (id in items) {
if (items.hasOwnProperty(id)) {
item = items[id];
item.addTrait(trait);
traitItems[id] = item;
}
}
this.traitsToItems[trait] = traitItems;
}
};
TreeModel.prototype.getElementsWithTrait = function (trait, includeHidden) {
var elements = [];
var items = this.traitsToItems[trait] || {};
var id;
for (id in items) {
if (items.hasOwnProperty(id) && (items[id].isVisible() || includeHidden)) {
elements.push(items[id].getElement());
}
}
return elements;
};
TreeModel.prototype.dispose = function () {
this.registry.dispose();
this._onSetInput.dispose();
this._onDidSetInput.dispose();
this._onRefresh.dispose();
this._onDidRefresh.dispose();
this._onDidHighlight.dispose();
this._onDidSelect.dispose();
this._onDidFocus.dispose();
this._onDidRevealItem.dispose();
this._onExpandItem.dispose();
this._onDidExpandItem.dispose();
this._onCollapseItem.dispose();
this._onDidCollapseItem.dispose();
this._onDidAddTraitItem.dispose();
this._onDidRemoveTraitItem.dispose();
this._onDidRefreshItem.dispose();
this._onRefreshItemChildren.dispose();
this._onDidRefreshItemChildren.dispose();
this._onDidDisposeItem.dispose();
};
return TreeModel;
}());
exports.TreeModel = TreeModel;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[257/*vs/base/parts/tree/browser/treeViewModel*/], __M([0/*require*/,1/*exports*/,54/*vs/base/common/iterator*/]), function (require, exports, iterator_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var HeightMap = /** @class */ (function () {
function HeightMap() {
this.heightMap = [];
this.indexes = {};
}
HeightMap.prototype.getContentHeight = function () {
var last = this.heightMap[this.heightMap.length - 1];
return !last ? 0 : last.top + last.height;
};
HeightMap.prototype.onInsertItems = function (iterator, afterItemId) {
if (afterItemId === void 0) { afterItemId = null; }
var item = null;
var viewItem;
var i, j;
var totalSize;
var sizeDiff = 0;
if (afterItemId === null) {
i = 0;
totalSize = 0;
}
else {
i = this.indexes[afterItemId] + 1;
viewItem = this.heightMap[i - 1];
if (!viewItem) {
console.error('view item doesnt exist');
return undefined;
}
totalSize = viewItem.top + viewItem.height;
}
var boundSplice = this.heightMap.splice.bind(this.heightMap, i, 0);
var itemsToInsert = [];
while (item = iterator.next()) {
viewItem = this.createViewItem(item);
viewItem.top = totalSize + sizeDiff;
this.indexes[item.id] = i++;
itemsToInsert.push(viewItem);
sizeDiff += viewItem.height;
}
boundSplice.apply(this.heightMap, itemsToInsert);
for (j = i; j < this.heightMap.length; j++) {
viewItem = this.heightMap[j];
viewItem.top += sizeDiff;
this.indexes[viewItem.model.id] = j;
}
for (j = itemsToInsert.length - 1; j >= 0; j--) {
this.onInsertItem(itemsToInsert[j]);
}
for (j = this.heightMap.length - 1; j >= i; j--) {
this.onRefreshItem(this.heightMap[j]);
}
return sizeDiff;
};
HeightMap.prototype.onInsertItem = function (item) {
// noop
};
// Contiguous items
HeightMap.prototype.onRemoveItems = function (iterator) {
var itemId = null;
var viewItem;
var startIndex = null;
var i = 0;
var sizeDiff = 0;
while (itemId = iterator.next()) {
i = this.indexes[itemId];
viewItem = this.heightMap[i];
if (!viewItem) {
console.error('view item doesnt exist');
return;
}
sizeDiff -= viewItem.height;
delete this.indexes[itemId];
this.onRemoveItem(viewItem);
if (startIndex === null) {
startIndex = i;
}
}
if (sizeDiff === 0 || startIndex === null) {
return;
}
this.heightMap.splice(startIndex, i - startIndex + 1);
for (i = startIndex; i < this.heightMap.length; i++) {
viewItem = this.heightMap[i];
viewItem.top += sizeDiff;
this.indexes[viewItem.model.id] = i;
this.onRefreshItem(viewItem);
}
};
HeightMap.prototype.onRemoveItem = function (item) {
// noop
};
HeightMap.prototype.onRefreshItemSet = function (items) {
var _this = this;
var sortedItems = items.sort(function (a, b) { return _this.indexes[a.id] - _this.indexes[b.id]; });
this.onRefreshItems(new iterator_1.ArrayIterator(sortedItems));
};
// Ordered, but not necessarily contiguous items
HeightMap.prototype.onRefreshItems = function (iterator) {
var item = null;
var viewItem;
var newHeight;
var i, j = null;
var cummDiff = 0;
while (item = iterator.next()) {
i = this.indexes[item.id];
for (; cummDiff !== 0 && j !== null && j < i; j++) {
viewItem = this.heightMap[j];
viewItem.top += cummDiff;
this.onRefreshItem(viewItem);
}
viewItem = this.heightMap[i];
newHeight = item.getHeight();
viewItem.top += cummDiff;
cummDiff += newHeight - viewItem.height;
viewItem.height = newHeight;
this.onRefreshItem(viewItem, true);
j = i + 1;
}
if (cummDiff !== 0 && j !== null) {
for (; j < this.heightMap.length; j++) {
viewItem = this.heightMap[j];
viewItem.top += cummDiff;
this.onRefreshItem(viewItem);
}
}
};
HeightMap.prototype.onRefreshItem = function (item, needsRender) {
if (needsRender === void 0) { needsRender = false; }
// noop
};
HeightMap.prototype.indexAt = function (position) {
var left = 0;
var right = this.heightMap.length;
var center;
var item;
// Binary search
while (left < right) {
center = Math.floor((left + right) / 2);
item = this.heightMap[center];
if (position < item.top) {
right = center;
}
else if (position >= item.top + item.height) {
if (left === center) {
break;
}
left = center;
}
else {
return center;
}
}
return this.heightMap.length;
};
HeightMap.prototype.indexAfter = function (position) {
return Math.min(this.indexAt(position) + 1, this.heightMap.length);
};
HeightMap.prototype.itemAtIndex = function (index) {
return this.heightMap[index];
};
HeightMap.prototype.itemAfter = function (item) {
return this.heightMap[this.indexes[item.model.id] + 1] || null;
};
HeightMap.prototype.createViewItem = function (item) {
throw new Error('not implemented');
};
HeightMap.prototype.dispose = function () {
this.heightMap = [];
this.indexes = {};
};
return HeightMap;
}());
exports.HeightMap = HeightMap;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[258/*vs/base/worker/defaultWorkerFactory*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,182/*vs/base/common/worker/simpleWorker*/]), function (require, exports, platform_1, simpleWorker_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getWorker(workerId, label) {
// Option for hosts to overwrite the worker script (used in the standalone editor)
if (platform_1.globals.MonacoEnvironment) {
if (typeof platform_1.globals.MonacoEnvironment.getWorker === 'function') {
return platform_1.globals.MonacoEnvironment.getWorker(workerId, label);
}
if (typeof platform_1.globals.MonacoEnvironment.getWorkerUrl === 'function') {
return new Worker(platform_1.globals.MonacoEnvironment.getWorkerUrl(workerId, label));
}
}
// ESM-comment-begin
if (typeof require === 'function') {
// check if the JS lives on a different origin
var workerMain = require.toUrl('./' + workerId);
var workerUrl = getWorkerBootstrapUrl(workerMain, label);
return new Worker(workerUrl, { name: label });
}
// ESM-comment-end
throw new Error("You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker");
}
// ESM-comment-begin
function getWorkerBootstrapUrl(scriptPath, label) {
if (/^(http:)|(https:)|(file:)/.test(scriptPath)) {
var currentUrl = String(window.location);
var currentOrigin = currentUrl.substr(0, currentUrl.length - window.location.hash.length - window.location.search.length - window.location.pathname.length);
if (scriptPath.substring(0, currentOrigin.length) !== currentOrigin) {
// this is the cross-origin case
// i.e. the webpage is running at a different origin than where the scripts are loaded from
var myPath = 'vs/base/worker/defaultWorkerFactory.js';
var workerBaseUrl = require.toUrl(myPath).slice(0, -myPath.length);
var js = "/*" + label + "*/self.MonacoEnvironment={baseUrl: '" + workerBaseUrl + "'};importScripts('" + scriptPath + "');/*" + label + "*/";
var url = "data:text/javascript;charset=utf-8," + encodeURIComponent(js);
return url;
}
}
return scriptPath + '#' + label;
}
exports.getWorkerBootstrapUrl = getWorkerBootstrapUrl;
// ESM-comment-end
function isPromiseLike(obj) {
if (typeof obj.then === 'function') {
return true;
}
return false;
}
/**
* A worker that uses HTML5 web workers so that is has
* its own global scope and its own thread.
*/
var WebWorker = /** @class */ (function () {
function WebWorker(moduleId, id, label, onMessageCallback, onErrorCallback) {
this.id = id;
var workerOrPromise = getWorker('workerMain.js', label);
if (isPromiseLike(workerOrPromise)) {
this.worker = workerOrPromise;
}
else {
this.worker = Promise.resolve(workerOrPromise);
}
this.postMessage(moduleId, []);
this.worker.then(function (w) {
w.onmessage = function (ev) {
onMessageCallback(ev.data);
};
w.onmessageerror = onErrorCallback;
if (typeof w.addEventListener === 'function') {
w.addEventListener('error', onErrorCallback);
}
});
}
WebWorker.prototype.getId = function () {
return this.id;
};
WebWorker.prototype.postMessage = function (message, transfer) {
if (this.worker) {
this.worker.then(function (w) { return w.postMessage(message, transfer); });
}
};
WebWorker.prototype.dispose = function () {
if (this.worker) {
this.worker.then(function (w) { return w.terminate(); });
}
this.worker = null;
};
return WebWorker;
}());
var DefaultWorkerFactory = /** @class */ (function () {
function DefaultWorkerFactory(label) {
this._label = label;
this._webWorkerFailedBeforeError = false;
}
DefaultWorkerFactory.prototype.create = function (moduleId, onMessageCallback, onErrorCallback) {
var _this = this;
var workerId = (++DefaultWorkerFactory.LAST_WORKER_ID);
if (this._webWorkerFailedBeforeError) {
throw this._webWorkerFailedBeforeError;
}
return new WebWorker(moduleId, workerId, this._label || 'anonymous' + workerId, onMessageCallback, function (err) {
simpleWorker_1.logOnceWebWorkerWarning(err);
_this._webWorkerFailedBeforeError = err;
onErrorCallback(err);
});
};
DefaultWorkerFactory.LAST_WORKER_ID = 0;
return DefaultWorkerFactory;
}());
exports.DefaultWorkerFactory = DefaultWorkerFactory;
});
define(__m[259/*vs/css!vs/base/browser/ui/actionbar/actionbar*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[260/*vs/css!vs/base/browser/ui/aria/aria*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[261/*vs/css!vs/base/browser/ui/checkbox/checkbox*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[138/*vs/base/browser/ui/checkbox/checkbox*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,47/*vs/base/browser/ui/widget*/,27/*vs/base/common/color*/,4/*vs/base/common/event*/,31/*vs/base/common/objects*/,261/*vs/css!vs/base/browser/ui/checkbox/checkbox*/]), function (require, exports, DOM, widget_1, color_1, event_1, objects) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var defaultOpts = {
inputActiveOptionBorder: color_1.Color.fromHex('#007ACC00'),
inputActiveOptionBackground: color_1.Color.fromHex('#0E639C50')
};
var Checkbox = /** @class */ (function (_super) {
__extends(Checkbox, _super);
function Checkbox(opts) {
var _this = _super.call(this) || this;
_this._onChange = _this._register(new event_1.Emitter());
_this.onChange = _this._onChange.event;
_this._onKeyDown = _this._register(new event_1.Emitter());
_this.onKeyDown = _this._onKeyDown.event;
_this._opts = objects.deepClone(opts);
objects.mixin(_this._opts, defaultOpts, false);
_this._checked = _this._opts.isChecked;
_this.domNode = document.createElement('div');
_this.domNode.title = _this._opts.title;
_this.domNode.className = 'monaco-custom-checkbox codicon ' + (_this._opts.actionClassName || '') + ' ' + (_this._checked ? 'checked' : 'unchecked');
_this.domNode.tabIndex = 0;
_this.domNode.setAttribute('role', 'checkbox');
_this.domNode.setAttribute('aria-checked', String(_this._checked));
_this.domNode.setAttribute('aria-label', _this._opts.title);
_this.applyStyles();
_this.onclick(_this.domNode, function (ev) {
_this.checked = !_this._checked;
_this._onChange.fire(false);
ev.preventDefault();
});
_this.ignoreGesture(_this.domNode);
_this.onkeydown(_this.domNode, function (keyboardEvent) {
if (keyboardEvent.keyCode === 10 /* Space */ || keyboardEvent.keyCode === 3 /* Enter */) {
_this.checked = !_this._checked;
_this._onChange.fire(true);
keyboardEvent.preventDefault();
return;
}
_this._onKeyDown.fire(keyboardEvent);
});
return _this;
}
Object.defineProperty(Checkbox.prototype, "enabled", {
get: function () {
return this.domNode.getAttribute('aria-disabled') !== 'true';
},
enumerable: true,
configurable: true
});
Checkbox.prototype.focus = function () {
this.domNode.focus();
};
Object.defineProperty(Checkbox.prototype, "checked", {
get: function () {
return this._checked;
},
set: function (newIsChecked) {
this._checked = newIsChecked;
this.domNode.setAttribute('aria-checked', String(this._checked));
if (this._checked) {
this.domNode.classList.add('checked');
}
else {
this.domNode.classList.remove('checked');
}
this.applyStyles();
},
enumerable: true,
configurable: true
});
Checkbox.prototype.width = function () {
return 2 /*marginleft*/ + 2 /*border*/ + 2 /*padding*/ + 16 /* icon width */;
};
Checkbox.prototype.style = function (styles) {
if (styles.inputActiveOptionBorder) {
this._opts.inputActiveOptionBorder = styles.inputActiveOptionBorder;
}
if (styles.inputActiveOptionBackground) {
this._opts.inputActiveOptionBackground = styles.inputActiveOptionBackground;
}
this.applyStyles();
};
Checkbox.prototype.applyStyles = function () {
if (this.domNode) {
this.domNode.style.borderColor = this._checked && this._opts.inputActiveOptionBorder ? this._opts.inputActiveOptionBorder.toString() : 'transparent';
this.domNode.style.backgroundColor = this._checked && this._opts.inputActiveOptionBackground ? this._opts.inputActiveOptionBackground.toString() : 'transparent';
}
};
Checkbox.prototype.enable = function () {
this.domNode.tabIndex = 0;
this.domNode.setAttribute('aria-disabled', String(false));
};
Checkbox.prototype.disable = function () {
DOM.removeTabIndexAndUpdateFocus(this.domNode);
this.domNode.setAttribute('aria-disabled', String(true));
};
return Checkbox;
}(widget_1.Widget));
exports.Checkbox = Checkbox;
});
define(__m[262/*vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[263/*vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon-animations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[183/*vs/base/browser/ui/codiconLabel/codiconLabel*/], __M([0/*require*/,1/*exports*/,262/*vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon*/,263/*vs/css!vs/base/browser/ui/codiconLabel/codicon/codicon-animations*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
});
define(__m[264/*vs/css!vs/base/browser/ui/contextview/contextview*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[265/*vs/base/browser/ui/contextview/contextview*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,16/*vs/base/common/platform*/,2/*vs/base/common/lifecycle*/,103/*vs/base/common/range*/,88/*vs/base/browser/canIUse*/,264/*vs/css!vs/base/browser/ui/contextview/contextview*/]), function (require, exports, DOM, platform, lifecycle_1, range_1, canIUse_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Lays out a one dimensional view next to an anchor in a viewport.
*
* @returns The view offset within the viewport.
*/
function layout(viewportSize, viewSize, anchor) {
var anchorEnd = anchor.offset + anchor.size;
if (anchor.position === 0 /* Before */) {
if (viewSize <= viewportSize - anchorEnd) {
return anchorEnd; // happy case, lay it out after the anchor
}
if (viewSize <= anchor.offset) {
return anchor.offset - viewSize; // ok case, lay it out before the anchor
}
return Math.max(viewportSize - viewSize, 0); // sad case, lay it over the anchor
}
else {
if (viewSize <= anchor.offset) {
return anchor.offset - viewSize; // happy case, lay it out before the anchor
}
if (viewSize <= viewportSize - anchorEnd) {
return anchorEnd; // ok case, lay it out after the anchor
}
return 0; // sad case, lay it over the anchor
}
}
exports.layout = layout;
var ContextView = /** @class */ (function (_super) {
__extends(ContextView, _super);
function ContextView(container) {
var _this = _super.call(this) || this;
_this.container = null;
_this.delegate = null;
_this.toDisposeOnClean = lifecycle_1.Disposable.None;
_this.toDisposeOnSetContainer = lifecycle_1.Disposable.None;
_this.view = DOM.$('.context-view');
DOM.hide(_this.view);
_this.setContainer(container);
_this._register(lifecycle_1.toDisposable(function () { return _this.setContainer(null); }));
return _this;
}
ContextView.prototype.setContainer = function (container) {
var _this = this;
if (this.container) {
this.toDisposeOnSetContainer.dispose();
this.container.removeChild(this.view);
this.container = null;
}
if (container) {
this.container = container;
this.container.appendChild(this.view);
var toDisposeOnSetContainer_1 = new lifecycle_1.DisposableStore();
ContextView.BUBBLE_UP_EVENTS.forEach(function (event) {
toDisposeOnSetContainer_1.add(DOM.addStandardDisposableListener(_this.container, event, function (e) {
_this.onDOMEvent(e, false);
}));
});
ContextView.BUBBLE_DOWN_EVENTS.forEach(function (event) {
toDisposeOnSetContainer_1.add(DOM.addStandardDisposableListener(_this.container, event, function (e) {
_this.onDOMEvent(e, true);
}, true));
});
this.toDisposeOnSetContainer = toDisposeOnSetContainer_1;
}
};
ContextView.prototype.show = function (delegate) {
if (this.isVisible()) {
this.hide();
}
// Show static box
DOM.clearNode(this.view);
this.view.className = 'context-view';
this.view.style.top = '0px';
this.view.style.left = '0px';
DOM.show(this.view);
// Render content
this.toDisposeOnClean = delegate.render(this.view) || lifecycle_1.Disposable.None;
// Set active delegate
this.delegate = delegate;
// Layout
this.doLayout();
// Focus
if (this.delegate.focus) {
this.delegate.focus();
}
};
ContextView.prototype.layout = function () {
if (!this.isVisible()) {
return;
}
if (this.delegate.canRelayout === false && !(platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents)) {
this.hide();
return;
}
if (this.delegate.layout) {
this.delegate.layout();
}
this.doLayout();
};
ContextView.prototype.doLayout = function () {
// Check that we still have a delegate - this.delegate.layout may have hidden
if (!this.isVisible()) {
return;
}
// Get anchor
var anchor = this.delegate.getAnchor();
// Compute around
var around;
// Get the element's position and size (to anchor the view)
if (DOM.isHTMLElement(anchor)) {
var elementPosition = DOM.getDomNodePagePosition(anchor);
around = {
top: elementPosition.top,
left: elementPosition.left,
width: elementPosition.width,
height: elementPosition.height
};
}
else {
around = {
top: anchor.y,
left: anchor.x,
width: anchor.width || 1,
height: anchor.height || 2
};
}
var viewSizeWidth = DOM.getTotalWidth(this.view);
var viewSizeHeight = DOM.getTotalHeight(this.view);
var anchorPosition = this.delegate.anchorPosition || 0 /* BELOW */;
var anchorAlignment = this.delegate.anchorAlignment || 0 /* LEFT */;
var verticalAnchor = { offset: around.top - window.pageYOffset, size: around.height, position: anchorPosition === 0 /* BELOW */ ? 0 /* Before */ : 1 /* After */ };
var horizontalAnchor;
if (anchorAlignment === 0 /* LEFT */) {
horizontalAnchor = { offset: around.left, size: 0, position: 0 /* Before */ };
}
else {
horizontalAnchor = { offset: around.left + around.width, size: 0, position: 1 /* After */ };
}
var top = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset;
// if view intersects vertically with anchor, shift it horizontally
if (range_1.Range.intersects({ start: top, end: top + viewSizeHeight }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) {
horizontalAnchor.size = around.width;
if (anchorAlignment === 1 /* RIGHT */) {
horizontalAnchor.offset = around.left;
}
}
var left = layout(window.innerWidth, viewSizeWidth, horizontalAnchor);
DOM.removeClasses(this.view, 'top', 'bottom', 'left', 'right');
DOM.addClass(this.view, anchorPosition === 0 /* BELOW */ ? 'bottom' : 'top');
DOM.addClass(this.view, anchorAlignment === 0 /* LEFT */ ? 'left' : 'right');
var containerPosition = DOM.getDomNodePagePosition(this.container);
this.view.style.top = top - containerPosition.top + "px";
this.view.style.left = left - containerPosition.left + "px";
this.view.style.width = 'initial';
};
ContextView.prototype.hide = function (data) {
var delegate = this.delegate;
this.delegate = null;
if (delegate === null || delegate === void 0 ? void 0 : delegate.onHide) {
delegate.onHide(data);
}
this.toDisposeOnClean.dispose();
DOM.hide(this.view);
};
ContextView.prototype.isVisible = function () {
return !!this.delegate;
};
ContextView.prototype.onDOMEvent = function (e, onCapture) {
if (this.delegate) {
if (this.delegate.onDOMEvent) {
this.delegate.onDOMEvent(e, document.activeElement);
}
else if (onCapture && !DOM.isAncestor(e.target, this.container)) {
this.hide();
}
}
};
ContextView.prototype.dispose = function () {
this.hide();
_super.prototype.dispose.call(this);
};
ContextView.BUBBLE_UP_EVENTS = ['click', 'keydown', 'focus', 'blur'];
ContextView.BUBBLE_DOWN_EVENTS = ['click'];
return ContextView;
}(lifecycle_1.Disposable));
exports.ContextView = ContextView;
});
define(__m[266/*vs/css!vs/base/browser/ui/countBadge/countBadge*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[267/*vs/base/browser/ui/countBadge/countBadge*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,5/*vs/base/common/strings*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,266/*vs/css!vs/base/browser/ui/countBadge/countBadge*/]), function (require, exports, dom_1, strings_1, color_1, objects_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var defaultOpts = {
badgeBackground: color_1.Color.fromHex('#4D4D4D'),
badgeForeground: color_1.Color.fromHex('#FFFFFF')
};
var CountBadge = /** @class */ (function () {
function CountBadge(container, options) {
this.count = 0;
this.options = options || Object.create(null);
objects_1.mixin(this.options, defaultOpts, false);
this.badgeBackground = this.options.badgeBackground;
this.badgeForeground = this.options.badgeForeground;
this.badgeBorder = this.options.badgeBorder;
this.element = dom_1.append(container, dom_1.$('.monaco-count-badge'));
this.countFormat = this.options.countFormat || '{0}';
this.titleFormat = this.options.titleFormat || '';
this.setCount(this.options.count || 0);
}
CountBadge.prototype.setCount = function (count) {
this.count = count;
this.render();
};
CountBadge.prototype.setTitleFormat = function (titleFormat) {
this.titleFormat = titleFormat;
this.render();
};
CountBadge.prototype.render = function () {
this.element.textContent = strings_1.format(this.countFormat, this.count);
this.element.title = strings_1.format(this.titleFormat, this.count);
this.applyStyles();
};
CountBadge.prototype.style = function (styles) {
this.badgeBackground = styles.badgeBackground;
this.badgeForeground = styles.badgeForeground;
this.badgeBorder = styles.badgeBorder;
this.applyStyles();
};
CountBadge.prototype.applyStyles = function () {
if (this.element) {
var background = this.badgeBackground ? this.badgeBackground.toString() : '';
var foreground = this.badgeForeground ? this.badgeForeground.toString() : '';
var border = this.badgeBorder ? this.badgeBorder.toString() : '';
this.element.style.backgroundColor = background;
this.element.style.color = foreground;
this.element.style.borderWidth = border ? '1px' : '';
this.element.style.borderStyle = border ? 'solid' : '';
this.element.style.borderColor = border;
}
};
return CountBadge;
}());
exports.CountBadge = CountBadge;
});
define(__m[184/*vs/css!vs/base/browser/ui/findinput/findInput*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[268/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[139/*vs/base/browser/ui/iconLabel/iconLabel*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,133/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,2/*vs/base/common/lifecycle*/,103/*vs/base/common/range*/,31/*vs/base/common/objects*/,268/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/]), function (require, exports, dom, highlightedLabel_1, lifecycle_1, range_1, objects_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FastLabelNode = /** @class */ (function () {
function FastLabelNode(_element) {
this._element = _element;
}
Object.defineProperty(FastLabelNode.prototype, "element", {
get: function () {
return this._element;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FastLabelNode.prototype, "textContent", {
set: function (content) {
if (this.disposed || content === this._textContent) {
return;
}
this._textContent = content;
this._element.textContent = content;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FastLabelNode.prototype, "className", {
set: function (className) {
if (this.disposed || className === this._className) {
return;
}
this._className = className;
this._element.className = className;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FastLabelNode.prototype, "title", {
set: function (title) {
if (this.disposed || title === this._title) {
return;
}
this._title = title;
if (this._title) {
this._element.title = title;
}
else {
this._element.removeAttribute('title');
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(FastLabelNode.prototype, "empty", {
set: function (empty) {
if (this.disposed || empty === this._empty) {
return;
}
this._empty = empty;
this._element.style.marginLeft = empty ? '0' : '';
},
enumerable: true,
configurable: true
});
FastLabelNode.prototype.dispose = function () {
this.disposed = true;
};
return FastLabelNode;
}());
var IconLabel = /** @class */ (function (_super) {
__extends(IconLabel, _super);
function IconLabel(container, options) {
var _this = _super.call(this) || this;
_this.domNode = _this._register(new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label'))));
var labelContainer = dom.append(_this.domNode.element, dom.$('.monaco-icon-label-container'));
var nameContainer = dom.append(labelContainer, dom.$('span.monaco-icon-name-container'));
_this.descriptionContainer = _this._register(new FastLabelNode(dom.append(labelContainer, dom.$('span.monaco-icon-description-container'))));
if (options === null || options === void 0 ? void 0 : options.supportHighlights) {
_this.nameNode = new LabelWithHighlights(nameContainer, !!options.supportCodicons);
}
else {
_this.nameNode = new Label(nameContainer);
}
if (options === null || options === void 0 ? void 0 : options.supportDescriptionHighlights) {
_this.descriptionNodeFactory = function () { return new highlightedLabel_1.HighlightedLabel(dom.append(_this.descriptionContainer.element, dom.$('span.label-description')), !!options.supportCodicons); };
}
else {
_this.descriptionNodeFactory = function () { return _this._register(new FastLabelNode(dom.append(_this.descriptionContainer.element, dom.$('span.label-description')))); };
}
return _this;
}
IconLabel.prototype.setLabel = function (label, description, options) {
var classes = ['monaco-icon-label'];
if (options) {
if (options.extraClasses) {
classes.push.apply(classes, options.extraClasses);
}
if (options.italic) {
classes.push('italic');
}
}
this.domNode.className = classes.join(' ');
this.domNode.title = (options === null || options === void 0 ? void 0 : options.title) || '';
this.nameNode.setLabel(label, options);
if (description || this.descriptionNode) {
if (!this.descriptionNode) {
this.descriptionNode = this.descriptionNodeFactory(); // description node is created lazily on demand
}
if (this.descriptionNode instanceof highlightedLabel_1.HighlightedLabel) {
this.descriptionNode.set(description || '', options ? options.descriptionMatches : undefined);
if (options === null || options === void 0 ? void 0 : options.descriptionTitle) {
this.descriptionNode.element.title = options.descriptionTitle;
}
else {
this.descriptionNode.element.removeAttribute('title');
}
}
else {
this.descriptionNode.textContent = description || '';
this.descriptionNode.title = (options === null || options === void 0 ? void 0 : options.descriptionTitle) || '';
this.descriptionNode.empty = !description;
}
}
};
return IconLabel;
}(lifecycle_1.Disposable));
exports.IconLabel = IconLabel;
var Label = /** @class */ (function () {
function Label(container) {
this.container = container;
this.label = undefined;
this.singleLabel = undefined;
}
Label.prototype.setLabel = function (label, options) {
if (this.label === label && objects_1.equals(this.options, options)) {
return;
}
this.label = label;
this.options = options;
if (typeof label === 'string') {
if (!this.singleLabel) {
this.container.innerHTML = '';
dom.removeClass(this.container, 'multiple');
this.singleLabel = dom.append(this.container, dom.$('a.label-name', { id: options === null || options === void 0 ? void 0 : options.domId }));
}
this.singleLabel.textContent = label;
}
else {
this.container.innerHTML = '';
dom.addClass(this.container, 'multiple');
this.singleLabel = undefined;
for (var i = 0; i < label.length; i++) {
var l = label[i];
var id = (options === null || options === void 0 ? void 0 : options.domId) && (options === null || options === void 0 ? void 0 : options.domId) + "_" + i;
dom.append(this.container, dom.$('a.label-name', { id: id, 'data-icon-label-count': label.length, 'data-icon-label-index': i }, l));
if (i < label.length - 1) {
dom.append(this.container, dom.$('span.label-separator', undefined, (options === null || options === void 0 ? void 0 : options.separator) || '/'));
}
}
}
};
return Label;
}());
function splitMatches(labels, separator, matches) {
if (!matches) {
return undefined;
}
var labelStart = 0;
return labels.map(function (label) {
var labelRange = { start: labelStart, end: labelStart + label.length };
var result = matches
.map(function (match) { return range_1.Range.intersect(labelRange, match); })
.filter(function (range) { return !range_1.Range.isEmpty(range); })
.map(function (_a) {
var start = _a.start, end = _a.end;
return ({ start: start - labelStart, end: end - labelStart });
});
labelStart = labelRange.end + separator.length;
return result;
});
}
var LabelWithHighlights = /** @class */ (function () {
function LabelWithHighlights(container, supportCodicons) {
this.container = container;
this.supportCodicons = supportCodicons;
this.label = undefined;
this.singleLabel = undefined;
}
LabelWithHighlights.prototype.setLabel = function (label, options) {
if (this.label === label && objects_1.equals(this.options, options)) {
return;
}
this.label = label;
this.options = options;
if (typeof label === 'string') {
if (!this.singleLabel) {
this.container.innerHTML = '';
dom.removeClass(this.container, 'multiple');
this.singleLabel = new highlightedLabel_1.HighlightedLabel(dom.append(this.container, dom.$('a.label-name', { id: options === null || options === void 0 ? void 0 : options.domId })), this.supportCodicons);
}
this.singleLabel.set(label, options === null || options === void 0 ? void 0 : options.matches, options === null || options === void 0 ? void 0 : options.title, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
}
else {
this.container.innerHTML = '';
dom.addClass(this.container, 'multiple');
this.singleLabel = undefined;
var separator = (options === null || options === void 0 ? void 0 : options.separator) || '/';
var matches = splitMatches(label, separator, options === null || options === void 0 ? void 0 : options.matches);
for (var i = 0; i < label.length; i++) {
var l = label[i];
var m = matches ? matches[i] : undefined;
var id = (options === null || options === void 0 ? void 0 : options.domId) && (options === null || options === void 0 ? void 0 : options.domId) + "_" + i;
var name_1 = dom.$('a.label-name', { id: id, 'data-icon-label-count': label.length, 'data-icon-label-index': i });
var highlightedLabel = new highlightedLabel_1.HighlightedLabel(dom.append(this.container, name_1), this.supportCodicons);
highlightedLabel.set(l, m, options === null || options === void 0 ? void 0 : options.title, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
if (i < label.length - 1) {
dom.append(name_1, dom.$('span.label-separator', undefined, separator));
}
}
}
};
return LabelWithHighlights;
}());
});
define(__m[269/*vs/css!vs/base/browser/ui/inputbox/inputBox*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[270/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[271/*vs/css!vs/base/browser/ui/list/list*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[272/*vs/css!vs/base/browser/ui/menu/menu*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[273/*vs/css!vs/base/browser/ui/progressbar/progressbar*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[274/*vs/base/browser/ui/progressbar/progressbar*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,6/*vs/base/browser/dom*/,15/*vs/base/common/async*/,273/*vs/css!vs/base/browser/ui/progressbar/progressbar*/]), function (require, exports, lifecycle_1, color_1, objects_1, dom_1, async_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var css_done = 'done';
var css_active = 'active';
var css_infinite = 'infinite';
var css_discrete = 'discrete';
var css_progress_container = 'monaco-progress-container';
var css_progress_bit = 'progress-bit';
var defaultOpts = {
progressBarBackground: color_1.Color.fromHex('#0E70C0')
};
/**
* A progress bar with support for infinite or discrete progress.
*/
var ProgressBar = /** @class */ (function (_super) {
__extends(ProgressBar, _super);
function ProgressBar(container, options) {
var _this = _super.call(this) || this;
_this.options = options || Object.create(null);
objects_1.mixin(_this.options, defaultOpts, false);
_this.workedVal = 0;
_this.progressBarBackground = _this.options.progressBarBackground;
_this._register(_this.showDelayedScheduler = new async_1.RunOnceScheduler(function () { return dom_1.show(_this.element); }, 0));
_this.create(container);
return _this;
}
ProgressBar.prototype.create = function (container) {
this.element = document.createElement('div');
dom_1.addClass(this.element, css_progress_container);
container.appendChild(this.element);
this.bit = document.createElement('div');
dom_1.addClass(this.bit, css_progress_bit);
this.element.appendChild(this.bit);
this.applyStyles();
};
ProgressBar.prototype.off = function () {
this.bit.style.width = 'inherit';
this.bit.style.opacity = '1';
dom_1.removeClasses(this.element, css_active, css_infinite, css_discrete);
this.workedVal = 0;
this.totalWork = undefined;
};
/**
* Stops the progressbar from showing any progress instantly without fading out.
*/
ProgressBar.prototype.stop = function () {
return this.doDone(false);
};
ProgressBar.prototype.doDone = function (delayed) {
var _this = this;
dom_1.addClass(this.element, css_done);
// let it grow to 100% width and hide afterwards
if (!dom_1.hasClass(this.element, css_infinite)) {
this.bit.style.width = 'inherit';
if (delayed) {
setTimeout(function () { return _this.off(); }, 200);
}
else {
this.off();
}
}
// let it fade out and hide afterwards
else {
this.bit.style.opacity = '0';
if (delayed) {
setTimeout(function () { return _this.off(); }, 200);
}
else {
this.off();
}
}
return this;
};
ProgressBar.prototype.hide = function () {
dom_1.hide(this.element);
this.showDelayedScheduler.cancel();
};
ProgressBar.prototype.style = function (styles) {
this.progressBarBackground = styles.progressBarBackground;
this.applyStyles();
};
ProgressBar.prototype.applyStyles = function () {
if (this.bit) {
var background = this.progressBarBackground ? this.progressBarBackground.toString() : '';
this.bit.style.backgroundColor = background;
}
};
return ProgressBar;
}(lifecycle_1.Disposable));
exports.ProgressBar = ProgressBar;
});
define(__m[275/*vs/css!vs/base/browser/ui/sash/sash*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[104/*vs/base/browser/ui/sash/sash*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,24/*vs/base/browser/browser*/,16/*vs/base/common/platform*/,21/*vs/base/common/types*/,57/*vs/base/browser/touch*/,45/*vs/base/browser/mouseEvent*/,4/*vs/base/common/event*/,6/*vs/base/browser/dom*/,52/*vs/base/browser/event*/,275/*vs/css!vs/base/browser/ui/sash/sash*/]), function (require, exports, lifecycle_1, browser_1, platform_1, types, touch_1, mouseEvent_1, event_1, dom_1, event_2) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DEBUG = false;
var Sash = /** @class */ (function (_super) {
__extends(Sash, _super);
function Sash(container, layoutProvider, options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this) || this;
_this._state = 3 /* Enabled */;
_this._onDidEnablementChange = _this._register(new event_1.Emitter());
_this.onDidEnablementChange = _this._onDidEnablementChange.event;
_this._onDidStart = _this._register(new event_1.Emitter());
_this.onDidStart = _this._onDidStart.event;
_this._onDidChange = _this._register(new event_1.Emitter());
_this.onDidChange = _this._onDidChange.event;
_this._onDidReset = _this._register(new event_1.Emitter());
_this.onDidReset = _this._onDidReset.event;
_this._onDidEnd = _this._register(new event_1.Emitter());
_this.onDidEnd = _this._onDidEnd.event;
_this.linkedSash = undefined;
_this.orthogonalStartSashDisposables = _this._register(new lifecycle_1.DisposableStore());
_this.orthogonalEndSashDisposables = _this._register(new lifecycle_1.DisposableStore());
_this.el = dom_1.append(container, dom_1.$('.monaco-sash'));
if (platform_1.isMacintosh) {
dom_1.addClass(_this.el, 'mac');
}
_this._register(event_2.domEvent(_this.el, 'mousedown')(_this.onMouseDown, _this));
_this._register(event_2.domEvent(_this.el, 'dblclick')(_this.onMouseDoubleClick, _this));
_this._register(touch_1.Gesture.addTarget(_this.el));
_this._register(event_2.domEvent(_this.el, touch_1.EventType.Start)(_this.onTouchStart, _this));
if (browser_1.isIPad) {
// see also https://ux.stackexchange.com/questions/39023/what-is-the-optimum-button-size-of-touch-screen-applications
dom_1.addClass(_this.el, 'touch');
}
_this.setOrientation(options.orientation || 0 /* VERTICAL */);
_this.hidden = false;
_this.layoutProvider = layoutProvider;
_this.orthogonalStartSash = options.orthogonalStartSash;
_this.orthogonalEndSash = options.orthogonalEndSash;
dom_1.toggleClass(_this.el, 'debug', DEBUG);
return _this;
}
Object.defineProperty(Sash.prototype, "state", {
get: function () { return this._state; },
set: function (state) {
if (this._state === state) {
return;
}
dom_1.toggleClass(this.el, 'disabled', state === 0 /* Disabled */);
dom_1.toggleClass(this.el, 'minimum', state === 1 /* Minimum */);
dom_1.toggleClass(this.el, 'maximum', state === 2 /* Maximum */);
this._state = state;
this._onDidEnablementChange.fire(state);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Sash.prototype, "orthogonalStartSash", {
get: function () { return this._orthogonalStartSash; },
set: function (sash) {
this.orthogonalStartSashDisposables.clear();
if (sash) {
this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange(this.onOrthogonalStartSashEnablementChange, this));
this.onOrthogonalStartSashEnablementChange(sash.state);
}
else {
this.onOrthogonalStartSashEnablementChange(0 /* Disabled */);
}
this._orthogonalStartSash = sash;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Sash.prototype, "orthogonalEndSash", {
get: function () { return this._orthogonalEndSash; },
set: function (sash) {
this.orthogonalEndSashDisposables.clear();
if (sash) {
this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange(this.onOrthogonalEndSashEnablementChange, this));
this.onOrthogonalEndSashEnablementChange(sash.state);
}
else {
this.onOrthogonalEndSashEnablementChange(0 /* Disabled */);
}
this._orthogonalEndSash = sash;
},
enumerable: true,
configurable: true
});
Sash.prototype.setOrientation = function (orientation) {
this.orientation = orientation;
if (this.orientation === 1 /* HORIZONTAL */) {
dom_1.addClass(this.el, 'horizontal');
dom_1.removeClass(this.el, 'vertical');
}
else {
dom_1.removeClass(this.el, 'horizontal');
dom_1.addClass(this.el, 'vertical');
}
if (this.layoutProvider) {
this.layout();
}
};
Sash.prototype.onMouseDown = function (e) {
var _this = this;
dom_1.EventHelper.stop(e, false);
var isMultisashResize = false;
if (!e.__orthogonalSashEvent) {
var orthogonalSash = this.getOrthogonalSash(e);
if (orthogonalSash) {
isMultisashResize = true;
e.__orthogonalSashEvent = true;
orthogonalSash.onMouseDown(e);
}
}
if (this.linkedSash && !e.__linkedSashEvent) {
e.__linkedSashEvent = true;
this.linkedSash.onMouseDown(e);
}
if (!this.state) {
return;
}
// Select both iframes and webviews; internally Electron nests an iframe
// in its component, but this isn't queryable.
var iframes = __spreadArrays(dom_1.getElementsByTagName('iframe'), dom_1.getElementsByTagName('webview'));
for (var _i = 0, iframes_1 = iframes; _i < iframes_1.length; _i++) {
var iframe = iframes_1[_i];
iframe.style.pointerEvents = 'none'; // disable mouse events on iframes as long as we drag the sash
}
var mouseDownEvent = new mouseEvent_1.StandardMouseEvent(e);
var startX = mouseDownEvent.posx;
var startY = mouseDownEvent.posy;
var altKey = mouseDownEvent.altKey;
var startEvent = { startX: startX, currentX: startX, startY: startY, currentY: startY, altKey: altKey };
dom_1.addClass(this.el, 'active');
this._onDidStart.fire(startEvent);
// fix https://github.com/Microsoft/vscode/issues/21675
var style = dom_1.createStyleSheet(this.el);
var updateStyle = function () {
var cursor = '';
if (isMultisashResize) {
cursor = 'all-scroll';
}
else if (_this.orientation === 1 /* HORIZONTAL */) {
if (_this.state === 1 /* Minimum */) {
cursor = 's-resize';
}
else if (_this.state === 2 /* Maximum */) {
cursor = 'n-resize';
}
else {
cursor = platform_1.isMacintosh ? 'row-resize' : 'ns-resize';
}
}
else {
if (_this.state === 1 /* Minimum */) {
cursor = 'e-resize';
}
else if (_this.state === 2 /* Maximum */) {
cursor = 'w-resize';
}
else {
cursor = platform_1.isMacintosh ? 'col-resize' : 'ew-resize';
}
}
style.innerHTML = "* { cursor: " + cursor + " !important; }";
};
var disposables = new lifecycle_1.DisposableStore();
updateStyle();
if (!isMultisashResize) {
this.onDidEnablementChange(updateStyle, null, disposables);
}
var onMouseMove = function (e) {
dom_1.EventHelper.stop(e, false);
var mouseMoveEvent = new mouseEvent_1.StandardMouseEvent(e);
var event = { startX: startX, currentX: mouseMoveEvent.posx, startY: startY, currentY: mouseMoveEvent.posy, altKey: altKey };
_this._onDidChange.fire(event);
};
var onMouseUp = function (e) {
dom_1.EventHelper.stop(e, false);
_this.el.removeChild(style);
dom_1.removeClass(_this.el, 'active');
_this._onDidEnd.fire();
disposables.dispose();
for (var _i = 0, iframes_2 = iframes; _i < iframes_2.length; _i++) {
var iframe = iframes_2[_i];
iframe.style.pointerEvents = 'auto';
}
};
event_2.domEvent(window, 'mousemove')(onMouseMove, null, disposables);
event_2.domEvent(window, 'mouseup')(onMouseUp, null, disposables);
};
Sash.prototype.onMouseDoubleClick = function (e) {
var orthogonalSash = this.getOrthogonalSash(e);
if (orthogonalSash) {
orthogonalSash._onDidReset.fire();
}
if (this.linkedSash) {
this.linkedSash._onDidReset.fire();
}
this._onDidReset.fire();
};
Sash.prototype.onTouchStart = function (event) {
var _this = this;
dom_1.EventHelper.stop(event);
var listeners = [];
var startX = event.pageX;
var startY = event.pageY;
var altKey = event.altKey;
this._onDidStart.fire({
startX: startX,
currentX: startX,
startY: startY,
currentY: startY,
altKey: altKey
});
listeners.push(dom_1.addDisposableListener(this.el, touch_1.EventType.Change, function (event) {
if (types.isNumber(event.pageX) && types.isNumber(event.pageY)) {
_this._onDidChange.fire({
startX: startX,
currentX: event.pageX,
startY: startY,
currentY: event.pageY,
altKey: altKey
});
}
}));
listeners.push(dom_1.addDisposableListener(this.el, touch_1.EventType.End, function (event) {
_this._onDidEnd.fire();
lifecycle_1.dispose(listeners);
}));
};
Sash.prototype.layout = function () {
var size = browser_1.isIPad ? 20 : 4;
if (this.orientation === 0 /* VERTICAL */) {
var verticalProvider = this.layoutProvider;
this.el.style.left = verticalProvider.getVerticalSashLeft(this) - (size / 2) + 'px';
if (verticalProvider.getVerticalSashTop) {
this.el.style.top = verticalProvider.getVerticalSashTop(this) + 'px';
}
if (verticalProvider.getVerticalSashHeight) {
this.el.style.height = verticalProvider.getVerticalSashHeight(this) + 'px';
}
}
else {
var horizontalProvider = this.layoutProvider;
this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - (size / 2) + 'px';
if (horizontalProvider.getHorizontalSashLeft) {
this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + 'px';
}
if (horizontalProvider.getHorizontalSashWidth) {
this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + 'px';
}
}
};
Sash.prototype.hide = function () {
this.hidden = true;
this.el.style.display = 'none';
this.el.setAttribute('aria-hidden', 'true');
};
Sash.prototype.onOrthogonalStartSashEnablementChange = function (state) {
dom_1.toggleClass(this.el, 'orthogonal-start', state !== 0 /* Disabled */);
};
Sash.prototype.onOrthogonalEndSashEnablementChange = function (state) {
dom_1.toggleClass(this.el, 'orthogonal-end', state !== 0 /* Disabled */);
};
Sash.prototype.getOrthogonalSash = function (e) {
if (this.orientation === 0 /* VERTICAL */) {
if (e.offsetY <= 4) {
return this.orthogonalStartSash;
}
else if (e.offsetY >= this.el.clientHeight - 4) {
return this.orthogonalEndSash;
}
}
else {
if (e.offsetX <= 4) {
return this.orthogonalStartSash;
}
else if (e.offsetX >= this.el.clientWidth - 4) {
return this.orthogonalEndSash;
}
}
return undefined;
};
Sash.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.el.remove();
};
return Sash;
}(lifecycle_1.Disposable));
exports.Sash = Sash;
});
define(__m[276/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[53/*vs/base/browser/ui/scrollbar/scrollableElement*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,45/*vs/base/browser/mouseEvent*/,250/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/,251/*vs/base/browser/ui/scrollbar/verticalScrollbar*/,47/*vs/base/browser/ui/widget*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,176/*vs/base/common/scrollable*/,276/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/]), function (require, exports, browser_1, dom, fastDomNode_1, mouseEvent_1, horizontalScrollbar_1, verticalScrollbar_1, widget_1, async_1, event_1, lifecycle_1, platform, scrollable_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var HIDE_TIMEOUT = 500;
var SCROLL_WHEEL_SENSITIVITY = 50;
var SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true;
var MouseWheelClassifierItem = /** @class */ (function () {
function MouseWheelClassifierItem(timestamp, deltaX, deltaY) {
this.timestamp = timestamp;
this.deltaX = deltaX;
this.deltaY = deltaY;
this.score = 0;
}
return MouseWheelClassifierItem;
}());
var MouseWheelClassifier = /** @class */ (function () {
function MouseWheelClassifier() {
this._capacity = 5;
this._memory = [];
this._front = -1;
this._rear = -1;
}
MouseWheelClassifier.prototype.isPhysicalMouseWheel = function () {
if (this._front === -1 && this._rear === -1) {
// no elements
return false;
}
// 0.5 * last + 0.25 * 2nd last + 0.125 * 3rd last + ...
var remainingInfluence = 1;
var score = 0;
var iteration = 1;
var index = this._rear;
do {
var influence = (index === this._front ? remainingInfluence : Math.pow(2, -iteration));
remainingInfluence -= influence;
score += this._memory[index].score * influence;
if (index === this._front) {
break;
}
index = (this._capacity + index - 1) % this._capacity;
iteration++;
} while (true);
return (score <= 0.5);
};
MouseWheelClassifier.prototype.accept = function (timestamp, deltaX, deltaY) {
var item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY);
item.score = this._computeScore(item);
if (this._front === -1 && this._rear === -1) {
this._memory[0] = item;
this._front = 0;
this._rear = 0;
}
else {
this._rear = (this._rear + 1) % this._capacity;
if (this._rear === this._front) {
// Drop oldest
this._front = (this._front + 1) % this._capacity;
}
this._memory[this._rear] = item;
}
};
/**
* A score between 0 and 1 for `item`.
* - a score towards 0 indicates that the source appears to be a physical mouse wheel
* - a score towards 1 indicates that the source appears to be a touchpad or magic mouse, etc.
*/
MouseWheelClassifier.prototype._computeScore = function (item) {
if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) {
// both axes exercised => definitely not a physical mouse wheel
return 1;
}
var score = 0.5;
var prev = (this._front === -1 && this._rear === -1 ? null : this._memory[this._rear]);
if (prev) {
// const deltaT = item.timestamp - prev.timestamp;
// if (deltaT < 1000 / 30) {
// // sooner than X times per second => indicator that this is not a physical mouse wheel
// score += 0.25;
// }
// if (item.deltaX === prev.deltaX && item.deltaY === prev.deltaY) {
// // equal amplitude => indicator that this is a physical mouse wheel
// score -= 0.25;
// }
}
if (Math.abs(item.deltaX - Math.round(item.deltaX)) > 0 || Math.abs(item.deltaY - Math.round(item.deltaY)) > 0) {
// non-integer deltas => indicator that this is not a physical mouse wheel
score += 0.25;
}
return Math.min(Math.max(score, 0), 1);
};
MouseWheelClassifier.INSTANCE = new MouseWheelClassifier();
return MouseWheelClassifier;
}());
exports.MouseWheelClassifier = MouseWheelClassifier;
var AbstractScrollableElement = /** @class */ (function (_super) {
__extends(AbstractScrollableElement, _super);
function AbstractScrollableElement(element, options, scrollable) {
var _this = _super.call(this) || this;
_this._onScroll = _this._register(new event_1.Emitter());
_this.onScroll = _this._onScroll.event;
element.style.overflow = 'hidden';
_this._options = resolveOptions(options);
_this._scrollable = scrollable;
_this._register(_this._scrollable.onScroll(function (e) {
_this._onDidScroll(e);
_this._onScroll.fire(e);
}));
var scrollbarHost = {
onMouseWheel: function (mouseWheelEvent) { return _this._onMouseWheel(mouseWheelEvent); },
onDragStart: function () { return _this._onDragStart(); },
onDragEnd: function () { return _this._onDragEnd(); },
};
_this._verticalScrollbar = _this._register(new verticalScrollbar_1.VerticalScrollbar(_this._scrollable, _this._options, scrollbarHost));
_this._horizontalScrollbar = _this._register(new horizontalScrollbar_1.HorizontalScrollbar(_this._scrollable, _this._options, scrollbarHost));
_this._domNode = document.createElement('div');
_this._domNode.className = 'monaco-scrollable-element ' + _this._options.className;
_this._domNode.setAttribute('role', 'presentation');
_this._domNode.style.position = 'relative';
_this._domNode.style.overflow = 'hidden';
_this._domNode.appendChild(element);
_this._domNode.appendChild(_this._horizontalScrollbar.domNode.domNode);
_this._domNode.appendChild(_this._verticalScrollbar.domNode.domNode);
if (_this._options.useShadows) {
_this._leftShadowDomNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
_this._leftShadowDomNode.setClassName('shadow');
_this._domNode.appendChild(_this._leftShadowDomNode.domNode);
_this._topShadowDomNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
_this._topShadowDomNode.setClassName('shadow');
_this._domNode.appendChild(_this._topShadowDomNode.domNode);
_this._topLeftShadowDomNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
_this._topLeftShadowDomNode.setClassName('shadow top-left-corner');
_this._domNode.appendChild(_this._topLeftShadowDomNode.domNode);
}
else {
_this._leftShadowDomNode = null;
_this._topShadowDomNode = null;
_this._topLeftShadowDomNode = null;
}
_this._listenOnDomNode = _this._options.listenOnDomNode || _this._domNode;
_this._mouseWheelToDispose = [];
_this._setListeningToMouseWheel(_this._options.handleMouseWheel);
_this.onmouseover(_this._listenOnDomNode, function (e) { return _this._onMouseOver(e); });
_this.onnonbubblingmouseout(_this._listenOnDomNode, function (e) { return _this._onMouseOut(e); });
_this._hideTimeout = _this._register(new async_1.TimeoutTimer());
_this._isDragging = false;
_this._mouseIsOver = false;
_this._shouldRender = true;
_this._revealOnScroll = true;
return _this;
}
AbstractScrollableElement.prototype.dispose = function () {
this._mouseWheelToDispose = lifecycle_1.dispose(this._mouseWheelToDispose);
_super.prototype.dispose.call(this);
};
/**
* Get the generated 'scrollable' dom node
*/
AbstractScrollableElement.prototype.getDomNode = function () {
return this._domNode;
};
AbstractScrollableElement.prototype.getOverviewRulerLayoutInfo = function () {
return {
parent: this._domNode,
insertBefore: this._verticalScrollbar.domNode.domNode,
};
};
/**
* Delegate a mouse down event to the vertical scrollbar.
* This is to help with clicking somewhere else and having the scrollbar react.
*/
AbstractScrollableElement.prototype.delegateVerticalScrollbarMouseDown = function (browserEvent) {
this._verticalScrollbar.delegateMouseDown(browserEvent);
};
AbstractScrollableElement.prototype.getScrollDimensions = function () {
return this._scrollable.getScrollDimensions();
};
AbstractScrollableElement.prototype.setScrollDimensions = function (dimensions) {
this._scrollable.setScrollDimensions(dimensions);
};
/**
* Update the class name of the scrollable element.
*/
AbstractScrollableElement.prototype.updateClassName = function (newClassName) {
this._options.className = newClassName;
// Defaults are different on Macs
if (platform.isMacintosh) {
this._options.className += ' mac';
}
this._domNode.className = 'monaco-scrollable-element ' + this._options.className;
};
/**
* Update configuration options for the scrollbar.
* Really this is Editor.IEditorScrollbarOptions, but base shouldn't
* depend on Editor.
*/
AbstractScrollableElement.prototype.updateOptions = function (newOptions) {
var massagedOptions = resolveOptions(newOptions);
this._options.handleMouseWheel = massagedOptions.handleMouseWheel;
this._options.mouseWheelScrollSensitivity = massagedOptions.mouseWheelScrollSensitivity;
this._options.fastScrollSensitivity = massagedOptions.fastScrollSensitivity;
this._setListeningToMouseWheel(this._options.handleMouseWheel);
if (!this._options.lazyRender) {
this._render();
}
};
// -------------------- mouse wheel scrolling --------------------
AbstractScrollableElement.prototype._setListeningToMouseWheel = function (shouldListen) {
var _this = this;
var isListening = (this._mouseWheelToDispose.length > 0);
if (isListening === shouldListen) {
// No change
return;
}
// Stop listening (if necessary)
this._mouseWheelToDispose = lifecycle_1.dispose(this._mouseWheelToDispose);
// Start listening (if necessary)
if (shouldListen) {
var onMouseWheel = function (browserEvent) {
_this._onMouseWheel(new mouseEvent_1.StandardWheelEvent(browserEvent));
};
this._mouseWheelToDispose.push(dom.addDisposableListener(this._listenOnDomNode, browser_1.isEdgeOrIE ? 'mousewheel' : 'wheel', onMouseWheel, { passive: false }));
}
};
AbstractScrollableElement.prototype._onMouseWheel = function (e) {
var _a;
var classifier = MouseWheelClassifier.INSTANCE;
if (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) {
classifier.accept(Date.now(), e.deltaX, e.deltaY);
}
// console.log(`${Date.now()}, ${e.deltaY}, ${e.deltaX}`);
if (e.deltaY || e.deltaX) {
var deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity;
var deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity;
if (this._options.flipAxes) {
_a = [deltaX, deltaY], deltaY = _a[0], deltaX = _a[1];
}
// Convert vertical scrolling to horizontal if shift is held, this
// is handled at a higher level on Mac
var shiftConvert = !platform.isMacintosh && e.browserEvent && e.browserEvent.shiftKey;
if ((this._options.scrollYToX || shiftConvert) && !deltaX) {
deltaX = deltaY;
deltaY = 0;
}
if (e.browserEvent && e.browserEvent.altKey) {
// fastScrolling
deltaX = deltaX * this._options.fastScrollSensitivity;
deltaY = deltaY * this._options.fastScrollSensitivity;
}
var futureScrollPosition = this._scrollable.getFutureScrollPosition();
var desiredScrollPosition = {};
if (deltaY) {
var desiredScrollTop = futureScrollPosition.scrollTop - SCROLL_WHEEL_SENSITIVITY * deltaY;
this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop);
}
if (deltaX) {
var desiredScrollLeft = futureScrollPosition.scrollLeft - SCROLL_WHEEL_SENSITIVITY * deltaX;
this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft);
}
// Check that we are scrolling towards a location which is valid
desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition);
if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) {
var canPerformSmoothScroll = (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED
&& this._options.mouseWheelSmoothScroll
&& classifier.isPhysicalMouseWheel());
if (canPerformSmoothScroll) {
this._scrollable.setScrollPositionSmooth(desiredScrollPosition);
}
else {
this._scrollable.setScrollPositionNow(desiredScrollPosition);
}
this._shouldRender = true;
}
}
if (this._options.alwaysConsumeMouseWheel || this._shouldRender) {
e.preventDefault();
e.stopPropagation();
}
};
AbstractScrollableElement.prototype._onDidScroll = function (e) {
this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender;
this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender;
if (this._options.useShadows) {
this._shouldRender = true;
}
if (this._revealOnScroll) {
this._reveal();
}
if (!this._options.lazyRender) {
this._render();
}
};
/**
* Render / mutate the DOM now.
* Should be used together with the ctor option `lazyRender`.
*/
AbstractScrollableElement.prototype.renderNow = function () {
if (!this._options.lazyRender) {
throw new Error('Please use `lazyRender` together with `renderNow`!');
}
this._render();
};
AbstractScrollableElement.prototype._render = function () {
if (!this._shouldRender) {
return;
}
this._shouldRender = false;
this._horizontalScrollbar.render();
this._verticalScrollbar.render();
if (this._options.useShadows) {
var scrollState = this._scrollable.getCurrentScrollPosition();
var enableTop = scrollState.scrollTop > 0;
var enableLeft = scrollState.scrollLeft > 0;
this._leftShadowDomNode.setClassName('shadow' + (enableLeft ? ' left' : ''));
this._topShadowDomNode.setClassName('shadow' + (enableTop ? ' top' : ''));
this._topLeftShadowDomNode.setClassName('shadow top-left-corner' + (enableTop ? ' top' : '') + (enableLeft ? ' left' : ''));
}
};
// -------------------- fade in / fade out --------------------
AbstractScrollableElement.prototype._onDragStart = function () {
this._isDragging = true;
this._reveal();
};
AbstractScrollableElement.prototype._onDragEnd = function () {
this._isDragging = false;
this._hide();
};
AbstractScrollableElement.prototype._onMouseOut = function (e) {
this._mouseIsOver = false;
this._hide();
};
AbstractScrollableElement.prototype._onMouseOver = function (e) {
this._mouseIsOver = true;
this._reveal();
};
AbstractScrollableElement.prototype._reveal = function () {
this._verticalScrollbar.beginReveal();
this._horizontalScrollbar.beginReveal();
this._scheduleHide();
};
AbstractScrollableElement.prototype._hide = function () {
if (!this._mouseIsOver && !this._isDragging) {
this._verticalScrollbar.beginHide();
this._horizontalScrollbar.beginHide();
}
};
AbstractScrollableElement.prototype._scheduleHide = function () {
var _this = this;
if (!this._mouseIsOver && !this._isDragging) {
this._hideTimeout.cancelAndSet(function () { return _this._hide(); }, HIDE_TIMEOUT);
}
};
return AbstractScrollableElement;
}(widget_1.Widget));
exports.AbstractScrollableElement = AbstractScrollableElement;
var ScrollableElement = /** @class */ (function (_super) {
__extends(ScrollableElement, _super);
function ScrollableElement(element, options) {
var _this = this;
options = options || {};
options.mouseWheelSmoothScroll = false;
var scrollable = new scrollable_1.Scrollable(0, function (callback) { return dom.scheduleAtNextAnimationFrame(callback); });
_this = _super.call(this, element, options, scrollable) || this;
_this._register(scrollable);
return _this;
}
ScrollableElement.prototype.setScrollPosition = function (update) {
this._scrollable.setScrollPositionNow(update);
};
ScrollableElement.prototype.getScrollPosition = function () {
return this._scrollable.getCurrentScrollPosition();
};
return ScrollableElement;
}(AbstractScrollableElement));
exports.ScrollableElement = ScrollableElement;
var SmoothScrollableElement = /** @class */ (function (_super) {
__extends(SmoothScrollableElement, _super);
function SmoothScrollableElement(element, options, scrollable) {
return _super.call(this, element, options, scrollable) || this;
}
return SmoothScrollableElement;
}(AbstractScrollableElement));
exports.SmoothScrollableElement = SmoothScrollableElement;
var DomScrollableElement = /** @class */ (function (_super) {
__extends(DomScrollableElement, _super);
function DomScrollableElement(element, options) {
var _this = _super.call(this, element, options) || this;
_this._element = element;
_this.onScroll(function (e) {
if (e.scrollTopChanged) {
_this._element.scrollTop = e.scrollTop;
}
if (e.scrollLeftChanged) {
_this._element.scrollLeft = e.scrollLeft;
}
});
_this.scanDomNode();
return _this;
}
DomScrollableElement.prototype.scanDomNode = function () {
// width, scrollLeft, scrollWidth, height, scrollTop, scrollHeight
this.setScrollDimensions({
width: this._element.clientWidth,
scrollWidth: this._element.scrollWidth,
height: this._element.clientHeight,
scrollHeight: this._element.scrollHeight
});
this.setScrollPosition({
scrollLeft: this._element.scrollLeft,
scrollTop: this._element.scrollTop,
});
};
return DomScrollableElement;
}(ScrollableElement));
exports.DomScrollableElement = DomScrollableElement;
function resolveOptions(opts) {
var result = {
lazyRender: (typeof opts.lazyRender !== 'undefined' ? opts.lazyRender : false),
className: (typeof opts.className !== 'undefined' ? opts.className : ''),
useShadows: (typeof opts.useShadows !== 'undefined' ? opts.useShadows : true),
handleMouseWheel: (typeof opts.handleMouseWheel !== 'undefined' ? opts.handleMouseWheel : true),
flipAxes: (typeof opts.flipAxes !== 'undefined' ? opts.flipAxes : false),
alwaysConsumeMouseWheel: (typeof opts.alwaysConsumeMouseWheel !== 'undefined' ? opts.alwaysConsumeMouseWheel : false),
scrollYToX: (typeof opts.scrollYToX !== 'undefined' ? opts.scrollYToX : false),
mouseWheelScrollSensitivity: (typeof opts.mouseWheelScrollSensitivity !== 'undefined' ? opts.mouseWheelScrollSensitivity : 1),
fastScrollSensitivity: (typeof opts.fastScrollSensitivity !== 'undefined' ? opts.fastScrollSensitivity : 5),
mouseWheelSmoothScroll: (typeof opts.mouseWheelSmoothScroll !== 'undefined' ? opts.mouseWheelSmoothScroll : true),
arrowSize: (typeof opts.arrowSize !== 'undefined' ? opts.arrowSize : 11),
listenOnDomNode: (typeof opts.listenOnDomNode !== 'undefined' ? opts.listenOnDomNode : null),
horizontal: (typeof opts.horizontal !== 'undefined' ? opts.horizontal : 1 /* Auto */),
horizontalScrollbarSize: (typeof opts.horizontalScrollbarSize !== 'undefined' ? opts.horizontalScrollbarSize : 10),
horizontalSliderSize: (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : 0),
horizontalHasArrows: (typeof opts.horizontalHasArrows !== 'undefined' ? opts.horizontalHasArrows : false),
vertical: (typeof opts.vertical !== 'undefined' ? opts.vertical : 1 /* Auto */),
verticalScrollbarSize: (typeof opts.verticalScrollbarSize !== 'undefined' ? opts.verticalScrollbarSize : 10),
verticalHasArrows: (typeof opts.verticalHasArrows !== 'undefined' ? opts.verticalHasArrows : false),
verticalSliderSize: (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : 0)
};
result.horizontalSliderSize = (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : result.horizontalScrollbarSize);
result.verticalSliderSize = (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : result.verticalScrollbarSize);
// Defaults are different on Macs
if (platform.isMacintosh) {
result.className += ' mac';
}
return result;
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[140/*vs/base/browser/ui/list/listView*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,2/*vs/base/common/lifecycle*/,57/*vs/base/browser/touch*/,6/*vs/base/browser/dom*/,4/*vs/base/common/event*/,52/*vs/base/browser/event*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,246/*vs/base/browser/ui/list/rangeMap*/,249/*vs/base/browser/ui/list/rowCache*/,101/*vs/base/common/decorators*/,103/*vs/base/common/range*/,19/*vs/base/common/arrays*/,98/*vs/base/browser/dnd*/,15/*vs/base/common/async*/,24/*vs/base/browser/browser*/]), function (require, exports, objects_1, lifecycle_1, touch_1, DOM, event_1, event_2, scrollableElement_1, rangeMap_1, rowCache_1, decorators_1, range_1, arrays_1, dnd_1, async_1, browser_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DefaultOptions = {
useShadows: true,
verticalScrollMode: 1 /* Auto */,
setRowLineHeight: true,
supportDynamicHeights: false,
dnd: {
getDragElements: function (e) { return [e]; },
getDragURI: function () { return null; },
onDragStart: function () { },
onDragOver: function () { return false; },
drop: function () { }
},
horizontalScrolling: false
};
var ElementsDragAndDropData = /** @class */ (function () {
function ElementsDragAndDropData(elements) {
this.elements = elements;
}
ElementsDragAndDropData.prototype.update = function () { };
ElementsDragAndDropData.prototype.getData = function () {
return this.elements;
};
return ElementsDragAndDropData;
}());
exports.ElementsDragAndDropData = ElementsDragAndDropData;
var ExternalElementsDragAndDropData = /** @class */ (function () {
function ExternalElementsDragAndDropData(elements) {
this.elements = elements;
}
ExternalElementsDragAndDropData.prototype.update = function () { };
ExternalElementsDragAndDropData.prototype.getData = function () {
return this.elements;
};
return ExternalElementsDragAndDropData;
}());
exports.ExternalElementsDragAndDropData = ExternalElementsDragAndDropData;
var DesktopDragAndDropData = /** @class */ (function () {
function DesktopDragAndDropData() {
this.types = [];
this.files = [];
}
DesktopDragAndDropData.prototype.update = function (dataTransfer) {
var _a;
if (dataTransfer.types) {
(_a = this.types).splice.apply(_a, __spreadArrays([0, this.types.length], dataTransfer.types));
}
if (dataTransfer.files) {
this.files.splice(0, this.files.length);
for (var i = 0; i < dataTransfer.files.length; i++) {
var file = dataTransfer.files.item(i);
if (file && (file.size || file.type)) {
this.files.push(file);
}
}
}
};
DesktopDragAndDropData.prototype.getData = function () {
return {
types: this.types,
files: this.files
};
};
return DesktopDragAndDropData;
}());
exports.DesktopDragAndDropData = DesktopDragAndDropData;
function equalsDragFeedback(f1, f2) {
if (Array.isArray(f1) && Array.isArray(f2)) {
return arrays_1.equals(f1, f2);
}
return f1 === f2;
}
var ListView = /** @class */ (function () {
function ListView(container, virtualDelegate, renderers, options) {
var _this = this;
if (options === void 0) { options = DefaultOptions; }
this.virtualDelegate = virtualDelegate;
this.domId = "list_id_" + ++ListView.InstanceCount;
this.renderers = new Map();
this.renderWidth = 0;
this._scrollHeight = 0;
this.scrollableElementUpdateDisposable = null;
this.scrollableElementWidthDelayer = new async_1.Delayer(50);
this.splicing = false;
this.dragOverAnimationStopDisposable = lifecycle_1.Disposable.None;
this.dragOverMouseY = 0;
this.canDrop = false;
this.currentDragFeedbackDisposable = lifecycle_1.Disposable.None;
this.onDragLeaveTimeout = lifecycle_1.Disposable.None;
this.disposables = new lifecycle_1.DisposableStore();
this._onDidChangeContentHeight = new event_1.Emitter();
if (options.horizontalScrolling && options.supportDynamicHeights) {
throw new Error('Horizontal scrolling and dynamic heights not supported simultaneously');
}
this.items = [];
this.itemId = 0;
this.rangeMap = new rangeMap_1.RangeMap();
for (var _i = 0, renderers_1 = renderers; _i < renderers_1.length; _i++) {
var renderer = renderers_1[_i];
this.renderers.set(renderer.templateId, renderer);
}
this.cache = this.disposables.add(new rowCache_1.RowCache(this.renderers));
this.lastRenderTop = 0;
this.lastRenderHeight = 0;
this.domNode = document.createElement('div');
this.domNode.className = 'monaco-list';
DOM.addClass(this.domNode, this.domId);
this.domNode.tabIndex = 0;
DOM.toggleClass(this.domNode, 'mouse-support', typeof options.mouseSupport === 'boolean' ? options.mouseSupport : true);
this.horizontalScrolling = objects_1.getOrDefault(options, function (o) { return o.horizontalScrolling; }, DefaultOptions.horizontalScrolling);
DOM.toggleClass(this.domNode, 'horizontal-scrolling', this.horizontalScrolling);
this.additionalScrollHeight = typeof options.additionalScrollHeight === 'undefined' ? 0 : options.additionalScrollHeight;
this.ariaProvider = options.ariaProvider || { getSetSize: function (e, i, length) { return length; }, getPosInSet: function (_, index) { return index + 1; } };
this.rowsContainer = document.createElement('div');
this.rowsContainer.className = 'monaco-list-rows';
this.rowsContainer.style.transform = 'translate3d(0px, 0px, 0px)';
this.disposables.add(touch_1.Gesture.addTarget(this.rowsContainer));
this.scrollableElement = this.disposables.add(new scrollableElement_1.ScrollableElement(this.rowsContainer, {
alwaysConsumeMouseWheel: true,
horizontal: this.horizontalScrolling ? 1 /* Auto */ : 2 /* Hidden */,
vertical: objects_1.getOrDefault(options, function (o) { return o.verticalScrollMode; }, DefaultOptions.verticalScrollMode),
useShadows: objects_1.getOrDefault(options, function (o) { return o.useShadows; }, DefaultOptions.useShadows)
}));
this.domNode.appendChild(this.scrollableElement.getDomNode());
container.appendChild(this.domNode);
this.scrollableElement.onScroll(this.onScroll, this, this.disposables);
event_2.domEvent(this.rowsContainer, touch_1.EventType.Change)(this.onTouchChange, this, this.disposables);
// Prevent the monaco-scrollable-element from scrolling
// https://github.com/Microsoft/vscode/issues/44181
event_2.domEvent(this.scrollableElement.getDomNode(), 'scroll')(function (e) { return e.target.scrollTop = 0; }, null, this.disposables);
event_1.Event.map(event_2.domEvent(this.domNode, 'dragover'), function (e) { return _this.toDragEvent(e); })(this.onDragOver, this, this.disposables);
event_1.Event.map(event_2.domEvent(this.domNode, 'drop'), function (e) { return _this.toDragEvent(e); })(this.onDrop, this, this.disposables);
event_2.domEvent(this.domNode, 'dragleave')(this.onDragLeave, this, this.disposables);
event_2.domEvent(window, 'dragend')(this.onDragEnd, this, this.disposables);
this.setRowLineHeight = objects_1.getOrDefault(options, function (o) { return o.setRowLineHeight; }, DefaultOptions.setRowLineHeight);
this.supportDynamicHeights = objects_1.getOrDefault(options, function (o) { return o.supportDynamicHeights; }, DefaultOptions.supportDynamicHeights);
this.dnd = objects_1.getOrDefault(options, function (o) { return o.dnd; }, DefaultOptions.dnd);
this.layout();
}
Object.defineProperty(ListView.prototype, "contentHeight", {
get: function () { return this.rangeMap.size; },
enumerable: true,
configurable: true
});
ListView.prototype.splice = function (start, deleteCount, elements) {
if (elements === void 0) { elements = []; }
if (this.splicing) {
throw new Error('Can\'t run recursive splices.');
}
this.splicing = true;
try {
return this._splice(start, deleteCount, elements);
}
finally {
this.splicing = false;
this._onDidChangeContentHeight.fire(this.contentHeight);
}
};
ListView.prototype._splice = function (start, deleteCount, elements) {
var _a;
var _this = this;
if (elements === void 0) { elements = []; }
var previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
var deleteRange = { start: start, end: start + deleteCount };
var removeRange = range_1.Range.intersect(previousRenderRange, deleteRange);
for (var i = removeRange.start; i < removeRange.end; i++) {
this.removeItemFromDOM(i);
}
var previousRestRange = { start: start + deleteCount, end: this.items.length };
var previousRenderedRestRange = range_1.Range.intersect(previousRestRange, previousRenderRange);
var previousUnrenderedRestRanges = range_1.Range.relativeComplement(previousRestRange, previousRenderRange);
var inserted = elements.map(function (element) { return ({
id: String(_this.itemId++),
element: element,
templateId: _this.virtualDelegate.getTemplateId(element),
size: _this.virtualDelegate.getHeight(element),
width: undefined,
hasDynamicHeight: !!_this.virtualDelegate.hasDynamicHeight && _this.virtualDelegate.hasDynamicHeight(element),
lastDynamicHeightWidth: undefined,
row: null,
uri: undefined,
dropTarget: false,
dragStartDisposable: lifecycle_1.Disposable.None
}); });
var deleted;
// TODO@joao: improve this optimization to catch even more cases
if (start === 0 && deleteCount >= this.items.length) {
this.rangeMap = new rangeMap_1.RangeMap();
this.rangeMap.splice(0, 0, inserted);
this.items = inserted;
deleted = [];
}
else {
this.rangeMap.splice(start, deleteCount, inserted);
deleted = (_a = this.items).splice.apply(_a, __spreadArrays([start, deleteCount], inserted));
}
var delta = elements.length - deleteCount;
var renderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
var renderedRestRange = rangeMap_1.shift(previousRenderedRestRange, delta);
var updateRange = range_1.Range.intersect(renderRange, renderedRestRange);
for (var i = updateRange.start; i < updateRange.end; i++) {
this.updateItemInDOM(this.items[i], i);
}
var removeRanges = range_1.Range.relativeComplement(renderedRestRange, renderRange);
for (var _i = 0, removeRanges_1 = removeRanges; _i < removeRanges_1.length; _i++) {
var range = removeRanges_1[_i];
for (var i = range.start; i < range.end; i++) {
this.removeItemFromDOM(i);
}
}
var unrenderedRestRanges = previousUnrenderedRestRanges.map(function (r) { return rangeMap_1.shift(r, delta); });
var elementsRange = { start: start, end: start + elements.length };
var insertRanges = __spreadArrays([elementsRange], unrenderedRestRanges).map(function (r) { return range_1.Range.intersect(renderRange, r); });
var beforeElement = this.getNextToLastElement(insertRanges);
for (var _b = 0, insertRanges_1 = insertRanges; _b < insertRanges_1.length; _b++) {
var range = insertRanges_1[_b];
for (var i = range.start; i < range.end; i++) {
this.insertItemInDOM(i, beforeElement);
}
}
this.eventuallyUpdateScrollDimensions();
if (this.supportDynamicHeights) {
this._rerender(this.scrollTop, this.renderHeight);
}
return deleted.map(function (i) { return i.element; });
};
ListView.prototype.eventuallyUpdateScrollDimensions = function () {
var _this = this;
this._scrollHeight = this.contentHeight;
this.rowsContainer.style.height = this._scrollHeight + "px";
if (!this.scrollableElementUpdateDisposable) {
this.scrollableElementUpdateDisposable = DOM.scheduleAtNextAnimationFrame(function () {
_this.scrollableElement.setScrollDimensions({ scrollHeight: _this.scrollHeight });
_this.updateScrollWidth();
_this.scrollableElementUpdateDisposable = null;
});
}
};
ListView.prototype.eventuallyUpdateScrollWidth = function () {
var _this = this;
if (!this.horizontalScrolling) {
return;
}
this.scrollableElementWidthDelayer.trigger(function () { return _this.updateScrollWidth(); });
};
ListView.prototype.updateScrollWidth = function () {
if (!this.horizontalScrolling) {
return;
}
if (this.items.length === 0) {
this.scrollableElement.setScrollDimensions({ scrollWidth: 0 });
}
var scrollWidth = 0;
for (var _i = 0, _a = this.items; _i < _a.length; _i++) {
var item = _a[_i];
if (typeof item.width !== 'undefined') {
scrollWidth = Math.max(scrollWidth, item.width);
}
}
this.scrollWidth = scrollWidth;
this.scrollableElement.setScrollDimensions({ scrollWidth: scrollWidth + 10 });
};
ListView.prototype.rerender = function () {
if (!this.supportDynamicHeights) {
return;
}
for (var _i = 0, _a = this.items; _i < _a.length; _i++) {
var item = _a[_i];
item.lastDynamicHeightWidth = undefined;
}
this._rerender(this.lastRenderTop, this.lastRenderHeight);
};
Object.defineProperty(ListView.prototype, "length", {
get: function () {
return this.items.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ListView.prototype, "renderHeight", {
get: function () {
var scrollDimensions = this.scrollableElement.getScrollDimensions();
return scrollDimensions.height;
},
enumerable: true,
configurable: true
});
ListView.prototype.element = function (index) {
return this.items[index].element;
};
ListView.prototype.domElement = function (index) {
var row = this.items[index].row;
return row && row.domNode;
};
ListView.prototype.elementHeight = function (index) {
return this.items[index].size;
};
ListView.prototype.elementTop = function (index) {
return this.rangeMap.positionAt(index);
};
ListView.prototype.indexAt = function (position) {
return this.rangeMap.indexAt(position);
};
ListView.prototype.indexAfter = function (position) {
return this.rangeMap.indexAfter(position);
};
ListView.prototype.layout = function (height, width) {
var scrollDimensions = {
height: typeof height === 'number' ? height : DOM.getContentHeight(this.domNode)
};
if (this.scrollableElementUpdateDisposable) {
this.scrollableElementUpdateDisposable.dispose();
this.scrollableElementUpdateDisposable = null;
scrollDimensions.scrollHeight = this.scrollHeight;
}
this.scrollableElement.setScrollDimensions(scrollDimensions);
if (typeof width !== 'undefined') {
this.renderWidth = width;
if (this.supportDynamicHeights) {
this._rerender(this.scrollTop, this.renderHeight);
}
if (this.horizontalScrolling) {
this.scrollableElement.setScrollDimensions({
width: typeof width === 'number' ? width : DOM.getContentWidth(this.domNode)
});
}
}
};
// Render
ListView.prototype.render = function (renderTop, renderHeight, renderLeft, scrollWidth) {
var previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
var renderRange = this.getRenderRange(renderTop, renderHeight);
var rangesToInsert = range_1.Range.relativeComplement(renderRange, previousRenderRange);
var rangesToRemove = range_1.Range.relativeComplement(previousRenderRange, renderRange);
var beforeElement = this.getNextToLastElement(rangesToInsert);
for (var _i = 0, rangesToInsert_1 = rangesToInsert; _i < rangesToInsert_1.length; _i++) {
var range = rangesToInsert_1[_i];
for (var i = range.start; i < range.end; i++) {
this.insertItemInDOM(i, beforeElement);
}
}
for (var _a = 0, rangesToRemove_1 = rangesToRemove; _a < rangesToRemove_1.length; _a++) {
var range = rangesToRemove_1[_a];
for (var i = range.start; i < range.end; i++) {
this.removeItemFromDOM(i);
}
}
this.rowsContainer.style.left = "-" + renderLeft + "px";
this.rowsContainer.style.top = "-" + renderTop + "px";
if (this.horizontalScrolling) {
this.rowsContainer.style.width = Math.max(scrollWidth, this.renderWidth) + "px";
}
this.lastRenderTop = renderTop;
this.lastRenderHeight = renderHeight;
};
// DOM operations
ListView.prototype.insertItemInDOM = function (index, beforeElement) {
var _this = this;
var item = this.items[index];
if (!item.row) {
item.row = this.cache.alloc(item.templateId);
var role = this.ariaProvider.getRole ? this.ariaProvider.getRole(item.element) : 'treeitem';
item.row.domNode.setAttribute('role', role);
var checked = this.ariaProvider.isChecked ? this.ariaProvider.isChecked(item.element) : undefined;
if (typeof checked !== 'undefined') {
item.row.domNode.setAttribute('aria-checked', String(checked));
}
}
if (!item.row.domNode.parentElement) {
if (beforeElement) {
this.rowsContainer.insertBefore(item.row.domNode, beforeElement);
}
else {
this.rowsContainer.appendChild(item.row.domNode);
}
}
this.updateItemInDOM(item, index);
var renderer = this.renderers.get(item.templateId);
if (!renderer) {
throw new Error("No renderer found for template id " + item.templateId);
}
if (renderer) {
renderer.renderElement(item.element, index, item.row.templateData, item.size);
}
var uri = this.dnd.getDragURI(item.element);
item.dragStartDisposable.dispose();
item.row.domNode.draggable = !!uri;
if (uri) {
var onDragStart = event_2.domEvent(item.row.domNode, 'dragstart');
item.dragStartDisposable = onDragStart(function (event) { return _this.onDragStart(item.element, uri, event); });
}
if (this.horizontalScrolling) {
this.measureItemWidth(item);
this.eventuallyUpdateScrollWidth();
}
};
ListView.prototype.measureItemWidth = function (item) {
if (!item.row || !item.row.domNode) {
return;
}
item.row.domNode.style.width = browser_1.isFirefox ? '-moz-fit-content' : 'fit-content';
item.width = DOM.getContentWidth(item.row.domNode);
var style = window.getComputedStyle(item.row.domNode);
if (style.paddingLeft) {
item.width += parseFloat(style.paddingLeft);
}
if (style.paddingRight) {
item.width += parseFloat(style.paddingRight);
}
item.row.domNode.style.width = '';
};
ListView.prototype.updateItemInDOM = function (item, index) {
item.row.domNode.style.top = this.elementTop(index) + "px";
item.row.domNode.style.height = item.size + "px";
if (this.setRowLineHeight) {
item.row.domNode.style.lineHeight = item.size + "px";
}
item.row.domNode.setAttribute('data-index', "" + index);
item.row.domNode.setAttribute('data-last-element', index === this.length - 1 ? 'true' : 'false');
item.row.domNode.setAttribute('aria-setsize', String(this.ariaProvider.getSetSize(item.element, index, this.length)));
item.row.domNode.setAttribute('aria-posinset', String(this.ariaProvider.getPosInSet(item.element, index)));
item.row.domNode.setAttribute('id', this.getElementDomId(index));
DOM.toggleClass(item.row.domNode, 'drop-target', item.dropTarget);
};
ListView.prototype.removeItemFromDOM = function (index) {
var item = this.items[index];
item.dragStartDisposable.dispose();
var renderer = this.renderers.get(item.templateId);
if (renderer && renderer.disposeElement) {
renderer.disposeElement(item.element, index, item.row.templateData, item.size);
}
this.cache.release(item.row);
item.row = null;
if (this.horizontalScrolling) {
this.eventuallyUpdateScrollWidth();
}
};
ListView.prototype.getScrollTop = function () {
var scrollPosition = this.scrollableElement.getScrollPosition();
return scrollPosition.scrollTop;
};
ListView.prototype.setScrollTop = function (scrollTop) {
if (this.scrollableElementUpdateDisposable) {
this.scrollableElementUpdateDisposable.dispose();
this.scrollableElementUpdateDisposable = null;
this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
}
this.scrollableElement.setScrollPosition({ scrollTop: scrollTop });
};
Object.defineProperty(ListView.prototype, "scrollTop", {
get: function () {
return this.getScrollTop();
},
set: function (scrollTop) {
this.setScrollTop(scrollTop);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ListView.prototype, "scrollHeight", {
get: function () {
return this._scrollHeight + (this.horizontalScrolling ? 10 : 0) + this.additionalScrollHeight;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ListView.prototype, "onMouseClick", {
// Events
get: function () {
var _this = this;
return event_1.Event.map(event_2.domEvent(this.domNode, 'click'), function (e) { return _this.toMouseEvent(e); });
},
enumerable: true,
configurable: true
});
Object.defineProperty(ListView.prototype, "onMouseDblClick", {
get: function () {
var _this = this;
return event_1.Event.map(event_2.domEvent(this.domNode, 'dblclick'), function (e) { return _this.toMouseEvent(e); });
},
enumerable: true,
configurable: true
});
Object.defineProperty(ListView.prototype, "onMouseMiddleClick", {
get: function () {
var _this = this;
return event_1.Event.filter(event_1.Event.map(event_2.domEvent(this.domNode, 'auxclick'), function (e) { return _this.toMouseEvent(e); }), function (e) { return e.browserEvent.button === 1; });
},
enumerable: true,
configurable: true
});
Object.defineProperty(ListView.prototype, "onMouseDown", {
get: function () {
var _this = this;
return event_1.Event.map(event_2.domEvent(this.domNode, 'mousedown'), function (e) { return _this.toMouseEvent(e); });
},
enumerable: true,
configurable: true
});
Object.defineProperty(ListView.prototype, "onContextMenu", {
get: function () {
var _this = this;
return event_1.Event.map(event_2.domEvent(this.domNode, 'contextmenu'), function (e) { return _this.toMouseEvent(e); });
},
enumerable: true,
configurable: true
});
Object.defineProperty(ListView.prototype, "onTouchStart", {
get: function () {
var _this = this;
return event_1.Event.map(event_2.domEvent(this.domNode, 'touchstart'), function (e) { return _this.toTouchEvent(e); });
},
enumerable: true,
configurable: true
});
Object.defineProperty(ListView.prototype, "onTap", {
get: function () {
var _this = this;
return event_1.Event.map(event_2.domEvent(this.rowsContainer, touch_1.EventType.Tap), function (e) { return _this.toGestureEvent(e); });
},
enumerable: true,
configurable: true
});
ListView.prototype.toMouseEvent = function (browserEvent) {
var index = this.getItemIndexFromEventTarget(browserEvent.target || null);
var item = typeof index === 'undefined' ? undefined : this.items[index];
var element = item && item.element;
return { browserEvent: browserEvent, index: index, element: element };
};
ListView.prototype.toTouchEvent = function (browserEvent) {
var index = this.getItemIndexFromEventTarget(browserEvent.target || null);
var item = typeof index === 'undefined' ? undefined : this.items[index];
var element = item && item.element;
return { browserEvent: browserEvent, index: index, element: element };
};
ListView.prototype.toGestureEvent = function (browserEvent) {
var index = this.getItemIndexFromEventTarget(browserEvent.initialTarget || null);
var item = typeof index === 'undefined' ? undefined : this.items[index];
var element = item && item.element;
return { browserEvent: browserEvent, index: index, element: element };
};
ListView.prototype.toDragEvent = function (browserEvent) {
var index = this.getItemIndexFromEventTarget(browserEvent.target || null);
var item = typeof index === 'undefined' ? undefined : this.items[index];
var element = item && item.element;
return { browserEvent: browserEvent, index: index, element: element };
};
ListView.prototype.onScroll = function (e) {
try {
this.render(e.scrollTop, e.height, e.scrollLeft, e.scrollWidth);
if (this.supportDynamicHeights) {
this._rerender(e.scrollTop, e.height);
}
}
catch (err) {
console.error('Got bad scroll event:', e);
throw err;
}
};
ListView.prototype.onTouchChange = function (event) {
event.preventDefault();
event.stopPropagation();
this.scrollTop -= event.translationY;
};
// DND
ListView.prototype.onDragStart = function (element, uri, event) {
if (!event.dataTransfer) {
return;
}
var elements = this.dnd.getDragElements(element);
event.dataTransfer.effectAllowed = 'copyMove';
event.dataTransfer.setData(dnd_1.DataTransfers.RESOURCES, JSON.stringify([uri]));
if (event.dataTransfer.setDragImage) {
var label = void 0;
if (this.dnd.getDragLabel) {
label = this.dnd.getDragLabel(elements, event);
}
if (typeof label === 'undefined') {
label = String(elements.length);
}
var dragImage_1 = DOM.$('.monaco-drag-image');
dragImage_1.textContent = label;
document.body.appendChild(dragImage_1);
event.dataTransfer.setDragImage(dragImage_1, -10, -10);
setTimeout(function () { return document.body.removeChild(dragImage_1); }, 0);
}
this.currentDragData = new ElementsDragAndDropData(elements);
dnd_1.StaticDND.CurrentDragAndDropData = new ExternalElementsDragAndDropData(elements);
if (this.dnd.onDragStart) {
this.dnd.onDragStart(this.currentDragData, event);
}
};
ListView.prototype.onDragOver = function (event) {
var _this = this;
event.browserEvent.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
this.onDragLeaveTimeout.dispose();
if (dnd_1.StaticDND.CurrentDragAndDropData && dnd_1.StaticDND.CurrentDragAndDropData.getData() === 'vscode-ui') {
return false;
}
this.setupDragAndDropScrollTopAnimation(event.browserEvent);
if (!event.browserEvent.dataTransfer) {
return false;
}
// Drag over from outside
if (!this.currentDragData) {
if (dnd_1.StaticDND.CurrentDragAndDropData) {
// Drag over from another list
this.currentDragData = dnd_1.StaticDND.CurrentDragAndDropData;
}
else {
// Drag over from the desktop
if (!event.browserEvent.dataTransfer.types) {
return false;
}
this.currentDragData = new DesktopDragAndDropData();
}
}
var result = this.dnd.onDragOver(this.currentDragData, event.element, event.index, event.browserEvent);
this.canDrop = typeof result === 'boolean' ? result : result.accept;
if (!this.canDrop) {
this.currentDragFeedback = undefined;
this.currentDragFeedbackDisposable.dispose();
return false;
}
event.browserEvent.dataTransfer.dropEffect = (typeof result !== 'boolean' && result.effect === 0 /* Copy */) ? 'copy' : 'move';
var feedback;
if (typeof result !== 'boolean' && result.feedback) {
feedback = result.feedback;
}
else {
if (typeof event.index === 'undefined') {
feedback = [-1];
}
else {
feedback = [event.index];
}
}
// sanitize feedback list
feedback = arrays_1.distinct(feedback).filter(function (i) { return i >= -1 && i < _this.length; }).sort(function (a, b) { return a - b; });
feedback = feedback[0] === -1 ? [-1] : feedback;
if (equalsDragFeedback(this.currentDragFeedback, feedback)) {
return true;
}
this.currentDragFeedback = feedback;
this.currentDragFeedbackDisposable.dispose();
if (feedback[0] === -1) { // entire list feedback
DOM.addClass(this.domNode, 'drop-target');
DOM.addClass(this.rowsContainer, 'drop-target');
this.currentDragFeedbackDisposable = lifecycle_1.toDisposable(function () {
DOM.removeClass(_this.domNode, 'drop-target');
DOM.removeClass(_this.rowsContainer, 'drop-target');
});
}
else {
for (var _i = 0, feedback_1 = feedback; _i < feedback_1.length; _i++) {
var index = feedback_1[_i];
var item = this.items[index];
item.dropTarget = true;
if (item.row && item.row.domNode) {
DOM.addClass(item.row.domNode, 'drop-target');
}
}
this.currentDragFeedbackDisposable = lifecycle_1.toDisposable(function () {
for (var _i = 0, feedback_2 = feedback; _i < feedback_2.length; _i++) {
var index = feedback_2[_i];
var item = _this.items[index];
item.dropTarget = false;
if (item.row && item.row.domNode) {
DOM.removeClass(item.row.domNode, 'drop-target');
}
}
});
}
return true;
};
ListView.prototype.onDragLeave = function () {
var _this = this;
this.onDragLeaveTimeout.dispose();
this.onDragLeaveTimeout = async_1.disposableTimeout(function () { return _this.clearDragOverFeedback(); }, 100);
};
ListView.prototype.onDrop = function (event) {
if (!this.canDrop) {
return;
}
var dragData = this.currentDragData;
this.teardownDragAndDropScrollTopAnimation();
this.clearDragOverFeedback();
this.currentDragData = undefined;
dnd_1.StaticDND.CurrentDragAndDropData = undefined;
if (!dragData || !event.browserEvent.dataTransfer) {
return;
}
event.browserEvent.preventDefault();
dragData.update(event.browserEvent.dataTransfer);
this.dnd.drop(dragData, event.element, event.index, event.browserEvent);
};
ListView.prototype.onDragEnd = function (event) {
this.canDrop = false;
this.teardownDragAndDropScrollTopAnimation();
this.clearDragOverFeedback();
this.currentDragData = undefined;
dnd_1.StaticDND.CurrentDragAndDropData = undefined;
if (this.dnd.onDragEnd) {
this.dnd.onDragEnd(event);
}
};
ListView.prototype.clearDragOverFeedback = function () {
this.currentDragFeedback = undefined;
this.currentDragFeedbackDisposable.dispose();
this.currentDragFeedbackDisposable = lifecycle_1.Disposable.None;
};
// DND scroll top animation
ListView.prototype.setupDragAndDropScrollTopAnimation = function (event) {
var _this = this;
if (!this.dragOverAnimationDisposable) {
var viewTop = DOM.getTopLeftOffset(this.domNode).top;
this.dragOverAnimationDisposable = DOM.animate(this.animateDragAndDropScrollTop.bind(this, viewTop));
}
this.dragOverAnimationStopDisposable.dispose();
this.dragOverAnimationStopDisposable = async_1.disposableTimeout(function () {
if (_this.dragOverAnimationDisposable) {
_this.dragOverAnimationDisposable.dispose();
_this.dragOverAnimationDisposable = undefined;
}
}, 1000);
this.dragOverMouseY = event.pageY;
};
ListView.prototype.animateDragAndDropScrollTop = function (viewTop) {
if (this.dragOverMouseY === undefined) {
return;
}
var diff = this.dragOverMouseY - viewTop;
var upperLimit = this.renderHeight - 35;
if (diff < 35) {
this.scrollTop += Math.max(-14, Math.floor(0.3 * (diff - 35)));
}
else if (diff > upperLimit) {
this.scrollTop += Math.min(14, Math.floor(0.3 * (diff - upperLimit)));
}
};
ListView.prototype.teardownDragAndDropScrollTopAnimation = function () {
this.dragOverAnimationStopDisposable.dispose();
if (this.dragOverAnimationDisposable) {
this.dragOverAnimationDisposable.dispose();
this.dragOverAnimationDisposable = undefined;
}
};
// Util
ListView.prototype.getItemIndexFromEventTarget = function (target) {
var element = target;
while (element instanceof HTMLElement && element !== this.rowsContainer) {
var rawIndex = element.getAttribute('data-index');
if (rawIndex) {
var index = Number(rawIndex);
if (!isNaN(index)) {
return index;
}
}
element = element.parentElement;
}
return undefined;
};
ListView.prototype.getRenderRange = function (renderTop, renderHeight) {
return {
start: this.rangeMap.indexAt(renderTop),
end: this.rangeMap.indexAfter(renderTop + renderHeight - 1)
};
};
/**
* Given a stable rendered state, checks every rendered element whether it needs
* to be probed for dynamic height. Adjusts scroll height and top if necessary.
*/
ListView.prototype._rerender = function (renderTop, renderHeight) {
var previousRenderRange = this.getRenderRange(renderTop, renderHeight);
// Let's remember the second element's position, this helps in scrolling up
// and preserving a linear upwards scroll movement
var anchorElementIndex;
var anchorElementTopDelta;
if (renderTop === this.elementTop(previousRenderRange.start)) {
anchorElementIndex = previousRenderRange.start;
anchorElementTopDelta = 0;
}
else if (previousRenderRange.end - previousRenderRange.start > 1) {
anchorElementIndex = previousRenderRange.start + 1;
anchorElementTopDelta = this.elementTop(anchorElementIndex) - renderTop;
}
var heightDiff = 0;
while (true) {
var renderRange = this.getRenderRange(renderTop, renderHeight);
var didChange = false;
for (var i = renderRange.start; i < renderRange.end; i++) {
var diff = this.probeDynamicHeight(i);
if (diff !== 0) {
this.rangeMap.splice(i, 1, [this.items[i]]);
}
heightDiff += diff;
didChange = didChange || diff !== 0;
}
if (!didChange) {
if (heightDiff !== 0) {
this.eventuallyUpdateScrollDimensions();
}
var unrenderRanges = range_1.Range.relativeComplement(previousRenderRange, renderRange);
for (var _i = 0, unrenderRanges_1 = unrenderRanges; _i < unrenderRanges_1.length; _i++) {
var range = unrenderRanges_1[_i];
for (var i = range.start; i < range.end; i++) {
if (this.items[i].row) {
this.removeItemFromDOM(i);
}
}
}
var renderRanges = range_1.Range.relativeComplement(renderRange, previousRenderRange);
for (var _a = 0, renderRanges_1 = renderRanges; _a < renderRanges_1.length; _a++) {
var range = renderRanges_1[_a];
for (var i = range.start; i < range.end; i++) {
var afterIndex = i + 1;
var beforeRow = afterIndex < this.items.length ? this.items[afterIndex].row : null;
var beforeElement = beforeRow ? beforeRow.domNode : null;
this.insertItemInDOM(i, beforeElement);
}
}
for (var i = renderRange.start; i < renderRange.end; i++) {
if (this.items[i].row) {
this.updateItemInDOM(this.items[i], i);
}
}
if (typeof anchorElementIndex === 'number') {
this.scrollTop = this.elementTop(anchorElementIndex) - anchorElementTopDelta;
}
this._onDidChangeContentHeight.fire(this.contentHeight);
return;
}
}
};
ListView.prototype.probeDynamicHeight = function (index) {
var item = this.items[index];
if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) {
return 0;
}
var size = item.size;
var row = this.cache.alloc(item.templateId);
row.domNode.style.height = '';
this.rowsContainer.appendChild(row.domNode);
var renderer = this.renderers.get(item.templateId);
if (renderer) {
renderer.renderElement(item.element, index, row.templateData, undefined);
if (renderer.disposeElement) {
renderer.disposeElement(item.element, index, row.templateData, undefined);
}
}
item.size = row.domNode.offsetHeight;
if (this.virtualDelegate.setDynamicHeight) {
this.virtualDelegate.setDynamicHeight(item.element, item.size);
}
item.lastDynamicHeightWidth = this.renderWidth;
this.rowsContainer.removeChild(row.domNode);
this.cache.release(row);
return item.size - size;
};
ListView.prototype.getNextToLastElement = function (ranges) {
var lastRange = ranges[ranges.length - 1];
if (!lastRange) {
return null;
}
var nextToLastItem = this.items[lastRange.end];
if (!nextToLastItem) {
return null;
}
if (!nextToLastItem.row) {
return null;
}
return nextToLastItem.row.domNode;
};
ListView.prototype.getElementDomId = function (index) {
return this.domId + "_" + index;
};
// Dispose
ListView.prototype.dispose = function () {
if (this.items) {
for (var _i = 0, _a = this.items; _i < _a.length; _i++) {
var item = _a[_i];
if (item.row) {
var renderer = this.renderers.get(item.row.templateId);
if (renderer) {
renderer.disposeTemplate(item.row.templateData);
}
}
}
this.items = [];
}
if (this.domNode && this.domNode.parentNode) {
this.domNode.parentNode.removeChild(this.domNode);
}
lifecycle_1.dispose(this.disposables);
};
ListView.InstanceCount = 0;
__decorate([
decorators_1.memoize
], ListView.prototype, "onMouseClick", null);
__decorate([
decorators_1.memoize
], ListView.prototype, "onMouseDblClick", null);
__decorate([
decorators_1.memoize
], ListView.prototype, "onMouseMiddleClick", null);
__decorate([
decorators_1.memoize
], ListView.prototype, "onMouseDown", null);
__decorate([
decorators_1.memoize
], ListView.prototype, "onContextMenu", null);
__decorate([
decorators_1.memoize
], ListView.prototype, "onTouchStart", null);
__decorate([
decorators_1.memoize
], ListView.prototype, "onTap", null);
return ListView;
}());
exports.ListView = ListView;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[277/*vs/base/parts/tree/browser/treeView*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,24/*vs/base/browser/browser*/,2/*vs/base/common/lifecycle*/,6/*vs/base/browser/dom*/,126/*vs/base/common/diff/diff*/,57/*vs/base/browser/touch*/,5/*vs/base/common/strings*/,45/*vs/base/browser/mouseEvent*/,56/*vs/base/browser/keyboardEvent*/,255/*vs/base/parts/tree/browser/treeDnd*/,54/*vs/base/common/iterator*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,257/*vs/base/parts/tree/browser/treeViewModel*/,254/*vs/base/parts/tree/browser/tree*/,4/*vs/base/common/event*/,98/*vs/base/browser/dnd*/,137/*vs/base/parts/tree/browser/treeDefaults*/,15/*vs/base/common/async*/]), function (require, exports, Platform, Browser, Lifecycle, DOM, Diff, Touch, strings, Mouse, Keyboard, dnd, iterator_1, scrollableElement_1, treeViewModel_1, _, event_1, dnd_1, treeDefaults_1, async_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function removeFromParent(element) {
try {
element.parentElement.removeChild(element);
}
catch (e) {
// this will throw if this happens due to a blur event, nasty business
}
}
var RowCache = /** @class */ (function () {
function RowCache(context) {
this.context = context;
this._cache = { '': [] };
}
RowCache.prototype.alloc = function (templateId) {
var result = this.cache(templateId).pop();
if (!result) {
var content = document.createElement('div');
content.className = 'content';
var row = document.createElement('div');
row.appendChild(content);
var templateData = null;
try {
templateData = this.context.renderer.renderTemplate(this.context.tree, templateId, content);
}
catch (err) {
console.error('Tree usage error: exception while rendering template');
console.error(err);
}
result = {
element: row,
templateId: templateId,
templateData: templateData
};
}
return result;
};
RowCache.prototype.release = function (templateId, row) {
removeFromParent(row.element);
this.cache(templateId).push(row);
};
RowCache.prototype.cache = function (templateId) {
return this._cache[templateId] || (this._cache[templateId] = []);
};
RowCache.prototype.garbageCollect = function () {
var _this = this;
if (this._cache) {
Object.keys(this._cache).forEach(function (templateId) {
_this._cache[templateId].forEach(function (cachedRow) {
_this.context.renderer.disposeTemplate(_this.context.tree, templateId, cachedRow.templateData);
cachedRow.element = null;
cachedRow.templateData = null;
});
delete _this._cache[templateId];
});
}
};
RowCache.prototype.dispose = function () {
this.garbageCollect();
this._cache = null;
};
return RowCache;
}());
exports.RowCache = RowCache;
var ViewItem = /** @class */ (function () {
function ViewItem(context, model) {
var _this = this;
this.width = 0;
this.needsRender = false;
this.uri = null;
this.unbindDragStart = Lifecycle.Disposable.None;
this._draggable = false;
this.context = context;
this.model = model;
this.id = this.model.id;
this.row = null;
this.top = 0;
this.height = model.getHeight();
this._styles = {};
model.getAllTraits().forEach(function (t) { return _this._styles[t] = true; });
if (model.isExpanded()) {
this.addClass('expanded');
}
}
Object.defineProperty(ViewItem.prototype, "expanded", {
set: function (value) {
value ? this.addClass('expanded') : this.removeClass('expanded');
},
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "loading", {
set: function (value) {
value ? this.addClass('codicon-loading') : this.removeClass('codicon-loading');
},
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "draggable", {
get: function () {
return this._draggable;
},
set: function (value) {
this._draggable = value;
this.render(true);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "dropTarget", {
set: function (value) {
value ? this.addClass('drop-target') : this.removeClass('drop-target');
},
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "element", {
get: function () {
return (this.row && this.row.element);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "templateId", {
get: function () {
return this._templateId || (this._templateId = (this.context.renderer.getTemplateId && this.context.renderer.getTemplateId(this.context.tree, this.model.getElement())));
},
enumerable: true,
configurable: true
});
ViewItem.prototype.addClass = function (name) {
this._styles[name] = true;
this.render(true);
};
ViewItem.prototype.removeClass = function (name) {
delete this._styles[name]; // is this slow?
this.render(true);
};
ViewItem.prototype.render = function (skipUserRender) {
var _this = this;
if (skipUserRender === void 0) { skipUserRender = false; }
if (!this.model || !this.element) {
return;
}
var classes = ['monaco-tree-row'];
classes.push.apply(classes, Object.keys(this._styles));
if (this.model.hasChildren()) {
classes.push('has-children');
}
this.element.className = classes.join(' ');
this.element.draggable = this.draggable;
this.element.style.height = this.height + 'px';
// ARIA
this.element.setAttribute('role', 'treeitem');
var accessibility = this.context.accessibilityProvider;
var ariaLabel = accessibility.getAriaLabel(this.context.tree, this.model.getElement());
if (ariaLabel) {
this.element.setAttribute('aria-label', ariaLabel);
}
if (accessibility.getPosInSet && accessibility.getSetSize) {
this.element.setAttribute('aria-setsize', accessibility.getSetSize());
this.element.setAttribute('aria-posinset', accessibility.getPosInSet(this.context.tree, this.model.getElement()));
}
if (this.model.hasTrait('focused')) {
var base64Id = strings.safeBtoa(this.model.id);
this.element.setAttribute('aria-selected', 'true');
this.element.setAttribute('id', base64Id);
}
else {
this.element.setAttribute('aria-selected', 'false');
this.element.removeAttribute('id');
}
if (this.model.hasChildren()) {
this.element.setAttribute('aria-expanded', String(!!this._styles['expanded']));
}
else {
this.element.removeAttribute('aria-expanded');
}
this.element.setAttribute('aria-level', String(this.model.getDepth()));
if (this.context.options.paddingOnRow) {
this.element.style.paddingLeft = this.context.options.twistiePixels + ((this.model.getDepth() - 1) * this.context.options.indentPixels) + 'px';
}
else {
this.element.style.paddingLeft = ((this.model.getDepth() - 1) * this.context.options.indentPixels) + 'px';
this.row.element.firstElementChild.style.paddingLeft = this.context.options.twistiePixels + 'px';
}
var uri = this.context.dnd.getDragURI(this.context.tree, this.model.getElement());
if (uri !== this.uri) {
if (this.unbindDragStart) {
this.unbindDragStart.dispose();
}
if (uri) {
this.uri = uri;
this.draggable = true;
this.unbindDragStart = DOM.addDisposableListener(this.element, 'dragstart', function (e) {
_this.onDragStart(e);
});
}
else {
this.uri = null;
}
}
if (!skipUserRender && this.element) {
var paddingLeft = 0;
if (this.context.horizontalScrolling) {
var style = window.getComputedStyle(this.element);
paddingLeft = parseFloat(style.paddingLeft);
}
if (this.context.horizontalScrolling) {
this.element.style.width = Browser.isFirefox ? '-moz-fit-content' : 'fit-content';
}
try {
this.context.renderer.renderElement(this.context.tree, this.model.getElement(), this.templateId, this.row.templateData);
}
catch (err) {
console.error('Tree usage error: exception while rendering element');
console.error(err);
}
if (this.context.horizontalScrolling) {
this.width = DOM.getContentWidth(this.element) + paddingLeft;
this.element.style.width = '';
}
}
};
ViewItem.prototype.insertInDOM = function (container, afterElement) {
if (!this.row) {
this.row = this.context.cache.alloc(this.templateId);
// used in reverse lookup from HTMLElement to Item
this.element[TreeView.BINDING] = this;
}
if (this.element.parentElement) {
return;
}
if (afterElement === null) {
container.appendChild(this.element);
}
else {
try {
container.insertBefore(this.element, afterElement);
}
catch (e) {
console.warn('Failed to locate previous tree element');
container.appendChild(this.element);
}
}
this.render();
};
ViewItem.prototype.removeFromDOM = function () {
if (!this.row) {
return;
}
this.unbindDragStart.dispose();
this.uri = null;
this.element[TreeView.BINDING] = null;
this.context.cache.release(this.templateId, this.row);
this.row = null;
};
ViewItem.prototype.dispose = function () {
this.row = null;
};
return ViewItem;
}());
exports.ViewItem = ViewItem;
var RootViewItem = /** @class */ (function (_super) {
__extends(RootViewItem, _super);
function RootViewItem(context, model, wrapper) {
var _this = _super.call(this, context, model) || this;
_this.row = {
element: wrapper,
templateData: null,
templateId: null
};
return _this;
}
RootViewItem.prototype.render = function () {
if (!this.model || !this.element) {
return;
}
var classes = ['monaco-tree-wrapper'];
classes.push.apply(classes, Object.keys(this._styles));
if (this.model.hasChildren()) {
classes.push('has-children');
}
this.element.className = classes.join(' ');
};
RootViewItem.prototype.insertInDOM = function (container, afterElement) {
// noop
};
RootViewItem.prototype.removeFromDOM = function () {
// noop
};
return RootViewItem;
}(ViewItem));
function reactionEquals(one, other) {
if (!one && !other) {
return true;
}
else if (!one || !other) {
return false;
}
else if (one.accept !== other.accept) {
return false;
}
else if (one.bubble !== other.bubble) {
return false;
}
else if (one.effect !== other.effect) {
return false;
}
else {
return true;
}
}
var TreeView = /** @class */ (function (_super) {
__extends(TreeView, _super);
function TreeView(context, container) {
var _this = _super.call(this) || this;
_this.model = null;
_this.lastPointerType = '';
_this.lastClickTimeStamp = 0;
_this.contentWidthUpdateDelayer = new async_1.Delayer(50);
_this.isRefreshing = false;
_this.refreshingPreviousChildrenIds = {};
_this.currentDragAndDropData = null;
_this.currentDropTarget = null;
_this.currentDropTargets = null;
_this.currentDropDisposable = Lifecycle.Disposable.None;
_this.gestureDisposable = Lifecycle.Disposable.None;
_this.dragAndDropScrollInterval = null;
_this.dragAndDropScrollTimeout = null;
_this.dragAndDropMouseY = null;
_this.highlightedItemWasDraggable = false;
_this.onHiddenScrollTop = null;
_this._onDOMFocus = new event_1.Emitter();
_this.onDOMFocus = _this._onDOMFocus.event;
_this._onDOMBlur = new event_1.Emitter();
_this._onDidScroll = new event_1.Emitter();
TreeView.counter++;
_this.instance = TreeView.counter;
var horizontalScrollMode = typeof context.options.horizontalScrollMode === 'undefined' ? 2 /* Hidden */ : context.options.horizontalScrollMode;
_this.horizontalScrolling = horizontalScrollMode !== 2 /* Hidden */;
_this.context = {
dataSource: context.dataSource,
renderer: context.renderer,
controller: context.controller,
dnd: context.dnd,
filter: context.filter,
sorter: context.sorter,
tree: context.tree,
accessibilityProvider: context.accessibilityProvider,
options: context.options,
cache: new RowCache(context),
horizontalScrolling: _this.horizontalScrolling
};
_this.modelListeners = [];
_this.viewListeners = [];
_this.items = {};
_this.domNode = document.createElement('div');
_this.domNode.className = "monaco-tree no-focused-item monaco-tree-instance-" + _this.instance;
// to allow direct tabbing into the tree instead of first focusing the tree
_this.domNode.tabIndex = context.options.preventRootFocus ? -1 : 0;
_this.styleElement = DOM.createStyleSheet(_this.domNode);
_this.treeStyler = context.styler || new treeDefaults_1.DefaultTreestyler(_this.styleElement, "monaco-tree-instance-" + _this.instance);
// ARIA
_this.domNode.setAttribute('role', 'tree');
if (_this.context.options.ariaLabel) {
_this.domNode.setAttribute('aria-label', _this.context.options.ariaLabel);
}
if (_this.context.options.alwaysFocused) {
DOM.addClass(_this.domNode, 'focused');
}
if (!_this.context.options.paddingOnRow) {
DOM.addClass(_this.domNode, 'no-row-padding');
}
_this.wrapper = document.createElement('div');
_this.wrapper.className = 'monaco-tree-wrapper';
_this.scrollableElement = new scrollableElement_1.ScrollableElement(_this.wrapper, {
alwaysConsumeMouseWheel: true,
horizontal: horizontalScrollMode,
vertical: (typeof context.options.verticalScrollMode !== 'undefined' ? context.options.verticalScrollMode : 1 /* Auto */),
useShadows: context.options.useShadows
});
_this.scrollableElement.onScroll(function (e) {
_this.render(e.scrollTop, e.height, e.scrollLeft, e.width, e.scrollWidth);
_this._onDidScroll.fire();
});
if (Browser.isIE) {
_this.wrapper.style.msTouchAction = 'none';
_this.wrapper.style.msContentZooming = 'none';
}
else {
_this.gestureDisposable = Touch.Gesture.addTarget(_this.wrapper);
}
_this.rowsContainer = document.createElement('div');
_this.rowsContainer.className = 'monaco-tree-rows';
if (context.options.showTwistie) {
_this.rowsContainer.className += ' show-twisties';
}
var focusTracker = DOM.trackFocus(_this.domNode);
_this.viewListeners.push(focusTracker.onDidFocus(function () { return _this.onFocus(); }));
_this.viewListeners.push(focusTracker.onDidBlur(function () { return _this.onBlur(); }));
_this.viewListeners.push(focusTracker);
_this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'keydown', function (e) { return _this.onKeyDown(e); }));
_this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'keyup', function (e) { return _this.onKeyUp(e); }));
_this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'mousedown', function (e) { return _this.onMouseDown(e); }));
_this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'mouseup', function (e) { return _this.onMouseUp(e); }));
_this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'auxclick', function (e) {
if (e && e.button === 1) {
_this.onMouseMiddleClick(e);
}
}));
_this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'click', function (e) { return _this.onClick(e); }));
_this.viewListeners.push(DOM.addDisposableListener(_this.domNode, 'contextmenu', function (e) { return _this.onContextMenu(e); }));
_this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, Touch.EventType.Tap, function (e) { return _this.onTap(e); }));
_this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, Touch.EventType.Change, function (e) { return _this.onTouchChange(e); }));
if (Browser.isIE) {
_this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'MSPointerDown', function (e) { return _this.onMsPointerDown(e); }));
_this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'MSGestureTap', function (e) { return _this.onMsGestureTap(e); }));
// these events come too fast, we throttle them
_this.viewListeners.push(DOM.addDisposableThrottledListener(_this.wrapper, 'MSGestureChange', function (e) { return _this.onThrottledMsGestureChange(e); }, function (lastEvent, event) {
event.stopPropagation();
event.preventDefault();
var result = { translationY: event.translationY, translationX: event.translationX };
if (lastEvent) {
result.translationY += lastEvent.translationY;
result.translationX += lastEvent.translationX;
}
return result;
}));
}
_this.viewListeners.push(DOM.addDisposableListener(window, 'dragover', function (e) { return _this.onDragOver(e); }));
_this.viewListeners.push(DOM.addDisposableListener(_this.wrapper, 'drop', function (e) { return _this.onDrop(e); }));
_this.viewListeners.push(DOM.addDisposableListener(window, 'dragend', function (e) { return _this.onDragEnd(e); }));
_this.viewListeners.push(DOM.addDisposableListener(window, 'dragleave', function (e) { return _this.onDragOver(e); }));
_this.wrapper.appendChild(_this.rowsContainer);
_this.domNode.appendChild(_this.scrollableElement.getDomNode());
container.appendChild(_this.domNode);
_this.lastRenderTop = 0;
_this.lastRenderHeight = 0;
_this.didJustPressContextMenuKey = false;
_this.currentDropTarget = null;
_this.currentDropTargets = [];
_this.shouldInvalidateDropReaction = false;
_this.dragAndDropScrollInterval = null;
_this.dragAndDropScrollTimeout = null;
_this.onRowsChanged();
_this.layout();
_this.setupMSGesture();
_this.applyStyles(context.options);
return _this;
}
TreeView.prototype.applyStyles = function (styles) {
this.treeStyler.style(styles);
};
TreeView.prototype.createViewItem = function (item) {
return new ViewItem(this.context, item);
};
TreeView.prototype.getHTMLElement = function () {
return this.domNode;
};
TreeView.prototype.focus = function () {
this.domNode.focus();
};
TreeView.prototype.isFocused = function () {
return document.activeElement === this.domNode;
};
TreeView.prototype.blur = function () {
this.domNode.blur();
};
TreeView.prototype.setupMSGesture = function () {
var _this = this;
if (window.MSGesture) {
this.msGesture = new MSGesture();
setTimeout(function () { return _this.msGesture.target = _this.wrapper; }, 100); // TODO@joh, TODO@IETeam
}
};
TreeView.prototype.isTreeVisible = function () {
return this.onHiddenScrollTop === null;
};
TreeView.prototype.layout = function (height, width) {
if (!this.isTreeVisible()) {
return;
}
this.viewHeight = height || DOM.getContentHeight(this.wrapper); // render
this.scrollHeight = this.getContentHeight();
if (this.horizontalScrolling) {
this.viewWidth = width || DOM.getContentWidth(this.wrapper);
}
};
TreeView.prototype.render = function (scrollTop, viewHeight, scrollLeft, viewWidth, scrollWidth) {
var i;
var stop;
var renderTop = scrollTop;
var renderBottom = scrollTop + viewHeight;
var thisRenderBottom = this.lastRenderTop + this.lastRenderHeight;
// when view scrolls down, start rendering from the renderBottom
for (i = this.indexAfter(renderBottom) - 1, stop = this.indexAt(Math.max(thisRenderBottom, renderTop)); i >= stop; i--) {
this.insertItemInDOM(this.itemAtIndex(i));
}
// when view scrolls up, start rendering from either this.renderTop or renderBottom
for (i = Math.min(this.indexAt(this.lastRenderTop), this.indexAfter(renderBottom)) - 1, stop = this.indexAt(renderTop); i >= stop; i--) {
this.insertItemInDOM(this.itemAtIndex(i));
}
// when view scrolls down, start unrendering from renderTop
for (i = this.indexAt(this.lastRenderTop), stop = Math.min(this.indexAt(renderTop), this.indexAfter(thisRenderBottom)); i < stop; i++) {
this.removeItemFromDOM(this.itemAtIndex(i));
}
// when view scrolls up, start unrendering from either renderBottom this.renderTop
for (i = Math.max(this.indexAfter(renderBottom), this.indexAt(this.lastRenderTop)), stop = this.indexAfter(thisRenderBottom); i < stop; i++) {
this.removeItemFromDOM(this.itemAtIndex(i));
}
var topItem = this.itemAtIndex(this.indexAt(renderTop));
if (topItem) {
this.rowsContainer.style.top = (topItem.top - renderTop) + 'px';
}
if (this.horizontalScrolling) {
this.rowsContainer.style.left = -scrollLeft + 'px';
this.rowsContainer.style.width = Math.max(scrollWidth, viewWidth) + "px";
}
this.lastRenderTop = renderTop;
this.lastRenderHeight = renderBottom - renderTop;
};
TreeView.prototype.setModel = function (newModel) {
this.releaseModel();
this.model = newModel;
this.model.onRefresh(this.onRefreshing, this, this.modelListeners);
this.model.onDidRefresh(this.onRefreshed, this, this.modelListeners);
this.model.onSetInput(this.onClearingInput, this, this.modelListeners);
this.model.onDidSetInput(this.onSetInput, this, this.modelListeners);
this.model.onDidFocus(this.onModelFocusChange, this, this.modelListeners);
this.model.onRefreshItemChildren(this.onItemChildrenRefreshing, this, this.modelListeners);
this.model.onDidRefreshItemChildren(this.onItemChildrenRefreshed, this, this.modelListeners);
this.model.onDidRefreshItem(this.onItemRefresh, this, this.modelListeners);
this.model.onExpandItem(this.onItemExpanding, this, this.modelListeners);
this.model.onDidExpandItem(this.onItemExpanded, this, this.modelListeners);
this.model.onCollapseItem(this.onItemCollapsing, this, this.modelListeners);
this.model.onDidRevealItem(this.onItemReveal, this, this.modelListeners);
this.model.onDidAddTraitItem(this.onItemAddTrait, this, this.modelListeners);
this.model.onDidRemoveTraitItem(this.onItemRemoveTrait, this, this.modelListeners);
};
TreeView.prototype.onRefreshing = function () {
this.isRefreshing = true;
};
TreeView.prototype.onRefreshed = function () {
this.isRefreshing = false;
this.onRowsChanged();
};
TreeView.prototype.onRowsChanged = function (scrollTop) {
if (scrollTop === void 0) { scrollTop = this.scrollTop; }
if (this.isRefreshing) {
return;
}
this.scrollTop = scrollTop;
this.updateScrollWidth();
};
TreeView.prototype.updateScrollWidth = function () {
var _this = this;
if (!this.horizontalScrolling) {
return;
}
this.contentWidthUpdateDelayer.trigger(function () {
var keys = Object.keys(_this.items);
var scrollWidth = 0;
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
scrollWidth = Math.max(scrollWidth, _this.items[key].width);
}
_this.scrollWidth = scrollWidth + 10 /* scrollbar */;
});
};
TreeView.prototype.focusNextPage = function (eventPayload) {
var _this = this;
var lastPageIndex = this.indexAt(this.scrollTop + this.viewHeight);
lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
var lastPageElement = this.itemAtIndex(lastPageIndex).model.getElement();
var currentlyFocusedElement = this.model.getFocus();
if (currentlyFocusedElement !== lastPageElement) {
this.model.setFocus(lastPageElement, eventPayload);
}
else {
var previousScrollTop = this.scrollTop;
this.scrollTop += this.viewHeight;
if (this.scrollTop !== previousScrollTop) {
// Let the scroll event listener run
setTimeout(function () {
_this.focusNextPage(eventPayload);
}, 0);
}
}
};
TreeView.prototype.focusPreviousPage = function (eventPayload) {
var _this = this;
var firstPageIndex;
if (this.scrollTop === 0) {
firstPageIndex = this.indexAt(this.scrollTop);
}
else {
firstPageIndex = this.indexAfter(this.scrollTop - 1);
}
var firstPageElement = this.itemAtIndex(firstPageIndex).model.getElement();
var currentlyFocusedElement = this.model.getFocus();
if (currentlyFocusedElement !== firstPageElement) {
this.model.setFocus(firstPageElement, eventPayload);
}
else {
var previousScrollTop = this.scrollTop;
this.scrollTop -= this.viewHeight;
if (this.scrollTop !== previousScrollTop) {
// Let the scroll event listener run
setTimeout(function () {
_this.focusPreviousPage(eventPayload);
}, 0);
}
}
};
Object.defineProperty(TreeView.prototype, "viewHeight", {
get: function () {
var scrollDimensions = this.scrollableElement.getScrollDimensions();
return scrollDimensions.height;
},
set: function (height) {
this.scrollableElement.setScrollDimensions({ height: height });
},
enumerable: true,
configurable: true
});
Object.defineProperty(TreeView.prototype, "scrollHeight", {
set: function (scrollHeight) {
scrollHeight = scrollHeight + (this.horizontalScrolling ? 10 : 0);
this.scrollableElement.setScrollDimensions({ scrollHeight: scrollHeight });
},
enumerable: true,
configurable: true
});
Object.defineProperty(TreeView.prototype, "viewWidth", {
get: function () {
var scrollDimensions = this.scrollableElement.getScrollDimensions();
return scrollDimensions.width;
},
set: function (viewWidth) {
this.scrollableElement.setScrollDimensions({ width: viewWidth });
},
enumerable: true,
configurable: true
});
Object.defineProperty(TreeView.prototype, "scrollWidth", {
set: function (scrollWidth) {
this.scrollableElement.setScrollDimensions({ scrollWidth: scrollWidth });
},
enumerable: true,
configurable: true
});
Object.defineProperty(TreeView.prototype, "scrollTop", {
get: function () {
var scrollPosition = this.scrollableElement.getScrollPosition();
return scrollPosition.scrollTop;
},
set: function (scrollTop) {
var scrollHeight = this.getContentHeight() + (this.horizontalScrolling ? 10 : 0);
this.scrollableElement.setScrollDimensions({ scrollHeight: scrollHeight });
this.scrollableElement.setScrollPosition({ scrollTop: scrollTop });
},
enumerable: true,
configurable: true
});
// Events
TreeView.prototype.onClearingInput = function (e) {
var item = e.item;
if (item) {
this.onRemoveItems(new iterator_1.MappedIterator(item.getNavigator(), function (item) { return item && item.id; }));
this.onRowsChanged();
}
};
TreeView.prototype.onSetInput = function (e) {
this.context.cache.garbageCollect();
this.inputItem = new RootViewItem(this.context, e.item, this.wrapper);
};
TreeView.prototype.onItemChildrenRefreshing = function (e) {
var item = e.item;
var viewItem = this.items[item.id];
if (viewItem && this.context.options.showLoading) {
viewItem.loadingTimer = setTimeout(function () {
viewItem.loadingTimer = 0;
viewItem.loading = true;
}, TreeView.LOADING_DECORATION_DELAY);
}
if (!e.isNested) {
var childrenIds = [];
var navigator_1 = item.getNavigator();
var childItem = void 0;
while (childItem = navigator_1.next()) {
childrenIds.push(childItem.id);
}
this.refreshingPreviousChildrenIds[item.id] = childrenIds;
}
};
TreeView.prototype.onItemChildrenRefreshed = function (e) {
var _this = this;
var item = e.item;
var viewItem = this.items[item.id];
if (viewItem) {
if (viewItem.loadingTimer) {
clearTimeout(viewItem.loadingTimer);
viewItem.loadingTimer = 0;
}
viewItem.loading = false;
}
if (!e.isNested) {
var previousChildrenIds_1 = this.refreshingPreviousChildrenIds[item.id];
var afterModelItems_1 = [];
var navigator_2 = item.getNavigator();
var childItem = void 0;
while (childItem = navigator_2.next()) {
afterModelItems_1.push(childItem);
}
var skipDiff = Math.abs(previousChildrenIds_1.length - afterModelItems_1.length) > 1000;
var diff = [];
var doToInsertItemsAlreadyExist = false;
if (!skipDiff) {
var lcs = new Diff.LcsDiff({
getElements: function () { return previousChildrenIds_1; }
}, {
getElements: function () { return afterModelItems_1.map(function (item) { return item.id; }); }
}, null);
diff = lcs.ComputeDiff(false).changes;
// this means that the result of the diff algorithm would result
// in inserting items that were already registered. this can only
// happen if the data provider returns bad ids OR if the sorting
// of the elements has changed
doToInsertItemsAlreadyExist = diff.some(function (d) {
if (d.modifiedLength > 0) {
for (var i = d.modifiedStart, len = d.modifiedStart + d.modifiedLength; i < len; i++) {
if (_this.items.hasOwnProperty(afterModelItems_1[i].id)) {
return true;
}
}
}
return false;
});
}
// 50 is an optimization number, at some point we're better off
// just replacing everything
if (!skipDiff && !doToInsertItemsAlreadyExist && diff.length < 50) {
for (var _i = 0, diff_1 = diff; _i < diff_1.length; _i++) {
var diffChange = diff_1[_i];
if (diffChange.originalLength > 0) {
this.onRemoveItems(new iterator_1.ArrayIterator(previousChildrenIds_1, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength));
}
if (diffChange.modifiedLength > 0) {
var beforeItem = afterModelItems_1[diffChange.modifiedStart - 1] || item;
beforeItem = beforeItem.getDepth() > 0 ? beforeItem : null;
this.onInsertItems(new iterator_1.ArrayIterator(afterModelItems_1, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength), beforeItem ? beforeItem.id : null);
}
}
}
else if (skipDiff || diff.length) {
this.onRemoveItems(new iterator_1.ArrayIterator(previousChildrenIds_1));
this.onInsertItems(new iterator_1.ArrayIterator(afterModelItems_1), item.getDepth() > 0 ? item.id : null);
}
if (skipDiff || diff.length) {
this.onRowsChanged();
}
}
};
TreeView.prototype.onItemRefresh = function (item) {
this.onItemsRefresh([item]);
};
TreeView.prototype.onItemsRefresh = function (items) {
var _this = this;
this.onRefreshItemSet(items.filter(function (item) { return _this.items.hasOwnProperty(item.id); }));
this.onRowsChanged();
};
TreeView.prototype.onItemExpanding = function (e) {
var viewItem = this.items[e.item.id];
if (viewItem) {
viewItem.expanded = true;
}
};
TreeView.prototype.onItemExpanded = function (e) {
var item = e.item;
var viewItem = this.items[item.id];
if (viewItem) {
viewItem.expanded = true;
var height = this.onInsertItems(item.getNavigator(), item.id) || 0;
var scrollTop = this.scrollTop;
if (viewItem.top + viewItem.height <= this.scrollTop) {
scrollTop += height;
}
this.onRowsChanged(scrollTop);
}
};
TreeView.prototype.onItemCollapsing = function (e) {
var item = e.item;
var viewItem = this.items[item.id];
if (viewItem) {
viewItem.expanded = false;
this.onRemoveItems(new iterator_1.MappedIterator(item.getNavigator(), function (item) { return item && item.id; }));
this.onRowsChanged();
}
};
TreeView.prototype.onItemReveal = function (e) {
var item = e.item;
var relativeTop = e.relativeTop;
var viewItem = this.items[item.id];
if (viewItem) {
if (relativeTop !== null) {
relativeTop = relativeTop < 0 ? 0 : relativeTop;
relativeTop = relativeTop > 1 ? 1 : relativeTop;
// y = mx + b
var m = viewItem.height - this.viewHeight;
this.scrollTop = m * relativeTop + viewItem.top;
}
else {
var viewItemBottom = viewItem.top + viewItem.height;
var wrapperBottom = this.scrollTop + this.viewHeight;
if (viewItem.top < this.scrollTop) {
this.scrollTop = viewItem.top;
}
else if (viewItemBottom >= wrapperBottom) {
this.scrollTop = viewItemBottom - this.viewHeight;
}
}
}
};
TreeView.prototype.onItemAddTrait = function (e) {
var item = e.item;
var trait = e.trait;
var viewItem = this.items[item.id];
if (viewItem) {
viewItem.addClass(trait);
}
if (trait === 'highlighted') {
DOM.addClass(this.domNode, trait);
// Ugly Firefox fix: input fields can't be selected if parent nodes are draggable
if (viewItem) {
this.highlightedItemWasDraggable = !!viewItem.draggable;
if (viewItem.draggable) {
viewItem.draggable = false;
}
}
}
};
TreeView.prototype.onItemRemoveTrait = function (e) {
var item = e.item;
var trait = e.trait;
var viewItem = this.items[item.id];
if (viewItem) {
viewItem.removeClass(trait);
}
if (trait === 'highlighted') {
DOM.removeClass(this.domNode, trait);
// Ugly Firefox fix: input fields can't be selected if parent nodes are draggable
if (this.highlightedItemWasDraggable) {
viewItem.draggable = true;
}
this.highlightedItemWasDraggable = false;
}
};
TreeView.prototype.onModelFocusChange = function () {
var focus = this.model && this.model.getFocus();
DOM.toggleClass(this.domNode, 'no-focused-item', !focus);
// ARIA
if (focus) {
this.domNode.setAttribute('aria-activedescendant', strings.safeBtoa(this.context.dataSource.getId(this.context.tree, focus)));
}
else {
this.domNode.removeAttribute('aria-activedescendant');
}
};
// HeightMap "events"
TreeView.prototype.onInsertItem = function (item) {
var _this = this;
item.onDragStart = function (e) { _this.onDragStart(item, e); };
item.needsRender = true;
this.refreshViewItem(item);
this.items[item.id] = item;
};
TreeView.prototype.onRefreshItem = function (item, needsRender) {
if (needsRender === void 0) { needsRender = false; }
item.needsRender = item.needsRender || needsRender;
this.refreshViewItem(item);
};
TreeView.prototype.onRemoveItem = function (item) {
this.removeItemFromDOM(item);
item.dispose();
delete this.items[item.id];
};
// ViewItem refresh
TreeView.prototype.refreshViewItem = function (item) {
item.render();
if (this.shouldBeRendered(item)) {
this.insertItemInDOM(item);
}
else {
this.removeItemFromDOM(item);
}
};
// DOM Events
TreeView.prototype.onClick = function (e) {
if (this.lastPointerType && this.lastPointerType !== 'mouse') {
return;
}
var event = new Mouse.StandardMouseEvent(e);
var item = this.getItemAround(event.target);
if (!item) {
return;
}
if (Browser.isIE && Date.now() - this.lastClickTimeStamp < 300) {
// IE10+ doesn't set the detail property correctly. While IE10 simply
// counts the number of clicks, IE11 reports always 1. To align with
// other browser, we set the value to 2 if clicks events come in a 300ms
// sequence.
event.detail = 2;
}
this.lastClickTimeStamp = Date.now();
this.context.controller.onClick(this.context.tree, item.model.getElement(), event);
};
TreeView.prototype.onMouseMiddleClick = function (e) {
if (!this.context.controller.onMouseMiddleClick) {
return;
}
var event = new Mouse.StandardMouseEvent(e);
var item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller.onMouseMiddleClick(this.context.tree, item.model.getElement(), event);
};
TreeView.prototype.onMouseDown = function (e) {
this.didJustPressContextMenuKey = false;
if (!this.context.controller.onMouseDown) {
return;
}
if (this.lastPointerType && this.lastPointerType !== 'mouse') {
return;
}
var event = new Mouse.StandardMouseEvent(e);
if (event.ctrlKey && Platform.isNative && Platform.isMacintosh) {
return;
}
var item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller.onMouseDown(this.context.tree, item.model.getElement(), event);
};
TreeView.prototype.onMouseUp = function (e) {
if (!this.context.controller.onMouseUp) {
return;
}
if (this.lastPointerType && this.lastPointerType !== 'mouse') {
return;
}
var event = new Mouse.StandardMouseEvent(e);
if (event.ctrlKey && Platform.isNative && Platform.isMacintosh) {
return;
}
var item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller.onMouseUp(this.context.tree, item.model.getElement(), event);
};
TreeView.prototype.onTap = function (e) {
var item = this.getItemAround(e.initialTarget);
if (!item) {
return;
}
this.context.controller.onTap(this.context.tree, item.model.getElement(), e);
};
TreeView.prototype.onTouchChange = function (event) {
event.preventDefault();
event.stopPropagation();
this.scrollTop -= event.translationY;
};
TreeView.prototype.onContextMenu = function (event) {
var resultEvent;
var element;
if (event instanceof KeyboardEvent || this.didJustPressContextMenuKey) {
this.didJustPressContextMenuKey = false;
var keyboardEvent = new Keyboard.StandardKeyboardEvent(event);
element = this.model.getFocus();
var position = void 0;
if (!element) {
element = this.model.getInput();
position = DOM.getDomNodePagePosition(this.inputItem.element);
}
else {
var id = this.context.dataSource.getId(this.context.tree, element);
var viewItem = this.items[id];
position = DOM.getDomNodePagePosition(viewItem.element);
}
resultEvent = new _.KeyboardContextMenuEvent(position.left + position.width, position.top, keyboardEvent);
}
else {
var mouseEvent = new Mouse.StandardMouseEvent(event);
var item = this.getItemAround(mouseEvent.target);
if (!item) {
return;
}
element = item.model.getElement();
resultEvent = new _.MouseContextMenuEvent(mouseEvent);
}
this.context.controller.onContextMenu(this.context.tree, element, resultEvent);
};
TreeView.prototype.onKeyDown = function (e) {
var event = new Keyboard.StandardKeyboardEvent(e);
this.didJustPressContextMenuKey = event.keyCode === 58 /* ContextMenu */ || (event.shiftKey && event.keyCode === 68 /* F10 */);
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return; // Ignore event if target is a form input field (avoids browser specific issues)
}
if (this.didJustPressContextMenuKey) {
event.preventDefault();
event.stopPropagation();
}
this.context.controller.onKeyDown(this.context.tree, event);
};
TreeView.prototype.onKeyUp = function (e) {
if (this.didJustPressContextMenuKey) {
this.onContextMenu(e);
}
this.didJustPressContextMenuKey = false;
this.context.controller.onKeyUp(this.context.tree, new Keyboard.StandardKeyboardEvent(e));
};
TreeView.prototype.onDragStart = function (item, e) {
if (this.model.getHighlight()) {
return;
}
var element = item.model.getElement();
var selection = this.model.getSelection();
var elements;
if (selection.indexOf(element) > -1) {
elements = selection;
}
else {
elements = [element];
}
e.dataTransfer.effectAllowed = 'copyMove';
e.dataTransfer.setData(dnd_1.DataTransfers.RESOURCES, JSON.stringify([item.uri]));
if (e.dataTransfer.setDragImage) {
var label = void 0;
if (this.context.dnd.getDragLabel) {
label = this.context.dnd.getDragLabel(this.context.tree, elements);
}
else {
label = String(elements.length);
}
var dragImage_1 = document.createElement('div');
dragImage_1.className = 'monaco-tree-drag-image';
dragImage_1.textContent = label;
document.body.appendChild(dragImage_1);
e.dataTransfer.setDragImage(dragImage_1, -10, -10);
setTimeout(function () { return document.body.removeChild(dragImage_1); }, 0);
}
this.currentDragAndDropData = new dnd.ElementsDragAndDropData(elements);
dnd_1.StaticDND.CurrentDragAndDropData = new dnd.ExternalElementsDragAndDropData(elements);
this.context.dnd.onDragStart(this.context.tree, this.currentDragAndDropData, new Mouse.DragMouseEvent(e));
};
TreeView.prototype.setupDragAndDropScrollInterval = function () {
var _this = this;
var viewTop = DOM.getTopLeftOffset(this.wrapper).top;
if (!this.dragAndDropScrollInterval) {
this.dragAndDropScrollInterval = window.setInterval(function () {
if (_this.dragAndDropMouseY === null) {
return;
}
var diff = _this.dragAndDropMouseY - viewTop;
var scrollDiff = 0;
var upperLimit = _this.viewHeight - 35;
if (diff < 35) {
scrollDiff = Math.max(-14, 0.2 * (diff - 35));
}
else if (diff > upperLimit) {
scrollDiff = Math.min(14, 0.2 * (diff - upperLimit));
}
_this.scrollTop += scrollDiff;
}, 10);
this.cancelDragAndDropScrollTimeout();
this.dragAndDropScrollTimeout = window.setTimeout(function () {
_this.cancelDragAndDropScrollInterval();
_this.dragAndDropScrollTimeout = null;
}, 1000);
}
};
TreeView.prototype.cancelDragAndDropScrollInterval = function () {
if (this.dragAndDropScrollInterval) {
window.clearInterval(this.dragAndDropScrollInterval);
this.dragAndDropScrollInterval = null;
}
this.cancelDragAndDropScrollTimeout();
};
TreeView.prototype.cancelDragAndDropScrollTimeout = function () {
if (this.dragAndDropScrollTimeout) {
window.clearTimeout(this.dragAndDropScrollTimeout);
this.dragAndDropScrollTimeout = null;
}
};
TreeView.prototype.onDragOver = function (e) {
var _this = this;
e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
var event = new Mouse.DragMouseEvent(e);
var viewItem = this.getItemAround(event.target);
if (!viewItem || (event.posx === 0 && event.posy === 0 && event.browserEvent.type === DOM.EventType.DRAG_LEAVE)) {
// dragging outside of tree
if (this.currentDropTarget) {
// clear previously hovered element feedback
this.currentDropTargets.forEach(function (i) { return i.dropTarget = false; });
this.currentDropTargets = [];
this.currentDropDisposable.dispose();
}
this.cancelDragAndDropScrollInterval();
this.currentDropTarget = null;
this.currentDropElement = null;
this.dragAndDropMouseY = null;
return false;
}
// dragging inside the tree
this.setupDragAndDropScrollInterval();
this.dragAndDropMouseY = event.posy;
if (!this.currentDragAndDropData) {
// just started dragging
if (dnd_1.StaticDND.CurrentDragAndDropData) {
this.currentDragAndDropData = dnd_1.StaticDND.CurrentDragAndDropData;
}
else {
if (!event.dataTransfer.types) {
return false;
}
this.currentDragAndDropData = new dnd.DesktopDragAndDropData();
}
}
this.currentDragAndDropData.update(event.browserEvent.dataTransfer);
var element;
var item = viewItem.model;
var reaction;
// check the bubble up behavior
do {
element = item ? item.getElement() : this.model.getInput();
reaction = this.context.dnd.onDragOver(this.context.tree, this.currentDragAndDropData, element, event);
if (!reaction || reaction.bubble !== 1 /* BUBBLE_UP */) {
break;
}
item = item && item.parent;
} while (item);
if (!item) {
this.currentDropElement = null;
return false;
}
var canDrop = reaction && reaction.accept;
if (canDrop) {
this.currentDropElement = item.getElement();
event.preventDefault();
event.dataTransfer.dropEffect = reaction.effect === 0 /* COPY */ ? 'copy' : 'move';
}
else {
this.currentDropElement = null;
}
// item is the model item where drop() should be called
// can be null
var currentDropTarget = item.id === this.inputItem.id ? this.inputItem : this.items[item.id];
if (this.shouldInvalidateDropReaction || this.currentDropTarget !== currentDropTarget || !reactionEquals(this.currentDropElementReaction, reaction)) {
this.shouldInvalidateDropReaction = false;
if (this.currentDropTarget) {
this.currentDropTargets.forEach(function (i) { return i.dropTarget = false; });
this.currentDropTargets = [];
this.currentDropDisposable.dispose();
}
this.currentDropTarget = currentDropTarget;
this.currentDropElementReaction = reaction;
if (canDrop) {
// setup hover feedback for drop target
if (this.currentDropTarget) {
this.currentDropTarget.dropTarget = true;
this.currentDropTargets.push(this.currentDropTarget);
}
if (reaction.bubble === 0 /* BUBBLE_DOWN */) {
var nav = item.getNavigator();
var child = void 0;
while (child = nav.next()) {
viewItem = this.items[child.id];
if (viewItem) {
viewItem.dropTarget = true;
this.currentDropTargets.push(viewItem);
}
}
}
if (reaction.autoExpand) {
var timeoutPromise_1 = async_1.timeout(500);
this.currentDropDisposable = Lifecycle.toDisposable(function () { return timeoutPromise_1.cancel(); });
timeoutPromise_1
.then(function () { return _this.context.tree.expand(_this.currentDropElement); })
.then(function () { return _this.shouldInvalidateDropReaction = true; });
}
}
}
return true;
};
TreeView.prototype.onDrop = function (e) {
if (this.currentDropElement) {
var event_2 = new Mouse.DragMouseEvent(e);
event_2.preventDefault();
this.currentDragAndDropData.update(event_2.browserEvent.dataTransfer);
this.context.dnd.drop(this.context.tree, this.currentDragAndDropData, this.currentDropElement, event_2);
this.onDragEnd(e);
}
this.cancelDragAndDropScrollInterval();
};
TreeView.prototype.onDragEnd = function (e) {
if (this.currentDropTarget) {
this.currentDropTargets.forEach(function (i) { return i.dropTarget = false; });
this.currentDropTargets = [];
}
this.currentDropDisposable.dispose();
this.cancelDragAndDropScrollInterval();
this.currentDragAndDropData = null;
dnd_1.StaticDND.CurrentDragAndDropData = undefined;
this.currentDropElement = null;
this.currentDropTarget = null;
this.dragAndDropMouseY = null;
};
TreeView.prototype.onFocus = function () {
if (!this.context.options.alwaysFocused) {
DOM.addClass(this.domNode, 'focused');
}
this._onDOMFocus.fire();
};
TreeView.prototype.onBlur = function () {
if (!this.context.options.alwaysFocused) {
DOM.removeClass(this.domNode, 'focused');
}
this.domNode.removeAttribute('aria-activedescendant'); // ARIA
this._onDOMBlur.fire();
};
// MS specific DOM Events
TreeView.prototype.onMsPointerDown = function (event) {
if (!this.msGesture) {
return;
}
// Circumvent IE11 breaking change in e.pointerType & TypeScript's stale definitions
var pointerType = event.pointerType;
if (pointerType === (event.MSPOINTER_TYPE_MOUSE || 'mouse')) {
this.lastPointerType = 'mouse';
return;
}
else if (pointerType === (event.MSPOINTER_TYPE_TOUCH || 'touch')) {
this.lastPointerType = 'touch';
}
else {
return;
}
event.stopPropagation();
event.preventDefault();
this.msGesture.addPointer(event.pointerId);
};
TreeView.prototype.onThrottledMsGestureChange = function (event) {
this.scrollTop -= event.translationY;
};
TreeView.prototype.onMsGestureTap = function (event) {
event.initialTarget = document.elementFromPoint(event.clientX, event.clientY);
this.onTap(event);
};
// DOM changes
TreeView.prototype.insertItemInDOM = function (item) {
var elementAfter = null;
var itemAfter = this.itemAfter(item);
if (itemAfter && itemAfter.element) {
elementAfter = itemAfter.element;
}
item.insertInDOM(this.rowsContainer, elementAfter);
};
TreeView.prototype.removeItemFromDOM = function (item) {
if (!item) {
return;
}
item.removeFromDOM();
};
// Helpers
TreeView.prototype.shouldBeRendered = function (item) {
return item.top < this.lastRenderTop + this.lastRenderHeight && item.top + item.height > this.lastRenderTop;
};
TreeView.prototype.getItemAround = function (element) {
var candidate = this.inputItem;
var el = element;
do {
if (el[TreeView.BINDING]) {
candidate = el[TreeView.BINDING];
}
if (el === this.wrapper || el === this.domNode) {
return candidate;
}
if (el === this.scrollableElement.getDomNode() || el === document.body) {
return undefined;
}
} while (el = el.parentElement);
return undefined;
};
// Cleanup
TreeView.prototype.releaseModel = function () {
if (this.model) {
this.modelListeners = Lifecycle.dispose(this.modelListeners);
this.model = null;
}
};
TreeView.prototype.dispose = function () {
var _this = this;
// TODO@joao: improve
this.scrollableElement.dispose();
this.releaseModel();
this.viewListeners = Lifecycle.dispose(this.viewListeners);
this._onDOMFocus.dispose();
this._onDOMBlur.dispose();
if (this.domNode.parentNode) {
this.domNode.parentNode.removeChild(this.domNode);
}
if (this.items) {
Object.keys(this.items).forEach(function (key) { return _this.items[key].removeFromDOM(); });
}
if (this.context.cache) {
this.context.cache.dispose();
}
this.gestureDisposable.dispose();
_super.prototype.dispose.call(this);
};
TreeView.BINDING = 'monaco-tree-row';
TreeView.LOADING_DECORATION_DELAY = 800;
TreeView.counter = 0;
return TreeView;
}(treeViewModel_1.HeightMap));
exports.TreeView = TreeView;
});
define(__m[278/*vs/css!vs/base/browser/ui/splitview/splitview*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[279/*vs/base/browser/ui/splitview/splitview*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,21/*vs/base/common/types*/,6/*vs/base/browser/dom*/,131/*vs/base/common/numbers*/,19/*vs/base/common/arrays*/,104/*vs/base/browser/ui/sash/sash*/,27/*vs/base/common/color*/,52/*vs/base/browser/event*/,278/*vs/css!vs/base/browser/ui/splitview/splitview*/]), function (require, exports, lifecycle_1, event_1, types, dom, numbers_1, arrays_1, sash_1, color_1, event_2) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var defaultStyles = {
separatorBorder: color_1.Color.transparent
};
var ViewItem = /** @class */ (function () {
function ViewItem(container, view, size, disposable) {
this.container = container;
this.view = view;
this.disposable = disposable;
this._cachedVisibleSize = undefined;
if (typeof size === 'number') {
this._size = size;
this._cachedVisibleSize = undefined;
dom.addClass(container, 'visible');
}
else {
this._size = 0;
this._cachedVisibleSize = size.cachedVisibleSize;
}
}
Object.defineProperty(ViewItem.prototype, "size", {
get: function () {
return this._size;
},
set: function (size) {
this._size = size;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "visible", {
get: function () {
return typeof this._cachedVisibleSize === 'undefined';
},
enumerable: true,
configurable: true
});
ViewItem.prototype.setVisible = function (visible, size) {
if (visible === this.visible) {
return;
}
if (visible) {
this.size = numbers_1.clamp(this._cachedVisibleSize, this.viewMinimumSize, this.viewMaximumSize);
this._cachedVisibleSize = undefined;
}
else {
this._cachedVisibleSize = typeof size === 'number' ? size : this.size;
this.size = 0;
}
dom.toggleClass(this.container, 'visible', visible);
if (this.view.setVisible) {
this.view.setVisible(visible);
}
};
Object.defineProperty(ViewItem.prototype, "minimumSize", {
get: function () { return this.visible ? this.view.minimumSize : 0; },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "viewMinimumSize", {
get: function () { return this.view.minimumSize; },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "maximumSize", {
get: function () { return this.visible ? this.view.maximumSize : 0; },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "viewMaximumSize", {
get: function () { return this.view.maximumSize; },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "priority", {
get: function () { return this.view.priority; },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "snap", {
get: function () { return !!this.view.snap; },
enumerable: true,
configurable: true
});
Object.defineProperty(ViewItem.prototype, "enabled", {
set: function (enabled) {
this.container.style.pointerEvents = enabled ? null : 'none';
},
enumerable: true,
configurable: true
});
ViewItem.prototype.layout = function (offset, layoutContext) {
this.layoutContainer(offset);
this.view.layout(this.size, offset, layoutContext);
};
ViewItem.prototype.dispose = function () {
this.disposable.dispose();
return this.view;
};
return ViewItem;
}());
var VerticalViewItem = /** @class */ (function (_super) {
__extends(VerticalViewItem, _super);
function VerticalViewItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
VerticalViewItem.prototype.layoutContainer = function (offset) {
this.container.style.top = offset + "px";
this.container.style.height = this.size + "px";
};
return VerticalViewItem;
}(ViewItem));
var HorizontalViewItem = /** @class */ (function (_super) {
__extends(HorizontalViewItem, _super);
function HorizontalViewItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
HorizontalViewItem.prototype.layoutContainer = function (offset) {
this.container.style.left = offset + "px";
this.container.style.width = this.size + "px";
};
return HorizontalViewItem;
}(ViewItem));
var State;
(function (State) {
State[State["Idle"] = 0] = "Idle";
State[State["Busy"] = 1] = "Busy";
})(State || (State = {}));
var Sizing;
(function (Sizing) {
Sizing.Distribute = { type: 'distribute' };
function Split(index) { return { type: 'split', index: index }; }
Sizing.Split = Split;
function Invisible(cachedVisibleSize) { return { type: 'invisible', cachedVisibleSize: cachedVisibleSize }; }
Sizing.Invisible = Invisible;
})(Sizing = exports.Sizing || (exports.Sizing = {}));
var SplitView = /** @class */ (function (_super) {
__extends(SplitView, _super);
function SplitView(container, options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this) || this;
_this.size = 0;
_this.contentSize = 0;
_this.proportions = undefined;
_this.viewItems = [];
_this.sashItems = [];
_this.state = State.Idle;
_this._onDidSashChange = _this._register(new event_1.Emitter());
_this.onDidSashChange = _this._onDidSashChange.event;
_this._onDidSashReset = _this._register(new event_1.Emitter());
_this._startSnappingEnabled = true;
_this._endSnappingEnabled = true;
_this.orientation = types.isUndefined(options.orientation) ? 0 /* VERTICAL */ : options.orientation;
_this.inverseAltBehavior = !!options.inverseAltBehavior;
_this.proportionalLayout = types.isUndefined(options.proportionalLayout) ? true : !!options.proportionalLayout;
_this.el = document.createElement('div');
dom.addClass(_this.el, 'monaco-split-view2');
dom.addClass(_this.el, _this.orientation === 0 /* VERTICAL */ ? 'vertical' : 'horizontal');
container.appendChild(_this.el);
_this.sashContainer = dom.append(_this.el, dom.$('.sash-container'));
_this.viewContainer = dom.append(_this.el, dom.$('.split-view-container'));
_this.style(options.styles || defaultStyles);
// We have an existing set of view, add them now
if (options.descriptor) {
_this.size = options.descriptor.size;
options.descriptor.views.forEach(function (viewDescriptor, index) {
var sizing = types.isUndefined(viewDescriptor.visible) || viewDescriptor.visible ? viewDescriptor.size : { type: 'invisible', cachedVisibleSize: viewDescriptor.size };
var view = viewDescriptor.view;
_this.doAddView(view, sizing, index, true);
});
// Initialize content size and proportions for first layout
_this.contentSize = _this.viewItems.reduce(function (r, i) { return r + i.size; }, 0);
_this.saveProportions();
}
return _this;
}
Object.defineProperty(SplitView.prototype, "orthogonalStartSash", {
get: function () { return this._orthogonalStartSash; },
set: function (sash) {
for (var _i = 0, _a = this.sashItems; _i < _a.length; _i++) {
var sashItem = _a[_i];
sashItem.sash.orthogonalStartSash = sash;
}
this._orthogonalStartSash = sash;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SplitView.prototype, "orthogonalEndSash", {
get: function () { return this._orthogonalEndSash; },
set: function (sash) {
for (var _i = 0, _a = this.sashItems; _i < _a.length; _i++) {
var sashItem = _a[_i];
sashItem.sash.orthogonalEndSash = sash;
}
this._orthogonalEndSash = sash;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SplitView.prototype, "startSnappingEnabled", {
get: function () { return this._startSnappingEnabled; },
set: function (startSnappingEnabled) {
if (this._startSnappingEnabled === startSnappingEnabled) {
return;
}
this._startSnappingEnabled = startSnappingEnabled;
this.updateSashEnablement();
},
enumerable: true,
configurable: true
});
Object.defineProperty(SplitView.prototype, "endSnappingEnabled", {
get: function () { return this._endSnappingEnabled; },
set: function (endSnappingEnabled) {
if (this._endSnappingEnabled === endSnappingEnabled) {
return;
}
this._endSnappingEnabled = endSnappingEnabled;
this.updateSashEnablement();
},
enumerable: true,
configurable: true
});
SplitView.prototype.style = function (styles) {
if (styles.separatorBorder.isTransparent()) {
dom.removeClass(this.el, 'separator-border');
this.el.style.removeProperty('--separator-border');
}
else {
dom.addClass(this.el, 'separator-border');
this.el.style.setProperty('--separator-border', styles.separatorBorder.toString());
}
};
SplitView.prototype.addView = function (view, size, index) {
if (index === void 0) { index = this.viewItems.length; }
this.doAddView(view, size, index, false);
};
SplitView.prototype.layout = function (size, layoutContext) {
var _this = this;
var previousSize = Math.max(this.size, this.contentSize);
this.size = size;
this.layoutContext = layoutContext;
if (!this.proportions) {
var indexes = arrays_1.range(this.viewItems.length);
var lowPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 1 /* Low */; });
var highPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 2 /* High */; });
this.resize(this.viewItems.length - 1, size - previousSize, undefined, lowPriorityIndexes, highPriorityIndexes);
}
else {
for (var i = 0; i < this.viewItems.length; i++) {
var item = this.viewItems[i];
item.size = numbers_1.clamp(Math.round(this.proportions[i] * size), item.minimumSize, item.maximumSize);
}
}
this.distributeEmptySpace();
this.layoutViews();
};
SplitView.prototype.saveProportions = function () {
var _this = this;
if (this.proportionalLayout && this.contentSize > 0) {
this.proportions = this.viewItems.map(function (i) { return i.size / _this.contentSize; });
}
};
SplitView.prototype.onSashStart = function (_a) {
var _this = this;
var sash = _a.sash, start = _a.start, alt = _a.alt;
for (var _i = 0, _b = this.viewItems; _i < _b.length; _i++) {
var item = _b[_i];
item.enabled = false;
}
var index = arrays_1.firstIndex(this.sashItems, function (item) { return item.sash === sash; });
// This way, we can press Alt while we resize a sash, macOS style!
var disposable = lifecycle_1.combinedDisposable(event_2.domEvent(document.body, 'keydown')(function (e) { return resetSashDragState(_this.sashDragState.current, e.altKey); }), event_2.domEvent(document.body, 'keyup')(function () { return resetSashDragState(_this.sashDragState.current, false); }));
var resetSashDragState = function (start, alt) {
var sizes = _this.viewItems.map(function (i) { return i.size; });
var minDelta = Number.NEGATIVE_INFINITY;
var maxDelta = Number.POSITIVE_INFINITY;
if (_this.inverseAltBehavior) {
alt = !alt;
}
if (alt) {
// When we're using the last sash with Alt, we're resizing
// the view to the left/up, instead of right/down as usual
// Thus, we must do the inverse of the usual
var isLastSash = index === _this.sashItems.length - 1;
if (isLastSash) {
var viewItem = _this.viewItems[index];
minDelta = (viewItem.minimumSize - viewItem.size) / 2;
maxDelta = (viewItem.maximumSize - viewItem.size) / 2;
}
else {
var viewItem = _this.viewItems[index + 1];
minDelta = (viewItem.size - viewItem.maximumSize) / 2;
maxDelta = (viewItem.size - viewItem.minimumSize) / 2;
}
}
var snapBefore;
var snapAfter;
if (!alt) {
var upIndexes = arrays_1.range(index, -1);
var downIndexes = arrays_1.range(index + 1, _this.viewItems.length);
var minDeltaUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].minimumSize - sizes[i]); }, 0);
var maxDeltaUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].viewMaximumSize - sizes[i]); }, 0);
var maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].minimumSize); }, 0);
var minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].viewMaximumSize); }, 0);
var minDelta_1 = Math.max(minDeltaUp, minDeltaDown);
var maxDelta_1 = Math.min(maxDeltaDown, maxDeltaUp);
var snapBeforeIndex = _this.findFirstSnapIndex(upIndexes);
var snapAfterIndex = _this.findFirstSnapIndex(downIndexes);
if (typeof snapBeforeIndex === 'number') {
var viewItem = _this.viewItems[snapBeforeIndex];
var halfSize = Math.floor(viewItem.viewMinimumSize / 2);
snapBefore = {
index: snapBeforeIndex,
limitDelta: viewItem.visible ? minDelta_1 - halfSize : minDelta_1 + halfSize,
size: viewItem.size
};
}
if (typeof snapAfterIndex === 'number') {
var viewItem = _this.viewItems[snapAfterIndex];
var halfSize = Math.floor(viewItem.viewMinimumSize / 2);
snapAfter = {
index: snapAfterIndex,
limitDelta: viewItem.visible ? maxDelta_1 + halfSize : maxDelta_1 - halfSize,
size: viewItem.size
};
}
}
_this.sashDragState = { start: start, current: start, index: index, sizes: sizes, minDelta: minDelta, maxDelta: maxDelta, alt: alt, snapBefore: snapBefore, snapAfter: snapAfter, disposable: disposable };
};
resetSashDragState(start, alt);
};
SplitView.prototype.onSashChange = function (_a) {
var current = _a.current;
var _b = this.sashDragState, index = _b.index, start = _b.start, sizes = _b.sizes, alt = _b.alt, minDelta = _b.minDelta, maxDelta = _b.maxDelta, snapBefore = _b.snapBefore, snapAfter = _b.snapAfter;
this.sashDragState.current = current;
var delta = current - start;
var newDelta = this.resize(index, delta, sizes, undefined, undefined, minDelta, maxDelta, snapBefore, snapAfter);
if (alt) {
var isLastSash = index === this.sashItems.length - 1;
var newSizes = this.viewItems.map(function (i) { return i.size; });
var viewItemIndex = isLastSash ? index : index + 1;
var viewItem = this.viewItems[viewItemIndex];
var newMinDelta = viewItem.size - viewItem.maximumSize;
var newMaxDelta = viewItem.size - viewItem.minimumSize;
var resizeIndex = isLastSash ? index - 1 : index + 1;
this.resize(resizeIndex, -newDelta, newSizes, undefined, undefined, newMinDelta, newMaxDelta);
}
this.distributeEmptySpace();
this.layoutViews();
};
SplitView.prototype.onSashEnd = function (index) {
this._onDidSashChange.fire(index);
this.sashDragState.disposable.dispose();
this.saveProportions();
for (var _i = 0, _a = this.viewItems; _i < _a.length; _i++) {
var item = _a[_i];
item.enabled = true;
}
};
SplitView.prototype.onViewChange = function (item, size) {
var index = this.viewItems.indexOf(item);
if (index < 0 || index >= this.viewItems.length) {
return;
}
size = typeof size === 'number' ? size : item.size;
size = numbers_1.clamp(size, item.minimumSize, item.maximumSize);
if (this.inverseAltBehavior && index > 0) {
// In this case, we want the view to grow or shrink both sides equally
// so we just resize the "left" side by half and let `resize` do the clamping magic
this.resize(index - 1, Math.floor((item.size - size) / 2));
this.distributeEmptySpace();
this.layoutViews();
}
else {
item.size = size;
this.relayout([index], undefined);
}
};
SplitView.prototype.resizeView = function (index, size) {
var _this = this;
if (this.state !== State.Idle) {
throw new Error('Cant modify splitview');
}
this.state = State.Busy;
if (index < 0 || index >= this.viewItems.length) {
return;
}
var indexes = arrays_1.range(this.viewItems.length).filter(function (i) { return i !== index; });
var lowPriorityIndexes = __spreadArrays(indexes.filter(function (i) { return _this.viewItems[i].priority === 1 /* Low */; }), [index]);
var highPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 2 /* High */; });
var item = this.viewItems[index];
size = Math.round(size);
size = numbers_1.clamp(size, item.minimumSize, Math.min(item.maximumSize, this.size));
item.size = size;
this.relayout(lowPriorityIndexes, highPriorityIndexes);
this.state = State.Idle;
};
SplitView.prototype.distributeViewSizes = function () {
var _this = this;
var flexibleViewItems = [];
var flexibleSize = 0;
for (var _i = 0, _a = this.viewItems; _i < _a.length; _i++) {
var item = _a[_i];
if (item.maximumSize - item.minimumSize > 0) {
flexibleViewItems.push(item);
flexibleSize += item.size;
}
}
var size = Math.floor(flexibleSize / flexibleViewItems.length);
for (var _b = 0, flexibleViewItems_1 = flexibleViewItems; _b < flexibleViewItems_1.length; _b++) {
var item = flexibleViewItems_1[_b];
item.size = numbers_1.clamp(size, item.minimumSize, item.maximumSize);
}
var indexes = arrays_1.range(this.viewItems.length);
var lowPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 1 /* Low */; });
var highPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 2 /* High */; });
this.relayout(lowPriorityIndexes, highPriorityIndexes);
};
SplitView.prototype.getViewSize = function (index) {
if (index < 0 || index >= this.viewItems.length) {
return -1;
}
return this.viewItems[index].size;
};
SplitView.prototype.doAddView = function (view, size, index, skipLayout) {
var _this = this;
if (index === void 0) { index = this.viewItems.length; }
if (this.state !== State.Idle) {
throw new Error('Cant modify splitview');
}
this.state = State.Busy;
// Add view
var container = dom.$('.split-view-view');
if (index === this.viewItems.length) {
this.viewContainer.appendChild(container);
}
else {
this.viewContainer.insertBefore(container, this.viewContainer.children.item(index));
}
var onChangeDisposable = view.onDidChange(function (size) { return _this.onViewChange(item, size); });
var containerDisposable = lifecycle_1.toDisposable(function () { return _this.viewContainer.removeChild(container); });
var disposable = lifecycle_1.combinedDisposable(onChangeDisposable, containerDisposable);
var viewSize;
if (typeof size === 'number') {
viewSize = size;
}
else if (size.type === 'split') {
viewSize = this.getViewSize(size.index) / 2;
}
else if (size.type === 'invisible') {
viewSize = { cachedVisibleSize: size.cachedVisibleSize };
}
else {
viewSize = view.minimumSize;
}
var item = this.orientation === 0 /* VERTICAL */
? new VerticalViewItem(container, view, viewSize, disposable)
: new HorizontalViewItem(container, view, viewSize, disposable);
this.viewItems.splice(index, 0, item);
// Add sash
if (this.viewItems.length > 1) {
var orientation_1 = this.orientation === 0 /* VERTICAL */ ? 1 /* HORIZONTAL */ : 0 /* VERTICAL */;
var layoutProvider = this.orientation === 0 /* VERTICAL */ ? { getHorizontalSashTop: function (sash) { return _this.getSashPosition(sash); } } : { getVerticalSashLeft: function (sash) { return _this.getSashPosition(sash); } };
var sash_2 = new sash_1.Sash(this.sashContainer, layoutProvider, {
orientation: orientation_1,
orthogonalStartSash: this.orthogonalStartSash,
orthogonalEndSash: this.orthogonalEndSash
});
var sashEventMapper = this.orientation === 0 /* VERTICAL */
? function (e) { return ({ sash: sash_2, start: e.startY, current: e.currentY, alt: e.altKey }); }
: function (e) { return ({ sash: sash_2, start: e.startX, current: e.currentX, alt: e.altKey }); };
var onStart = event_1.Event.map(sash_2.onDidStart, sashEventMapper);
var onStartDisposable = onStart(this.onSashStart, this);
var onChange = event_1.Event.map(sash_2.onDidChange, sashEventMapper);
var onChangeDisposable_1 = onChange(this.onSashChange, this);
var onEnd = event_1.Event.map(sash_2.onDidEnd, function () { return arrays_1.firstIndex(_this.sashItems, function (item) { return item.sash === sash_2; }); });
var onEndDisposable = onEnd(this.onSashEnd, this);
var onDidResetDisposable = sash_2.onDidReset(function () {
var index = arrays_1.firstIndex(_this.sashItems, function (item) { return item.sash === sash_2; });
var upIndexes = arrays_1.range(index, -1);
var downIndexes = arrays_1.range(index + 1, _this.viewItems.length);
var snapBeforeIndex = _this.findFirstSnapIndex(upIndexes);
var snapAfterIndex = _this.findFirstSnapIndex(downIndexes);
if (typeof snapBeforeIndex === 'number' && !_this.viewItems[snapBeforeIndex].visible) {
return;
}
if (typeof snapAfterIndex === 'number' && !_this.viewItems[snapAfterIndex].visible) {
return;
}
_this._onDidSashReset.fire(index);
});
var disposable_1 = lifecycle_1.combinedDisposable(onStartDisposable, onChangeDisposable_1, onEndDisposable, onDidResetDisposable, sash_2);
var sashItem = { sash: sash_2, disposable: disposable_1 };
this.sashItems.splice(index - 1, 0, sashItem);
}
container.appendChild(view.element);
var highPriorityIndexes;
if (typeof size !== 'number' && size.type === 'split') {
highPriorityIndexes = [size.index];
}
if (!skipLayout) {
this.relayout([index], highPriorityIndexes);
}
this.state = State.Idle;
if (!skipLayout && typeof size !== 'number' && size.type === 'distribute') {
this.distributeViewSizes();
}
};
SplitView.prototype.relayout = function (lowPriorityIndexes, highPriorityIndexes) {
var contentSize = this.viewItems.reduce(function (r, i) { return r + i.size; }, 0);
this.resize(this.viewItems.length - 1, this.size - contentSize, undefined, lowPriorityIndexes, highPriorityIndexes);
this.distributeEmptySpace();
this.layoutViews();
this.saveProportions();
};
SplitView.prototype.resize = function (index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta, snapBefore, snapAfter) {
var _this = this;
if (sizes === void 0) { sizes = this.viewItems.map(function (i) { return i.size; }); }
if (overloadMinDelta === void 0) { overloadMinDelta = Number.NEGATIVE_INFINITY; }
if (overloadMaxDelta === void 0) { overloadMaxDelta = Number.POSITIVE_INFINITY; }
if (index < 0 || index >= this.viewItems.length) {
return 0;
}
var upIndexes = arrays_1.range(index, -1);
var downIndexes = arrays_1.range(index + 1, this.viewItems.length);
if (highPriorityIndexes) {
for (var _i = 0, highPriorityIndexes_1 = highPriorityIndexes; _i < highPriorityIndexes_1.length; _i++) {
var index_1 = highPriorityIndexes_1[_i];
arrays_1.pushToStart(upIndexes, index_1);
arrays_1.pushToStart(downIndexes, index_1);
}
}
if (lowPriorityIndexes) {
for (var _a = 0, lowPriorityIndexes_1 = lowPriorityIndexes; _a < lowPriorityIndexes_1.length; _a++) {
var index_2 = lowPriorityIndexes_1[_a];
arrays_1.pushToEnd(upIndexes, index_2);
arrays_1.pushToEnd(downIndexes, index_2);
}
}
var upItems = upIndexes.map(function (i) { return _this.viewItems[i]; });
var upSizes = upIndexes.map(function (i) { return sizes[i]; });
var downItems = downIndexes.map(function (i) { return _this.viewItems[i]; });
var downSizes = downIndexes.map(function (i) { return sizes[i]; });
var minDeltaUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].minimumSize - sizes[i]); }, 0);
var maxDeltaUp = upIndexes.reduce(function (r, i) { return r + (_this.viewItems[i].maximumSize - sizes[i]); }, 0);
var maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].minimumSize); }, 0);
var minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce(function (r, i) { return r + (sizes[i] - _this.viewItems[i].maximumSize); }, 0);
var minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta);
var maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta);
var snapped = false;
if (snapBefore) {
var snapView = this.viewItems[snapBefore.index];
var visible = delta >= snapBefore.limitDelta;
snapped = visible !== snapView.visible;
snapView.setVisible(visible, snapBefore.size);
}
if (!snapped && snapAfter) {
var snapView = this.viewItems[snapAfter.index];
var visible = delta < snapAfter.limitDelta;
snapped = visible !== snapView.visible;
snapView.setVisible(visible, snapAfter.size);
}
if (snapped) {
return this.resize(index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta);
}
delta = numbers_1.clamp(delta, minDelta, maxDelta);
for (var i = 0, deltaUp = delta; i < upItems.length; i++) {
var item = upItems[i];
var size = numbers_1.clamp(upSizes[i] + deltaUp, item.minimumSize, item.maximumSize);
var viewDelta = size - upSizes[i];
deltaUp -= viewDelta;
item.size = size;
}
for (var i = 0, deltaDown = delta; i < downItems.length; i++) {
var item = downItems[i];
var size = numbers_1.clamp(downSizes[i] - deltaDown, item.minimumSize, item.maximumSize);
var viewDelta = size - downSizes[i];
deltaDown += viewDelta;
item.size = size;
}
return delta;
};
SplitView.prototype.distributeEmptySpace = function (lowPriorityIndex) {
var _this = this;
var contentSize = this.viewItems.reduce(function (r, i) { return r + i.size; }, 0);
var emptyDelta = this.size - contentSize;
var indexes = arrays_1.range(this.viewItems.length - 1, -1);
var lowPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 1 /* Low */; });
var highPriorityIndexes = indexes.filter(function (i) { return _this.viewItems[i].priority === 2 /* High */; });
for (var _i = 0, highPriorityIndexes_2 = highPriorityIndexes; _i < highPriorityIndexes_2.length; _i++) {
var index = highPriorityIndexes_2[_i];
arrays_1.pushToStart(indexes, index);
}
for (var _a = 0, lowPriorityIndexes_2 = lowPriorityIndexes; _a < lowPriorityIndexes_2.length; _a++) {
var index = lowPriorityIndexes_2[_a];
arrays_1.pushToEnd(indexes, index);
}
if (typeof lowPriorityIndex === 'number') {
arrays_1.pushToEnd(indexes, lowPriorityIndex);
}
for (var i = 0; emptyDelta !== 0 && i < indexes.length; i++) {
var item = this.viewItems[indexes[i]];
var size = numbers_1.clamp(item.size + emptyDelta, item.minimumSize, item.maximumSize);
var viewDelta = size - item.size;
emptyDelta -= viewDelta;
item.size = size;
}
};
SplitView.prototype.layoutViews = function () {
// Save new content size
this.contentSize = this.viewItems.reduce(function (r, i) { return r + i.size; }, 0);
// Layout views
var offset = 0;
for (var _i = 0, _a = this.viewItems; _i < _a.length; _i++) {
var viewItem = _a[_i];
viewItem.layout(offset, this.layoutContext);
offset += viewItem.size;
}
// Layout sashes
this.sashItems.forEach(function (item) { return item.sash.layout(); });
this.updateSashEnablement();
};
SplitView.prototype.updateSashEnablement = function () {
var previous = false;
var collapsesDown = this.viewItems.map(function (i) { return previous = (i.size - i.minimumSize > 0) || previous; });
previous = false;
var expandsDown = this.viewItems.map(function (i) { return previous = (i.maximumSize - i.size > 0) || previous; });
var reverseViews = __spreadArrays(this.viewItems).reverse();
previous = false;
var collapsesUp = reverseViews.map(function (i) { return previous = (i.size - i.minimumSize > 0) || previous; }).reverse();
previous = false;
var expandsUp = reverseViews.map(function (i) { return previous = (i.maximumSize - i.size > 0) || previous; }).reverse();
var position = 0;
for (var index = 0; index < this.sashItems.length; index++) {
var sash = this.sashItems[index].sash;
var viewItem = this.viewItems[index];
position += viewItem.size;
var min = !(collapsesDown[index] && expandsUp[index + 1]);
var max = !(expandsDown[index] && collapsesUp[index + 1]);
if (min && max) {
var upIndexes = arrays_1.range(index, -1);
var downIndexes = arrays_1.range(index + 1, this.viewItems.length);
var snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
var snapAfterIndex = this.findFirstSnapIndex(downIndexes);
var snappedBefore = typeof snapBeforeIndex === 'number' && !this.viewItems[snapBeforeIndex].visible;
var snappedAfter = typeof snapAfterIndex === 'number' && !this.viewItems[snapAfterIndex].visible;
if (snappedBefore && collapsesUp[index] && (position > 0 || this.startSnappingEnabled)) {
sash.state = 1 /* Minimum */;
}
else if (snappedAfter && collapsesDown[index] && (position < this.contentSize || this.endSnappingEnabled)) {
sash.state = 2 /* Maximum */;
}
else {
sash.state = 0 /* Disabled */;
}
}
else if (min && !max) {
sash.state = 1 /* Minimum */;
}
else if (!min && max) {
sash.state = 2 /* Maximum */;
}
else {
sash.state = 3 /* Enabled */;
}
}
};
SplitView.prototype.getSashPosition = function (sash) {
var position = 0;
for (var i = 0; i < this.sashItems.length; i++) {
position += this.viewItems[i].size;
if (this.sashItems[i].sash === sash) {
return Math.min(position, this.contentSize - 2);
}
}
return 0;
};
SplitView.prototype.findFirstSnapIndex = function (indexes) {
// visible views first
for (var _i = 0, indexes_1 = indexes; _i < indexes_1.length; _i++) {
var index = indexes_1[_i];
var viewItem = this.viewItems[index];
if (!viewItem.visible) {
continue;
}
if (viewItem.snap) {
return index;
}
}
// then, hidden views
for (var _a = 0, indexes_2 = indexes; _a < indexes_2.length; _a++) {
var index = indexes_2[_a];
var viewItem = this.viewItems[index];
if (viewItem.visible && viewItem.maximumSize - viewItem.minimumSize > 0) {
return undefined;
}
if (!viewItem.visible && viewItem.snap) {
return index;
}
}
return undefined;
};
SplitView.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.viewItems.forEach(function (i) { return i.dispose(); });
this.viewItems = [];
this.sashItems.forEach(function (i) { return i.disposable.dispose(); });
this.sashItems = [];
};
return SplitView;
}(lifecycle_1.Disposable));
exports.SplitView = SplitView;
});
define(__m[280/*vs/css!vs/base/browser/ui/tree/media/tree*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[281/*vs/css!vs/base/parts/quickopen/browser/quickopen*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[282/*vs/css!vs/base/parts/tree/browser/tree*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[283/*vs/base/parts/tree/browser/treeImpl*/], __M([0/*require*/,1/*exports*/,137/*vs/base/parts/tree/browser/treeDefaults*/,256/*vs/base/parts/tree/browser/treeModel*/,277/*vs/base/parts/tree/browser/treeView*/,4/*vs/base/common/event*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,282/*vs/css!vs/base/parts/tree/browser/tree*/]), function (require, exports, TreeDefaults, Model, View, event_1, color_1, objects_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TreeContext = /** @class */ (function () {
function TreeContext(tree, configuration, options) {
if (options === void 0) { options = {}; }
this.tree = tree;
this.configuration = configuration;
this.options = options;
if (!configuration.dataSource) {
throw new Error('You must provide a Data Source to the tree.');
}
this.dataSource = configuration.dataSource;
this.renderer = configuration.renderer;
this.controller = configuration.controller || new TreeDefaults.DefaultController({ clickBehavior: 1 /* ON_MOUSE_UP */, keyboardSupport: typeof options.keyboardSupport !== 'boolean' || options.keyboardSupport });
this.dnd = configuration.dnd || new TreeDefaults.DefaultDragAndDrop();
this.filter = configuration.filter || new TreeDefaults.DefaultFilter();
this.sorter = configuration.sorter;
this.accessibilityProvider = configuration.accessibilityProvider || new TreeDefaults.DefaultAccessibilityProvider();
this.styler = configuration.styler;
}
return TreeContext;
}());
exports.TreeContext = TreeContext;
var defaultStyles = {
listFocusBackground: color_1.Color.fromHex('#073655'),
listActiveSelectionBackground: color_1.Color.fromHex('#0E639C'),
listActiveSelectionForeground: color_1.Color.fromHex('#FFFFFF'),
listFocusAndSelectionBackground: color_1.Color.fromHex('#094771'),
listFocusAndSelectionForeground: color_1.Color.fromHex('#FFFFFF'),
listInactiveSelectionBackground: color_1.Color.fromHex('#3F3F46'),
listHoverBackground: color_1.Color.fromHex('#2A2D2E'),
listDropBackground: color_1.Color.fromHex('#383B3D')
};
var Tree = /** @class */ (function () {
function Tree(container, configuration, options) {
if (options === void 0) { options = {}; }
this._onDidChangeFocus = new event_1.Relay();
this.onDidChangeFocus = this._onDidChangeFocus.event;
this._onDidChangeSelection = new event_1.Relay();
this.onDidChangeSelection = this._onDidChangeSelection.event;
this._onHighlightChange = new event_1.Relay();
this._onDidExpandItem = new event_1.Relay();
this._onDidCollapseItem = new event_1.Relay();
this._onDispose = new event_1.Emitter();
this.onDidDispose = this._onDispose.event;
this.container = container;
objects_1.mixin(options, defaultStyles, false);
options.twistiePixels = typeof options.twistiePixels === 'number' ? options.twistiePixels : 32;
options.showTwistie = options.showTwistie === false ? false : true;
options.indentPixels = typeof options.indentPixels === 'number' ? options.indentPixels : 12;
options.alwaysFocused = options.alwaysFocused === true ? true : false;
options.useShadows = options.useShadows === false ? false : true;
options.paddingOnRow = options.paddingOnRow === false ? false : true;
options.showLoading = options.showLoading === false ? false : true;
this.context = new TreeContext(this, configuration, options);
this.model = new Model.TreeModel(this.context);
this.view = new View.TreeView(this.context, this.container);
this.view.setModel(this.model);
this._onDidChangeFocus.input = this.model.onDidFocus;
this._onDidChangeSelection.input = this.model.onDidSelect;
this._onHighlightChange.input = this.model.onDidHighlight;
this._onDidExpandItem.input = this.model.onDidExpandItem;
this._onDidCollapseItem.input = this.model.onDidCollapseItem;
}
Tree.prototype.style = function (styles) {
this.view.applyStyles(styles);
};
Object.defineProperty(Tree.prototype, "onDidFocus", {
get: function () {
return this.view.onDOMFocus;
},
enumerable: true,
configurable: true
});
Tree.prototype.getHTMLElement = function () {
return this.view.getHTMLElement();
};
Tree.prototype.layout = function (height, width) {
this.view.layout(height, width);
};
Tree.prototype.domFocus = function () {
this.view.focus();
};
Tree.prototype.isDOMFocused = function () {
return this.view.isFocused();
};
Tree.prototype.domBlur = function () {
this.view.blur();
};
Tree.prototype.setInput = function (element) {
return this.model.setInput(element);
};
Tree.prototype.getInput = function () {
return this.model.getInput();
};
Tree.prototype.expand = function (element) {
return this.model.expand(element);
};
Tree.prototype.collapse = function (element, recursive) {
if (recursive === void 0) { recursive = false; }
return this.model.collapse(element, recursive);
};
Tree.prototype.toggleExpansion = function (element, recursive) {
if (recursive === void 0) { recursive = false; }
return this.model.toggleExpansion(element, recursive);
};
Tree.prototype.isExpanded = function (element) {
return this.model.isExpanded(element);
};
Tree.prototype.reveal = function (element, relativeTop) {
if (relativeTop === void 0) { relativeTop = null; }
return this.model.reveal(element, relativeTop);
};
Tree.prototype.getHighlight = function () {
return this.model.getHighlight();
};
Tree.prototype.clearHighlight = function (eventPayload) {
this.model.setHighlight(null, eventPayload);
};
Tree.prototype.setSelection = function (elements, eventPayload) {
this.model.setSelection(elements, eventPayload);
};
Tree.prototype.getSelection = function () {
return this.model.getSelection();
};
Tree.prototype.clearSelection = function (eventPayload) {
this.model.setSelection([], eventPayload);
};
Tree.prototype.setFocus = function (element, eventPayload) {
this.model.setFocus(element, eventPayload);
};
Tree.prototype.getFocus = function () {
return this.model.getFocus();
};
Tree.prototype.focusNext = function (count, eventPayload) {
this.model.focusNext(count, eventPayload);
};
Tree.prototype.focusPrevious = function (count, eventPayload) {
this.model.focusPrevious(count, eventPayload);
};
Tree.prototype.focusParent = function (eventPayload) {
this.model.focusParent(eventPayload);
};
Tree.prototype.focusFirstChild = function (eventPayload) {
this.model.focusFirstChild(eventPayload);
};
Tree.prototype.focusFirst = function (eventPayload, from) {
this.model.focusFirst(eventPayload, from);
};
Tree.prototype.focusNth = function (index, eventPayload) {
this.model.focusNth(index, eventPayload);
};
Tree.prototype.focusLast = function (eventPayload, from) {
this.model.focusLast(eventPayload, from);
};
Tree.prototype.focusNextPage = function (eventPayload) {
this.view.focusNextPage(eventPayload);
};
Tree.prototype.focusPreviousPage = function (eventPayload) {
this.view.focusPreviousPage(eventPayload);
};
Tree.prototype.clearFocus = function (eventPayload) {
this.model.setFocus(null, eventPayload);
};
Tree.prototype.dispose = function () {
this._onDispose.fire();
this.model.dispose();
this.view.dispose();
this._onDidChangeFocus.dispose();
this._onDidChangeSelection.dispose();
this._onHighlightChange.dispose();
this._onDidExpandItem.dispose();
this._onDidCollapseItem.dispose();
this._onDispose.dispose();
};
return Tree;
}());
exports.Tree = Tree;
});
define(__m[284/*vs/css!vs/editor/browser/controller/textAreaHandler*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[285/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[286/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[287/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[288/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[289/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[290/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[291/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[292/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[293/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[294/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[295/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[296/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[297/*vs/css!vs/editor/browser/viewParts/selections/selections*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[298/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[299/*vs/css!vs/editor/browser/widget/media/diffEditor*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[300/*vs/css!vs/editor/browser/widget/media/diffReview*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[301/*vs/css!vs/editor/browser/widget/media/editor*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[302/*vs/css!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[303/*vs/css!vs/editor/contrib/clipboard/clipboard*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[304/*vs/css!vs/editor/contrib/codeAction/lightBulbWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[305/*vs/css!vs/editor/contrib/codelens/codelensWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[306/*vs/css!vs/editor/contrib/colorPicker/colorPicker*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[307/*vs/css!vs/editor/contrib/dnd/dnd*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[308/*vs/css!vs/editor/contrib/documentSymbols/media/outlineTree*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[309/*vs/css!vs/editor/contrib/documentSymbols/media/symbol-icons*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[310/*vs/css!vs/editor/contrib/find/findWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[311/*vs/css!vs/editor/contrib/folding/folding*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[312/*vs/css!vs/editor/contrib/gotoError/media/gotoErrorWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[313/*vs/css!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[314/*vs/css!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[315/*vs/css!vs/editor/contrib/hover/hover*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[316/*vs/css!vs/editor/contrib/links/links*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[317/*vs/css!vs/editor/contrib/message/messageController*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[318/*vs/css!vs/editor/contrib/parameterHints/parameterHints*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[319/*vs/css!vs/editor/contrib/peekView/media/peekViewWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[320/*vs/css!vs/editor/contrib/rename/renameInputField*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[321/*vs/css!vs/editor/contrib/snippet/snippetSession*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[322/*vs/css!vs/editor/contrib/suggest/media/suggest*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[323/*vs/css!vs/editor/contrib/suggest/media/suggestStatusBar*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[324/*vs/css!vs/editor/contrib/zoneWidget/zoneWidget*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[325/*vs/css!vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[326/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[327/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[328/*vs/css!vs/editor/standalone/browser/quickOpen/editorQuickOpen*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[329/*vs/css!vs/editor/standalone/browser/quickOpen/gotoLine*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[330/*vs/css!vs/editor/standalone/browser/quickOpen/quickOutline*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[331/*vs/css!vs/editor/standalone/browser/standalone-tokens*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
define(__m[332/*vs/css!vs/platform/contextview/browser/contextMenuHandler*/], __M([9/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[333/*vs/editor/browser/config/charWidthReader*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CharWidthRequest = /** @class */ (function () {
function CharWidthRequest(chr, type) {
this.chr = chr;
this.type = type;
this.width = 0;
}
CharWidthRequest.prototype.fulfill = function (width) {
this.width = width;
};
return CharWidthRequest;
}());
exports.CharWidthRequest = CharWidthRequest;
var DomCharWidthReader = /** @class */ (function () {
function DomCharWidthReader(bareFontInfo, requests) {
this._bareFontInfo = bareFontInfo;
this._requests = requests;
this._container = null;
this._testElements = null;
}
DomCharWidthReader.prototype.read = function () {
// Create a test container with all these test elements
this._createDomElements();
// Add the container to the DOM
document.body.appendChild(this._container);
// Read character widths
this._readFromDomElements();
// Remove the container from the DOM
document.body.removeChild(this._container);
this._container = null;
this._testElements = null;
};
DomCharWidthReader.prototype._createDomElements = function () {
var container = document.createElement('div');
container.style.position = 'absolute';
container.style.top = '-50000px';
container.style.width = '50000px';
var regularDomNode = document.createElement('div');
regularDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
regularDomNode.style.fontWeight = this._bareFontInfo.fontWeight;
regularDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px';
regularDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
regularDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px';
regularDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px';
container.appendChild(regularDomNode);
var boldDomNode = document.createElement('div');
boldDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
boldDomNode.style.fontWeight = 'bold';
boldDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px';
boldDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
boldDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px';
boldDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px';
container.appendChild(boldDomNode);
var italicDomNode = document.createElement('div');
italicDomNode.style.fontFamily = this._bareFontInfo.getMassagedFontFamily();
italicDomNode.style.fontWeight = this._bareFontInfo.fontWeight;
italicDomNode.style.fontSize = this._bareFontInfo.fontSize + 'px';
italicDomNode.style.fontFeatureSettings = this._bareFontInfo.fontFeatureSettings;
italicDomNode.style.lineHeight = this._bareFontInfo.lineHeight + 'px';
italicDomNode.style.letterSpacing = this._bareFontInfo.letterSpacing + 'px';
italicDomNode.style.fontStyle = 'italic';
container.appendChild(italicDomNode);
var testElements = [];
for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
var request = _a[_i];
var parent_1 = void 0;
if (request.type === 0 /* Regular */) {
parent_1 = regularDomNode;
}
if (request.type === 2 /* Bold */) {
parent_1 = boldDomNode;
}
if (request.type === 1 /* Italic */) {
parent_1 = italicDomNode;
}
parent_1.appendChild(document.createElement('br'));
var testElement = document.createElement('span');
DomCharWidthReader._render(testElement, request);
parent_1.appendChild(testElement);
testElements.push(testElement);
}
this._container = container;
this._testElements = testElements;
};
DomCharWidthReader._render = function (testElement, request) {
if (request.chr === ' ') {
var htmlString = ' ';
// Repeat character 256 (2^8) times
for (var i = 0; i < 8; i++) {
htmlString += htmlString;
}
testElement.innerHTML = htmlString;
}
else {
var testString = request.chr;
// Repeat character 256 (2^8) times
for (var i = 0; i < 8; i++) {
testString += testString;
}
testElement.textContent = testString;
}
};
DomCharWidthReader.prototype._readFromDomElements = function () {
for (var i = 0, len = this._requests.length; i < len; i++) {
var request = this._requests[i];
var testElement = this._testElements[i];
request.fulfill(testElement.offsetWidth / 256);
}
};
return DomCharWidthReader;
}());
function readCharWidths(bareFontInfo, requests) {
var reader = new DomCharWidthReader(bareFontInfo, requests);
reader.read();
}
exports.readCharWidths = readCharWidths;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[185/*vs/editor/browser/config/elementSizeObserver*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/browser/dom*/]), function (require, exports, lifecycle_1, dom) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ElementSizeObserver = /** @class */ (function (_super) {
__extends(ElementSizeObserver, _super);
function ElementSizeObserver(referenceDomElement, dimension, changeCallback) {
var _this = _super.call(this) || this;
_this.referenceDomElement = referenceDomElement;
_this.changeCallback = changeCallback;
_this.width = -1;
_this.height = -1;
_this.mutationObserver = null;
_this.windowSizeListener = null;
_this.measureReferenceDomElement(false, dimension);
return _this;
}
ElementSizeObserver.prototype.dispose = function () {
this.stopObserving();
_super.prototype.dispose.call(this);
};
ElementSizeObserver.prototype.getWidth = function () {
return this.width;
};
ElementSizeObserver.prototype.getHeight = function () {
return this.height;
};
ElementSizeObserver.prototype.startObserving = function () {
var _this = this;
if (!this.mutationObserver && this.referenceDomElement) {
this.mutationObserver = new MutationObserver(function () { return _this._onDidMutate(); });
this.mutationObserver.observe(this.referenceDomElement, {
attributes: true,
});
}
if (!this.windowSizeListener) {
this.windowSizeListener = dom.addDisposableListener(window, 'resize', function () { return _this._onDidResizeWindow(); });
}
};
ElementSizeObserver.prototype.stopObserving = function () {
if (this.mutationObserver) {
this.mutationObserver.disconnect();
this.mutationObserver = null;
}
if (this.windowSizeListener) {
this.windowSizeListener.dispose();
this.windowSizeListener = null;
}
};
ElementSizeObserver.prototype.observe = function (dimension) {
this.measureReferenceDomElement(true, dimension);
};
ElementSizeObserver.prototype._onDidMutate = function () {
this.measureReferenceDomElement(true);
};
ElementSizeObserver.prototype._onDidResizeWindow = function () {
this.measureReferenceDomElement(true);
};
ElementSizeObserver.prototype.measureReferenceDomElement = function (callChangeCallback, dimension) {
var observedWidth = 0;
var observedHeight = 0;
if (dimension) {
observedWidth = dimension.width;
observedHeight = dimension.height;
}
else if (this.referenceDomElement) {
observedWidth = this.referenceDomElement.clientWidth;
observedHeight = this.referenceDomElement.clientHeight;
}
observedWidth = Math.max(5, observedWidth);
observedHeight = Math.max(5, observedHeight);
if (this.width !== observedWidth || this.height !== observedHeight) {
this.width = observedWidth;
this.height = observedHeight;
if (callChangeCallback) {
this.changeCallback();
}
}
};
return ElementSizeObserver;
}(lifecycle_1.Disposable));
exports.ElementSizeObserver = ElementSizeObserver;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[141/*vs/editor/browser/editorDom*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,78/*vs/base/browser/globalMouseMoveMonitor*/,45/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom, globalMouseMoveMonitor_1, mouseEvent_1, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Coordinates relative to the whole document (e.g. mouse event's pageX and pageY)
*/
var PageCoordinates = /** @class */ (function () {
function PageCoordinates(x, y) {
this.x = x;
this.y = y;
}
PageCoordinates.prototype.toClientCoordinates = function () {
return new ClientCoordinates(this.x - dom.StandardWindow.scrollX, this.y - dom.StandardWindow.scrollY);
};
return PageCoordinates;
}());
exports.PageCoordinates = PageCoordinates;
/**
* Coordinates within the application's client area (i.e. origin is document's scroll position).
*
* For example, clicking in the top-left corner of the client area will
* always result in a mouse event with a client.x value of 0, regardless
* of whether the page is scrolled horizontally.
*/
var ClientCoordinates = /** @class */ (function () {
function ClientCoordinates(clientX, clientY) {
this.clientX = clientX;
this.clientY = clientY;
}
ClientCoordinates.prototype.toPageCoordinates = function () {
return new PageCoordinates(this.clientX + dom.StandardWindow.scrollX, this.clientY + dom.StandardWindow.scrollY);
};
return ClientCoordinates;
}());
exports.ClientCoordinates = ClientCoordinates;
/**
* The position of the editor in the page.
*/
var EditorPagePosition = /** @class */ (function () {
function EditorPagePosition(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
return EditorPagePosition;
}());
exports.EditorPagePosition = EditorPagePosition;
function createEditorPagePosition(editorViewDomNode) {
var editorPos = dom.getDomNodePagePosition(editorViewDomNode);
return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height);
}
exports.createEditorPagePosition = createEditorPagePosition;
var EditorMouseEvent = /** @class */ (function (_super) {
__extends(EditorMouseEvent, _super);
function EditorMouseEvent(e, editorViewDomNode) {
var _this = _super.call(this, e) || this;
_this.pos = new PageCoordinates(_this.posx, _this.posy);
_this.editorPos = createEditorPagePosition(editorViewDomNode);
return _this;
}
return EditorMouseEvent;
}(mouseEvent_1.StandardMouseEvent));
exports.EditorMouseEvent = EditorMouseEvent;
var EditorMouseEventFactory = /** @class */ (function () {
function EditorMouseEventFactory(editorViewDomNode) {
this._editorViewDomNode = editorViewDomNode;
}
EditorMouseEventFactory.prototype._create = function (e) {
return new EditorMouseEvent(e, this._editorViewDomNode);
};
EditorMouseEventFactory.prototype.onContextMenu = function (target, callback) {
var _this = this;
return dom.addDisposableListener(target, 'contextmenu', function (e) {
callback(_this._create(e));
});
};
EditorMouseEventFactory.prototype.onMouseUp = function (target, callback) {
var _this = this;
return dom.addDisposableListener(target, 'mouseup', function (e) {
callback(_this._create(e));
});
};
EditorMouseEventFactory.prototype.onMouseDown = function (target, callback) {
var _this = this;
return dom.addDisposableListener(target, 'mousedown', function (e) {
callback(_this._create(e));
});
};
EditorMouseEventFactory.prototype.onMouseLeave = function (target, callback) {
var _this = this;
return dom.addDisposableNonBubblingMouseOutListener(target, function (e) {
callback(_this._create(e));
});
};
EditorMouseEventFactory.prototype.onMouseMoveThrottled = function (target, callback, merger, minimumTimeMs) {
var _this = this;
var myMerger = function (lastEvent, currentEvent) {
return merger(lastEvent, _this._create(currentEvent));
};
return dom.addDisposableThrottledListener(target, 'mousemove', callback, myMerger, minimumTimeMs);
};
return EditorMouseEventFactory;
}());
exports.EditorMouseEventFactory = EditorMouseEventFactory;
var EditorPointerEventFactory = /** @class */ (function () {
function EditorPointerEventFactory(editorViewDomNode) {
this._editorViewDomNode = editorViewDomNode;
}
EditorPointerEventFactory.prototype._create = function (e) {
return new EditorMouseEvent(e, this._editorViewDomNode);
};
EditorPointerEventFactory.prototype.onPointerUp = function (target, callback) {
var _this = this;
return dom.addDisposableListener(target, 'pointerup', function (e) {
callback(_this._create(e));
});
};
EditorPointerEventFactory.prototype.onPointerDown = function (target, callback) {
var _this = this;
return dom.addDisposableListener(target, 'pointerdown', function (e) {
callback(_this._create(e));
});
};
EditorPointerEventFactory.prototype.onPointerLeave = function (target, callback) {
var _this = this;
return dom.addDisposableNonBubblingPointerOutListener(target, function (e) {
callback(_this._create(e));
});
};
EditorPointerEventFactory.prototype.onPointerMoveThrottled = function (target, callback, merger, minimumTimeMs) {
var _this = this;
var myMerger = function (lastEvent, currentEvent) {
return merger(lastEvent, _this._create(currentEvent));
};
return dom.addDisposableThrottledListener(target, 'pointermove', callback, myMerger, minimumTimeMs);
};
return EditorPointerEventFactory;
}());
exports.EditorPointerEventFactory = EditorPointerEventFactory;
var GlobalEditorMouseMoveMonitor = /** @class */ (function (_super) {
__extends(GlobalEditorMouseMoveMonitor, _super);
function GlobalEditorMouseMoveMonitor(editorViewDomNode) {
var _this = _super.call(this) || this;
_this._editorViewDomNode = editorViewDomNode;
_this._globalMouseMoveMonitor = _this._register(new globalMouseMoveMonitor_1.GlobalMouseMoveMonitor());
_this._keydownListener = null;
return _this;
}
GlobalEditorMouseMoveMonitor.prototype.startMonitoring = function (initialElement, initialButtons, merger, mouseMoveCallback, onStopCallback) {
var _this = this;
// Add a <> keydown event listener that will cancel the monitoring
// if something other than a modifier key is pressed
this._keydownListener = dom.addStandardDisposableListener(document, 'keydown', function (e) {
var kb = e.toKeybinding();
if (kb.isModifierKey()) {
// Allow modifier keys
return;
}
_this._globalMouseMoveMonitor.stopMonitoring(true);
}, true);
var myMerger = function (lastEvent, currentEvent) {
return merger(lastEvent, new EditorMouseEvent(currentEvent, _this._editorViewDomNode));
};
this._globalMouseMoveMonitor.startMonitoring(initialElement, initialButtons, myMerger, mouseMoveCallback, function () {
_this._keydownListener.dispose();
onStopCallback();
});
};
return GlobalEditorMouseMoveMonitor;
}(lifecycle_1.Disposable));
exports.GlobalEditorMouseMoveMonitor = GlobalEditorMouseMoveMonitor;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[334/*vs/editor/browser/services/abstractCodeEditorService*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var AbstractCodeEditorService = /** @class */ (function (_super) {
__extends(AbstractCodeEditorService, _super);
function AbstractCodeEditorService() {
var _this = _super.call(this) || this;
_this._onCodeEditorAdd = _this._register(new event_1.Emitter());
_this.onCodeEditorAdd = _this._onCodeEditorAdd.event;
_this._onCodeEditorRemove = _this._register(new event_1.Emitter());
_this.onCodeEditorRemove = _this._onCodeEditorRemove.event;
_this._onDiffEditorAdd = _this._register(new event_1.Emitter());
_this._onDiffEditorRemove = _this._register(new event_1.Emitter());
_this._codeEditors = Object.create(null);
_this._diffEditors = Object.create(null);
return _this;
}
AbstractCodeEditorService.prototype.addCodeEditor = function (editor) {
this._codeEditors[editor.getId()] = editor;
this._onCodeEditorAdd.fire(editor);
};
AbstractCodeEditorService.prototype.removeCodeEditor = function (editor) {
if (delete this._codeEditors[editor.getId()]) {
this._onCodeEditorRemove.fire(editor);
}
};
AbstractCodeEditorService.prototype.listCodeEditors = function () {
var _this = this;
return Object.keys(this._codeEditors).map(function (id) { return _this._codeEditors[id]; });
};
AbstractCodeEditorService.prototype.addDiffEditor = function (editor) {
this._diffEditors[editor.getId()] = editor;
this._onDiffEditorAdd.fire(editor);
};
AbstractCodeEditorService.prototype.removeDiffEditor = function (editor) {
if (delete this._diffEditors[editor.getId()]) {
this._onDiffEditorRemove.fire(editor);
}
};
AbstractCodeEditorService.prototype.listDiffEditors = function () {
var _this = this;
return Object.keys(this._diffEditors).map(function (id) { return _this._diffEditors[id]; });
};
AbstractCodeEditorService.prototype.getFocusedCodeEditor = function () {
var editorWithWidgetFocus = null;
var editors = this.listCodeEditors();
for (var _i = 0, editors_1 = editors; _i < editors_1.length; _i++) {
var editor = editors_1[_i];
if (editor.hasTextFocus()) {
// bingo!
return editor;
}
if (editor.hasWidgetFocus()) {
editorWithWidgetFocus = editor;
}
}
return editorWithWidgetFocus;
};
return AbstractCodeEditorService;
}(lifecycle_1.Disposable));
exports.AbstractCodeEditorService = AbstractCodeEditorService;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[186/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.allCharCodes = (function () {
var v = [];
for (var i = 32 /* START_CH_CODE */; i <= 126 /* END_CH_CODE */; i++) {
v.push(i);
}
v.push(65533 /* UNKNOWN_CODE */);
return v;
})();
exports.getCharIndex = function (chCode, fontScale) {
chCode -= 32 /* START_CH_CODE */;
if (chCode < 0 || chCode > 96 /* CHAR_COUNT */) {
if (fontScale <= 2) {
// for smaller scales, we can get away with using any ASCII character...
return (chCode + 96 /* CHAR_COUNT */) % 96 /* CHAR_COUNT */;
}
return 96 /* CHAR_COUNT */ - 1; // unknown symbol
}
return chCode;
};
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[335/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/], __M([0/*require*/,1/*exports*/,186/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/]), function (require, exports, minimapCharSheet_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MinimapCharRenderer = /** @class */ (function () {
function MinimapCharRenderer(charData, scale) {
this.scale = scale;
this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15);
this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60);
}
MinimapCharRenderer.soften = function (input, ratio) {
var result = new Uint8ClampedArray(input.length);
for (var i = 0, len = input.length; i < len; i++) {
result[i] = input[i] * ratio;
}
return result;
};
MinimapCharRenderer.prototype.renderChar = function (target, dx, dy, chCode, color, backgroundColor, fontScale, useLighterFont) {
var charWidth = 1 /* BASE_CHAR_WIDTH */ * this.scale;
var charHeight = 2 /* BASE_CHAR_HEIGHT */ * this.scale;
if (dx + charWidth > target.width || dy + charHeight > target.height) {
console.warn('bad render request outside image data');
return;
}
var charData = useLighterFont ? this.charDataLight : this.charDataNormal;
var charIndex = minimapCharSheet_1.getCharIndex(chCode, fontScale);
var destWidth = target.width * 4 /* RGBA_CHANNELS_CNT */;
var backgroundR = backgroundColor.r;
var backgroundG = backgroundColor.g;
var backgroundB = backgroundColor.b;
var deltaR = color.r - backgroundR;
var deltaG = color.g - backgroundG;
var deltaB = color.b - backgroundB;
var dest = target.data;
var sourceOffset = charIndex * charWidth * charHeight;
var row = dy * destWidth + dx * 4 /* RGBA_CHANNELS_CNT */;
for (var y = 0; y < charHeight; y++) {
var column = row;
for (var x = 0; x < charWidth; x++) {
var c = charData[sourceOffset++] / 255;
dest[column++] = backgroundR + deltaR * c;
dest[column++] = backgroundG + deltaG * c;
dest[column++] = backgroundB + deltaB * c;
column++;
}
row += destWidth;
}
};
MinimapCharRenderer.prototype.blockRenderChar = function (target, dx, dy, color, backgroundColor, useLighterFont) {
var charWidth = 1 /* BASE_CHAR_WIDTH */ * this.scale;
var charHeight = 2 /* BASE_CHAR_HEIGHT */ * this.scale;
if (dx + charWidth > target.width || dy + charHeight > target.height) {
console.warn('bad render request outside image data');
return;
}
var destWidth = target.width * 4 /* RGBA_CHANNELS_CNT */;
var c = 0.5;
var backgroundR = backgroundColor.r;
var backgroundG = backgroundColor.g;
var backgroundB = backgroundColor.b;
var deltaR = color.r - backgroundR;
var deltaG = color.g - backgroundG;
var deltaB = color.b - backgroundB;
var colorR = backgroundR + deltaR * c;
var colorG = backgroundG + deltaG * c;
var colorB = backgroundB + deltaB * c;
var dest = target.data;
var row = dy * destWidth + dx * 4 /* RGBA_CHANNELS_CNT */;
for (var y = 0; y < charHeight; y++) {
var column = row;
for (var x = 0; x < charWidth; x++) {
dest[column++] = colorR;
dest[column++] = colorG;
dest[column++] = colorB;
column++;
}
row += destWidth;
}
};
return MinimapCharRenderer;
}());
exports.MinimapCharRenderer = MinimapCharRenderer;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[336/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/], __M([0/*require*/,1/*exports*/,102/*vs/base/common/functional*/]), function (require, exports, functional_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var charTable = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
A: 10,
B: 11,
C: 12,
D: 13,
E: 14,
F: 15
};
var decodeData = function (str) {
var output = new Uint8ClampedArray(str.length / 2);
for (var i = 0; i < str.length; i += 2) {
output[i >> 1] = (charTable[str[i]] << 4) | (charTable[str[i + 1]] & 0xF);
}
return output;
};
/*
const encodeData = (data: Uint8ClampedArray, length: string) => {
const chars = '0123456789ABCDEF';
let output = '';
for (let i = 0; i < data.length; i++) {
output += chars[data[i] >> 4] + chars[data[i] & 0xf];
}
return output;
};
*/
/**
* Map of minimap scales to prebaked sample data at those scales. We don't
* sample much larger data, because then font family becomes visible, which
* is use-configurable.
*/
exports.prebakedMiniMaps = {
1: functional_1.once(function () {
return decodeData('0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792');
}),
2: functional_1.once(function () {
return decodeData('000000000000000055394F383D2800008B8B1F210002000081B1CBCBCC820000847AAF6B9AAF2119BE08B8881AD60000A44FD07DCCF107015338130C00000000385972265F390B406E2437634B4B48031B12B8A0847000001E15B29A402F0000000000004B33460B00007A752C2A0000000000004D3900000084394B82013400ABA5CFC7AD9C0302A45A3E5A98AB000089A43382D97900008BA54AA087A70A0248A6A7AE6DBE0000BF6F94987EA40A01A06DCFA7A7A9030496C32F77891D0000A99FB1A0AFA80603B29AB9CA75930D010C0948354D3900000C0948354F37460D0028BE673D8400000000AF9D7B6E00002B007AA8933400007AA642675C2700007984CFB9C3985B768772A8A6B7B20000CAAECAAFC4B700009F94A6009F840009D09F9BA4CA9C0000CC8FC76DC87F0000C991C472A2000000A894A48CA7B501079BA2C9C69BA20000B19A5D3FA89000005CA6009DA2960901B0A7F0669FB200009D009E00B7890000DAD0F5D092820000D294D4C48BD10000B5A7A4A3B1A50402CAB6CBA6A2000000B5A7A4A3B1A8044FCDADD19D9CB00000B7778F7B8AAE0803C9AB5D3F5D3F00009EA09EA0BAB006039EA0989A8C7900009B9EF4D6B7C00000A9A7816CACA80000ABAC84705D3F000096DA635CDC8C00006F486F266F263D4784006124097B00374F6D2D6D2D6D4A3A95872322000000030000000000008D8939130000000000002E22A5C9CBC70600AB25C0B5C9B400061A2DB04CA67001082AA6BEBEBFC606002321DACBC19E03087AA08B6768380000282FBAC0B8CA7A88AD25BBA5A29900004C396C5894A6000040485A6E356E9442A32CD17EADA70000B4237923628600003E2DE9C1D7B500002F25BBA5A2990000231DB6AFB4A804023025C0B5CAB588062B2CBDBEC0C706882435A75CA20000002326BD6A82A908048B4B9A5A668000002423A09CB4BB060025259C9D8A7900001C1FCAB2C7C700002A2A9387ABA200002626A4A47D6E9D14333163A0C87500004B6F9C2D643A257049364936493647358A34438355497F1A0000A24C1D590000D38DFFBDD4CD3126');
})
};
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[337/*vs/editor/browser/viewParts/minimap/minimapCharRendererFactory*/], __M([0/*require*/,1/*exports*/,335/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/,186/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,336/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/]), function (require, exports, minimapCharRenderer_1, minimapCharSheet_1, minimapPreBaked_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Creates character renderers. It takes a 'scale' that determines how large
* characters should be drawn. Using this, it draws data into a canvas and
* then downsamples the characters as necessary for the current display.
* This makes rendering more efficient, rather than drawing a full (tiny)
* font, or downsampling in real-time.
*/
var MinimapCharRendererFactory = /** @class */ (function () {
function MinimapCharRendererFactory() {
}
/**
* Creates a new character renderer factory with the given scale.
*/
MinimapCharRendererFactory.create = function (scale, fontFamily) {
// renderers are immutable. By default we'll 'create' a new minimap
// character renderer whenever we switch editors, no need to do extra work.
if (this.lastCreated && scale === this.lastCreated.scale && fontFamily === this.lastFontFamily) {
return this.lastCreated;
}
var factory;
if (minimapPreBaked_1.prebakedMiniMaps[scale]) {
factory = new minimapCharRenderer_1.MinimapCharRenderer(minimapPreBaked_1.prebakedMiniMaps[scale](), scale);
}
else {
factory = MinimapCharRendererFactory.createFromSampleData(MinimapCharRendererFactory.createSampleData(fontFamily).data, scale);
}
this.lastFontFamily = fontFamily;
this.lastCreated = factory;
return factory;
};
/**
* Creates the font sample data, writing to a canvas.
*/
MinimapCharRendererFactory.createSampleData = function (fontFamily) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.style.height = 16 /* SAMPLED_CHAR_HEIGHT */ + "px";
canvas.height = 16 /* SAMPLED_CHAR_HEIGHT */;
canvas.width = 96 /* CHAR_COUNT */ * 10 /* SAMPLED_CHAR_WIDTH */;
canvas.style.width = 96 /* CHAR_COUNT */ * 10 /* SAMPLED_CHAR_WIDTH */ + 'px';
ctx.fillStyle = '#ffffff';
ctx.font = "bold " + 16 /* SAMPLED_CHAR_HEIGHT */ + "px " + fontFamily;
ctx.textBaseline = 'middle';
var x = 0;
for (var _i = 0, allCharCodes_1 = minimapCharSheet_1.allCharCodes; _i < allCharCodes_1.length; _i++) {
var code = allCharCodes_1[_i];
ctx.fillText(String.fromCharCode(code), x, 16 /* SAMPLED_CHAR_HEIGHT */ / 2);
x += 10 /* SAMPLED_CHAR_WIDTH */;
}
return ctx.getImageData(0, 0, 96 /* CHAR_COUNT */ * 10 /* SAMPLED_CHAR_WIDTH */, 16 /* SAMPLED_CHAR_HEIGHT */);
};
/**
* Creates a character renderer from the canvas sample data.
*/
MinimapCharRendererFactory.createFromSampleData = function (source, scale) {
var expectedLength = 16 /* SAMPLED_CHAR_HEIGHT */ * 10 /* SAMPLED_CHAR_WIDTH */ * 4 /* RGBA_CHANNELS_CNT */ * 96 /* CHAR_COUNT */;
if (source.length !== expectedLength) {
throw new Error('Unexpected source in MinimapCharRenderer');
}
var charData = MinimapCharRendererFactory._downsample(source, scale);
return new minimapCharRenderer_1.MinimapCharRenderer(charData, scale);
};
MinimapCharRendererFactory._downsampleChar = function (source, sourceOffset, dest, destOffset, scale) {
var width = 1 /* BASE_CHAR_WIDTH */ * scale;
var height = 2 /* BASE_CHAR_HEIGHT */ * scale;
var targetIndex = destOffset;
var brightest = 0;
// This is essentially an ad-hoc rescaling algorithm. Standard approaches
// like bicubic interpolation are awesome for scaling between image sizes,
// but don't work so well when scaling to very small pixel values, we end
// up with blurry, indistinct forms.
//
// The approach taken here is simply mapping each source pixel to the target
// pixels, and taking the weighted values for all pixels in each, and then
// averaging them out. Finally we apply an intensity boost in _downsample,
// since when scaling to the smallest pixel sizes there's more black space
// which causes characters to be much less distinct.
for (var y = 0; y < height; y++) {
// 1. For this destination pixel, get the source pixels we're sampling
// from (x1, y1) to the next pixel (x2, y2)
var sourceY1 = (y / height) * 16 /* SAMPLED_CHAR_HEIGHT */;
var sourceY2 = ((y + 1) / height) * 16 /* SAMPLED_CHAR_HEIGHT */;
for (var x = 0; x < width; x++) {
var sourceX1 = (x / width) * 10 /* SAMPLED_CHAR_WIDTH */;
var sourceX2 = ((x + 1) / width) * 10 /* SAMPLED_CHAR_WIDTH */;
// 2. Sample all of them, summing them up and weighting them. Similar
// to bilinear interpolation.
var value = 0;
var samples = 0;
for (var sy = sourceY1; sy < sourceY2; sy++) {
var sourceRow = sourceOffset + Math.floor(sy) * 3840 /* RGBA_SAMPLED_ROW_WIDTH */;
var yBalance = 1 - (sy - Math.floor(sy));
for (var sx = sourceX1; sx < sourceX2; sx++) {
var xBalance = 1 - (sx - Math.floor(sx));
var sourceIndex = sourceRow + Math.floor(sx) * 4 /* RGBA_CHANNELS_CNT */;
var weight = xBalance * yBalance;
samples += weight;
value += ((source[sourceIndex] * source[sourceIndex + 3]) / 255) * weight;
}
}
var final = value / samples;
brightest = Math.max(brightest, final);
dest[targetIndex++] = final;
}
}
return brightest;
};
MinimapCharRendererFactory._downsample = function (data, scale) {
var pixelsPerCharacter = 2 /* BASE_CHAR_HEIGHT */ * scale * 1 /* BASE_CHAR_WIDTH */ * scale;
var resultLen = pixelsPerCharacter * 96 /* CHAR_COUNT */;
var result = new Uint8ClampedArray(resultLen);
var resultOffset = 0;
var sourceOffset = 0;
var brightest = 0;
for (var charIndex = 0; charIndex < 96 /* CHAR_COUNT */; charIndex++) {
brightest = Math.max(brightest, this._downsampleChar(data, sourceOffset, result, resultOffset, scale));
resultOffset += pixelsPerCharacter;
sourceOffset += 10 /* SAMPLED_CHAR_WIDTH */ * 4 /* RGBA_CHANNELS_CNT */;
}
if (brightest > 0) {
var adjust = 255 / brightest;
for (var i = 0; i < resultLen; i++) {
result[i] *= adjust;
}
}
return result;
};
return MinimapCharRendererFactory;
}());
exports.MinimapCharRendererFactory = MinimapCharRendererFactory;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[105/*vs/editor/common/config/editorZoom*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/]), function (require, exports, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditorZoom = new /** @class */ (function () {
function class_1() {
this._zoomLevel = 0;
this._onDidChangeZoomLevel = new event_1.Emitter();
this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
}
class_1.prototype.getZoomLevel = function () {
return this._zoomLevel;
};
class_1.prototype.setZoomLevel = function (zoomLevel) {
zoomLevel = Math.min(Math.max(-5, zoomLevel), 20);
if (this._zoomLevel === zoomLevel) {
return;
}
this._zoomLevel = zoomLevel;
this._onDidChangeZoomLevel.fire(this._zoomLevel);
};
return class_1;
}());
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[142/*vs/editor/common/config/fontInfo*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,105/*vs/editor/common/config/editorZoom*/]), function (require, exports, platform, editorZoom_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Determined from empirical observations.
* @internal
*/
var GOLDEN_LINE_HEIGHT_RATIO = platform.isMacintosh ? 1.5 : 1.35;
/**
* @internal
*/
var MINIMUM_LINE_HEIGHT = 8;
var BareFontInfo = /** @class */ (function () {
/**
* @internal
*/
function BareFontInfo(opts) {
this.zoomLevel = opts.zoomLevel;
this.fontFamily = String(opts.fontFamily);
this.fontWeight = String(opts.fontWeight);
this.fontSize = opts.fontSize;
this.fontFeatureSettings = opts.fontFeatureSettings;
this.lineHeight = opts.lineHeight | 0;
this.letterSpacing = opts.letterSpacing;
}
/**
* @internal
*/
BareFontInfo.createFromValidatedSettings = function (options, zoomLevel, ignoreEditorZoom) {
var fontFamily = options.get(33 /* fontFamily */);
var fontWeight = options.get(37 /* fontWeight */);
var fontSize = options.get(36 /* fontSize */);
var fontFeatureSettings = options.get(35 /* fontLigatures */);
var lineHeight = options.get(49 /* lineHeight */);
var letterSpacing = options.get(46 /* letterSpacing */);
return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, ignoreEditorZoom);
};
/**
* @internal
*/
BareFontInfo._create = function (fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, zoomLevel, ignoreEditorZoom) {
if (lineHeight === 0) {
lineHeight = Math.round(GOLDEN_LINE_HEIGHT_RATIO * fontSize);
}
else if (lineHeight < MINIMUM_LINE_HEIGHT) {
lineHeight = MINIMUM_LINE_HEIGHT;
}
var editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : editorZoom_1.EditorZoom.getZoomLevel() * 0.1);
fontSize *= editorZoomLevelMultiplier;
lineHeight *= editorZoomLevelMultiplier;
return new BareFontInfo({
zoomLevel: zoomLevel,
fontFamily: fontFamily,
fontWeight: fontWeight,
fontSize: fontSize,
fontFeatureSettings: fontFeatureSettings,
lineHeight: lineHeight,
letterSpacing: letterSpacing
});
};
/**
* @internal
*/
BareFontInfo.prototype.getId = function () {
return this.zoomLevel + '-' + this.fontFamily + '-' + this.fontWeight + '-' + this.fontSize + '-' + this.fontFeatureSettings + '-' + this.lineHeight + '-' + this.letterSpacing;
};
/**
* @internal
*/
BareFontInfo.prototype.getMassagedFontFamily = function () {
if (/[,"']/.test(this.fontFamily)) {
// Looks like the font family might be already escaped
return this.fontFamily;
}
if (/[+ ]/.test(this.fontFamily)) {
// Wrap a font family using + or with quotes
return "\"" + this.fontFamily + "\"";
}
return this.fontFamily;
};
return BareFontInfo;
}());
exports.BareFontInfo = BareFontInfo;
var FontInfo = /** @class */ (function (_super) {
__extends(FontInfo, _super);
/**
* @internal
*/
function FontInfo(opts, isTrusted) {
var _this = _super.call(this, opts) || this;
_this.isTrusted = isTrusted;
_this.isMonospace = opts.isMonospace;
_this.typicalHalfwidthCharacterWidth = opts.typicalHalfwidthCharacterWidth;
_this.typicalFullwidthCharacterWidth = opts.typicalFullwidthCharacterWidth;
_this.canUseHalfwidthRightwardsArrow = opts.canUseHalfwidthRightwardsArrow;
_this.spaceWidth = opts.spaceWidth;
_this.middotWidth = opts.middotWidth;
_this.maxDigitWidth = opts.maxDigitWidth;
return _this;
}
/**
* @internal
*/
FontInfo.prototype.equals = function (other) {
return (this.fontFamily === other.fontFamily
&& this.fontWeight === other.fontWeight
&& this.fontSize === other.fontSize
&& this.fontFeatureSettings === other.fontFeatureSettings
&& this.lineHeight === other.lineHeight
&& this.letterSpacing === other.letterSpacing
&& this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth
&& this.typicalFullwidthCharacterWidth === other.typicalFullwidthCharacterWidth
&& this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow
&& this.spaceWidth === other.spaceWidth
&& this.middotWidth === other.middotWidth
&& this.maxDigitWidth === other.maxDigitWidth);
};
return FontInfo;
}(BareFontInfo));
exports.FontInfo = FontInfo;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[79/*vs/editor/common/core/characterClassifier*/], __M([0/*require*/,1/*exports*/,179/*vs/base/common/uint*/]), function (require, exports, uint_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A fast character classifier that uses a compact array for ASCII values.
*/
var CharacterClassifier = /** @class */ (function () {
function CharacterClassifier(_defaultValue) {
var defaultValue = uint_1.toUint8(_defaultValue);
this._defaultValue = defaultValue;
this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue);
this._map = new Map();
}
CharacterClassifier._createAsciiMap = function (defaultValue) {
var asciiMap = new Uint8Array(256);
for (var i = 0; i < 256; i++) {
asciiMap[i] = defaultValue;
}
return asciiMap;
};
CharacterClassifier.prototype.set = function (charCode, _value) {
var value = uint_1.toUint8(_value);
if (charCode >= 0 && charCode < 256) {
this._asciiMap[charCode] = value;
}
else {
this._map.set(charCode, value);
}
};
CharacterClassifier.prototype.get = function (charCode) {
if (charCode >= 0 && charCode < 256) {
return this._asciiMap[charCode];
}
else {
return (this._map.get(charCode) || this._defaultValue);
}
};
return CharacterClassifier;
}());
exports.CharacterClassifier = CharacterClassifier;
var CharacterSet = /** @class */ (function () {
function CharacterSet() {
this._actual = new CharacterClassifier(0 /* False */);
}
CharacterSet.prototype.add = function (charCode) {
this._actual.set(charCode, 1 /* True */);
};
CharacterSet.prototype.has = function (charCode) {
return (this._actual.get(charCode) === 1 /* True */);
};
return CharacterSet;
}());
exports.CharacterSet = CharacterSet;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[89/*vs/editor/common/controller/wordCharacterClassifier*/], __M([0/*require*/,1/*exports*/,79/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var WordCharacterClassifier = /** @class */ (function (_super) {
__extends(WordCharacterClassifier, _super);
function WordCharacterClassifier(wordSeparators) {
var _this = _super.call(this, 0 /* Regular */) || this;
for (var i = 0, len = wordSeparators.length; i < len; i++) {
_this.set(wordSeparators.charCodeAt(i), 2 /* WordSeparator */);
}
_this.set(32 /* Space */, 1 /* Whitespace */);
_this.set(9 /* Tab */, 1 /* Whitespace */);
return _this;
}
return WordCharacterClassifier;
}(characterClassifier_1.CharacterClassifier));
exports.WordCharacterClassifier = WordCharacterClassifier;
function once(computeFn) {
var cache = {}; // TODO@Alex unbounded cache
return function (input) {
if (!cache.hasOwnProperty(input)) {
cache[input] = computeFn(input);
}
return cache[input];
};
}
exports.getMapForWordSeparators = once(function (input) { return new WordCharacterClassifier(input); });
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[13/*vs/editor/common/core/position*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A position in the editor.
*/
var Position = /** @class */ (function () {
function Position(lineNumber, column) {
this.lineNumber = lineNumber;
this.column = column;
}
/**
* Create a new position from this position.
*
* @param newLineNumber new line number
* @param newColumn new column
*/
Position.prototype.with = function (newLineNumber, newColumn) {
if (newLineNumber === void 0) { newLineNumber = this.lineNumber; }
if (newColumn === void 0) { newColumn = this.column; }
if (newLineNumber === this.lineNumber && newColumn === this.column) {
return this;
}
else {
return new Position(newLineNumber, newColumn);
}
};
/**
* Derive a new position from this position.
*
* @param deltaLineNumber line number delta
* @param deltaColumn column delta
*/
Position.prototype.delta = function (deltaLineNumber, deltaColumn) {
if (deltaLineNumber === void 0) { deltaLineNumber = 0; }
if (deltaColumn === void 0) { deltaColumn = 0; }
return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
};
/**
* Test if this position equals other position
*/
Position.prototype.equals = function (other) {
return Position.equals(this, other);
};
/**
* Test if position `a` equals position `b`
*/
Position.equals = function (a, b) {
if (!a && !b) {
return true;
}
return (!!a &&
!!b &&
a.lineNumber === b.lineNumber &&
a.column === b.column);
};
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be false.
*/
Position.prototype.isBefore = function (other) {
return Position.isBefore(this, other);
};
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be false.
*/
Position.isBefore = function (a, b) {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column < b.column;
};
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be true.
*/
Position.prototype.isBeforeOrEqual = function (other) {
return Position.isBeforeOrEqual(this, other);
};
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be true.
*/
Position.isBeforeOrEqual = function (a, b) {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column <= b.column;
};
/**
* A function that compares positions, useful for sorting
*/
Position.compare = function (a, b) {
var aLineNumber = a.lineNumber | 0;
var bLineNumber = b.lineNumber | 0;
if (aLineNumber === bLineNumber) {
var aColumn = a.column | 0;
var bColumn = b.column | 0;
return aColumn - bColumn;
}
return aLineNumber - bLineNumber;
};
/**
* Clone this position.
*/
Position.prototype.clone = function () {
return new Position(this.lineNumber, this.column);
};
/**
* Convert to a human-readable representation.
*/
Position.prototype.toString = function () {
return '(' + this.lineNumber + ',' + this.column + ')';
};
// ---
/**
* Create a `Position` from an `IPosition`.
*/
Position.lift = function (pos) {
return new Position(pos.lineNumber, pos.column);
};
/**
* Test if `obj` is an `IPosition`.
*/
Position.isIPosition = function (obj) {
return (obj
&& (typeof obj.lineNumber === 'number')
&& (typeof obj.column === 'number'));
};
return Position;
}());
exports.Position = Position;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[3/*vs/editor/common/core/range*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/]), function (require, exports, position_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A range in the editor. (startLineNumber,startColumn) is <= (endLineNumber,endColumn)
*/
var Range = /** @class */ (function () {
function Range(startLineNumber, startColumn, endLineNumber, endColumn) {
if ((startLineNumber > endLineNumber) || (startLineNumber === endLineNumber && startColumn > endColumn)) {
this.startLineNumber = endLineNumber;
this.startColumn = endColumn;
this.endLineNumber = startLineNumber;
this.endColumn = startColumn;
}
else {
this.startLineNumber = startLineNumber;
this.startColumn = startColumn;
this.endLineNumber = endLineNumber;
this.endColumn = endColumn;
}
}
/**
* Test if this range is empty.
*/
Range.prototype.isEmpty = function () {
return Range.isEmpty(this);
};
/**
* Test if `range` is empty.
*/
Range.isEmpty = function (range) {
return (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn);
};
/**
* Test if position is in this range. If the position is at the edges, will return true.
*/
Range.prototype.containsPosition = function (position) {
return Range.containsPosition(this, position);
};
/**
* Test if `position` is in `range`. If the position is at the edges, will return true.
*/
Range.containsPosition = function (range, position) {
if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
return false;
}
if (position.lineNumber === range.startLineNumber && position.column < range.startColumn) {
return false;
}
if (position.lineNumber === range.endLineNumber && position.column > range.endColumn) {
return false;
}
return true;
};
/**
* Test if range is in this range. If the range is equal to this range, will return true.
*/
Range.prototype.containsRange = function (range) {
return Range.containsRange(this, range);
};
/**
* Test if `otherRange` is in `range`. If the ranges are equal, will return true.
*/
Range.containsRange = function (range, otherRange) {
if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
return false;
}
if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
return false;
}
if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn < range.startColumn) {
return false;
}
if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn > range.endColumn) {
return false;
}
return true;
};
/**
* Test if `range` is strictly in this range. `range` must start after and end before this range for the result to be true.
*/
Range.prototype.strictContainsRange = function (range) {
return Range.strictContainsRange(this, range);
};
/**
* Test if `otherRange` is strinctly in `range` (must start after, and end before). If the ranges are equal, will return false.
*/
Range.strictContainsRange = function (range, otherRange) {
if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
return false;
}
if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
return false;
}
if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn <= range.startColumn) {
return false;
}
if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn >= range.endColumn) {
return false;
}
return true;
};
/**
* A reunion of the two ranges.
* The smallest position will be used as the start point, and the largest one as the end point.
*/
Range.prototype.plusRange = function (range) {
return Range.plusRange(this, range);
};
/**
* A reunion of the two ranges.
* The smallest position will be used as the start point, and the largest one as the end point.
*/
Range.plusRange = function (a, b) {
var startLineNumber;
var startColumn;
var endLineNumber;
var endColumn;
if (b.startLineNumber < a.startLineNumber) {
startLineNumber = b.startLineNumber;
startColumn = b.startColumn;
}
else if (b.startLineNumber === a.startLineNumber) {
startLineNumber = b.startLineNumber;
startColumn = Math.min(b.startColumn, a.startColumn);
}
else {
startLineNumber = a.startLineNumber;
startColumn = a.startColumn;
}
if (b.endLineNumber > a.endLineNumber) {
endLineNumber = b.endLineNumber;
endColumn = b.endColumn;
}
else if (b.endLineNumber === a.endLineNumber) {
endLineNumber = b.endLineNumber;
endColumn = Math.max(b.endColumn, a.endColumn);
}
else {
endLineNumber = a.endLineNumber;
endColumn = a.endColumn;
}
return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
};
/**
* A intersection of the two ranges.
*/
Range.prototype.intersectRanges = function (range) {
return Range.intersectRanges(this, range);
};
/**
* A intersection of the two ranges.
*/
Range.intersectRanges = function (a, b) {
var resultStartLineNumber = a.startLineNumber;
var resultStartColumn = a.startColumn;
var resultEndLineNumber = a.endLineNumber;
var resultEndColumn = a.endColumn;
var otherStartLineNumber = b.startLineNumber;
var otherStartColumn = b.startColumn;
var otherEndLineNumber = b.endLineNumber;
var otherEndColumn = b.endColumn;
if (resultStartLineNumber < otherStartLineNumber) {
resultStartLineNumber = otherStartLineNumber;
resultStartColumn = otherStartColumn;
}
else if (resultStartLineNumber === otherStartLineNumber) {
resultStartColumn = Math.max(resultStartColumn, otherStartColumn);
}
if (resultEndLineNumber > otherEndLineNumber) {
resultEndLineNumber = otherEndLineNumber;
resultEndColumn = otherEndColumn;
}
else if (resultEndLineNumber === otherEndLineNumber) {
resultEndColumn = Math.min(resultEndColumn, otherEndColumn);
}
// Check if selection is now empty
if (resultStartLineNumber > resultEndLineNumber) {
return null;
}
if (resultStartLineNumber === resultEndLineNumber && resultStartColumn > resultEndColumn) {
return null;
}
return new Range(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn);
};
/**
* Test if this range equals other.
*/
Range.prototype.equalsRange = function (other) {
return Range.equalsRange(this, other);
};
/**
* Test if range `a` equals `b`.
*/
Range.equalsRange = function (a, b) {
return (!!a &&
!!b &&
a.startLineNumber === b.startLineNumber &&
a.startColumn === b.startColumn &&
a.endLineNumber === b.endLineNumber &&
a.endColumn === b.endColumn);
};
/**
* Return the end position (which will be after or equal to the start position)
*/
Range.prototype.getEndPosition = function () {
return new position_1.Position(this.endLineNumber, this.endColumn);
};
/**
* Return the start position (which will be before or equal to the end position)
*/
Range.prototype.getStartPosition = function () {
return new position_1.Position(this.startLineNumber, this.startColumn);
};
/**
* Transform to a user presentable string representation.
*/
Range.prototype.toString = function () {
return '[' + this.startLineNumber + ',' + this.startColumn + ' -> ' + this.endLineNumber + ',' + this.endColumn + ']';
};
/**
* Create a new range using this range's start position, and using endLineNumber and endColumn as the end position.
*/
Range.prototype.setEndPosition = function (endLineNumber, endColumn) {
return new Range(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
};
/**
* Create a new range using this range's end position, and using startLineNumber and startColumn as the start position.
*/
Range.prototype.setStartPosition = function (startLineNumber, startColumn) {
return new Range(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
};
/**
* Create a new empty range using this range's start position.
*/
Range.prototype.collapseToStart = function () {
return Range.collapseToStart(this);
};
/**
* Create a new empty range using this range's start position.
*/
Range.collapseToStart = function (range) {
return new Range(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn);
};
// ---
Range.fromPositions = function (start, end) {
if (end === void 0) { end = start; }
return new Range(start.lineNumber, start.column, end.lineNumber, end.column);
};
Range.lift = function (range) {
if (!range) {
return null;
}
return new Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
};
/**
* Test if `obj` is an `IRange`.
*/
Range.isIRange = function (obj) {
return (obj
&& (typeof obj.startLineNumber === 'number')
&& (typeof obj.startColumn === 'number')
&& (typeof obj.endLineNumber === 'number')
&& (typeof obj.endColumn === 'number'));
};
/**
* Test if the two ranges are touching in any way.
*/
Range.areIntersectingOrTouching = function (a, b) {
// Check if `a` is before `b`
if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn)) {
return false;
}
// Check if `b` is before `a`
if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn)) {
return false;
}
// These ranges must intersect
return true;
};
/**
* Test if the two ranges are intersecting. If the ranges are touching it returns true.
*/
Range.areIntersecting = function (a, b) {
// Check if `a` is before `b`
if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn <= b.startColumn)) {
return false;
}
// Check if `b` is before `a`
if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn <= a.startColumn)) {
return false;
}
// These ranges must intersect
return true;
};
/**
* A function that compares ranges, useful for sorting ranges
* It will first compare ranges on the startPosition and then on the endPosition
*/
Range.compareRangesUsingStarts = function (a, b) {
if (a && b) {
var aStartLineNumber = a.startLineNumber | 0;
var bStartLineNumber = b.startLineNumber | 0;
if (aStartLineNumber === bStartLineNumber) {
var aStartColumn = a.startColumn | 0;
var bStartColumn = b.startColumn | 0;
if (aStartColumn === bStartColumn) {
var aEndLineNumber = a.endLineNumber | 0;
var bEndLineNumber = b.endLineNumber | 0;
if (aEndLineNumber === bEndLineNumber) {
var aEndColumn = a.endColumn | 0;
var bEndColumn = b.endColumn | 0;
return aEndColumn - bEndColumn;
}
return aEndLineNumber - bEndLineNumber;
}
return aStartColumn - bStartColumn;
}
return aStartLineNumber - bStartLineNumber;
}
var aExists = (a ? 1 : 0);
var bExists = (b ? 1 : 0);
return aExists - bExists;
};
/**
* A function that compares ranges, useful for sorting ranges
* It will first compare ranges on the endPosition and then on the startPosition
*/
Range.compareRangesUsingEnds = function (a, b) {
if (a.endLineNumber === b.endLineNumber) {
if (a.endColumn === b.endColumn) {
if (a.startLineNumber === b.startLineNumber) {
return a.startColumn - b.startColumn;
}
return a.startLineNumber - b.startLineNumber;
}
return a.endColumn - b.endColumn;
}
return a.endLineNumber - b.endLineNumber;
};
/**
* Test if the range spans multiple lines.
*/
Range.spansMultipleLines = function (range) {
return range.endLineNumber > range.startLineNumber;
};
return Range;
}());
exports.Range = Range;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[187/*vs/editor/browser/controller/textAreaState*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, position_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TextAreaState = /** @class */ (function () {
function TextAreaState(value, selectionStart, selectionEnd, selectionStartPosition, selectionEndPosition) {
this.value = value;
this.selectionStart = selectionStart;
this.selectionEnd = selectionEnd;
this.selectionStartPosition = selectionStartPosition;
this.selectionEndPosition = selectionEndPosition;
}
TextAreaState.prototype.toString = function () {
return '[ <' + this.value + '>, selectionStart: ' + this.selectionStart + ', selectionEnd: ' + this.selectionEnd + ']';
};
TextAreaState.readFromTextArea = function (textArea) {
return new TextAreaState(textArea.getValue(), textArea.getSelectionStart(), textArea.getSelectionEnd(), null, null);
};
TextAreaState.prototype.collapseSelection = function () {
return new TextAreaState(this.value, this.value.length, this.value.length, null, null);
};
TextAreaState.prototype.writeToTextArea = function (reason, textArea, select) {
// console.log(Date.now() + ': writeToTextArea ' + reason + ': ' + this.toString());
textArea.setValue(reason, this.value);
if (select) {
textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd);
}
};
TextAreaState.prototype.deduceEditorPosition = function (offset) {
if (offset <= this.selectionStart) {
var str = this.value.substring(offset, this.selectionStart);
return this._finishDeduceEditorPosition(this.selectionStartPosition, str, -1);
}
if (offset >= this.selectionEnd) {
var str = this.value.substring(this.selectionEnd, offset);
return this._finishDeduceEditorPosition(this.selectionEndPosition, str, 1);
}
var str1 = this.value.substring(this.selectionStart, offset);
if (str1.indexOf(String.fromCharCode(8230)) === -1) {
return this._finishDeduceEditorPosition(this.selectionStartPosition, str1, 1);
}
var str2 = this.value.substring(offset, this.selectionEnd);
return this._finishDeduceEditorPosition(this.selectionEndPosition, str2, -1);
};
TextAreaState.prototype._finishDeduceEditorPosition = function (anchor, deltaText, signum) {
var lineFeedCnt = 0;
var lastLineFeedIndex = -1;
while ((lastLineFeedIndex = deltaText.indexOf('\n', lastLineFeedIndex + 1)) !== -1) {
lineFeedCnt++;
}
return [anchor, signum * deltaText.length, lineFeedCnt];
};
TextAreaState.selectedText = function (text) {
return new TextAreaState(text, 0, text.length, null, null);
};
TextAreaState.deduceInput = function (previousState, currentState, couldBeEmojiInput) {
if (!previousState) {
// This is the EMPTY state
return {
text: '',
replaceCharCnt: 0
};
}
// console.log('------------------------deduceInput');
// console.log('PREVIOUS STATE: ' + previousState.toString());
// console.log('CURRENT STATE: ' + currentState.toString());
var previousValue = previousState.value;
var previousSelectionStart = previousState.selectionStart;
var previousSelectionEnd = previousState.selectionEnd;
var currentValue = currentState.value;
var currentSelectionStart = currentState.selectionStart;
var currentSelectionEnd = currentState.selectionEnd;
// Strip the previous suffix from the value (without interfering with the current selection)
var previousSuffix = previousValue.substring(previousSelectionEnd);
var currentSuffix = currentValue.substring(currentSelectionEnd);
var suffixLength = strings.commonSuffixLength(previousSuffix, currentSuffix);
currentValue = currentValue.substring(0, currentValue.length - suffixLength);
previousValue = previousValue.substring(0, previousValue.length - suffixLength);
var previousPrefix = previousValue.substring(0, previousSelectionStart);
var currentPrefix = currentValue.substring(0, currentSelectionStart);
var prefixLength = strings.commonPrefixLength(previousPrefix, currentPrefix);
currentValue = currentValue.substring(prefixLength);
previousValue = previousValue.substring(prefixLength);
currentSelectionStart -= prefixLength;
previousSelectionStart -= prefixLength;
currentSelectionEnd -= prefixLength;
previousSelectionEnd -= prefixLength;
// console.log('AFTER DIFFING PREVIOUS STATE: <' + previousValue + '>, selectionStart: ' + previousSelectionStart + ', selectionEnd: ' + previousSelectionEnd);
// console.log('AFTER DIFFING CURRENT STATE: <' + currentValue + '>, selectionStart: ' + currentSelectionStart + ', selectionEnd: ' + currentSelectionEnd);
if (couldBeEmojiInput && currentSelectionStart === currentSelectionEnd && previousValue.length > 0) {
// on OSX, emojis from the emoji picker are inserted at random locations
// the only hints we can use is that the selection is immediately after the inserted emoji
// and that none of the old text has been deleted
var potentialEmojiInput = null;
if (currentSelectionStart === currentValue.length) {
// emoji potentially inserted "somewhere" after the previous selection => it should appear at the end of `currentValue`
if (strings.startsWith(currentValue, previousValue)) {
// only if all of the old text is accounted for
potentialEmojiInput = currentValue.substring(previousValue.length);
}
}
else {
// emoji potentially inserted "somewhere" before the previous selection => it should appear at the start of `currentValue`
if (strings.endsWith(currentValue, previousValue)) {
// only if all of the old text is accounted for
potentialEmojiInput = currentValue.substring(0, currentValue.length - previousValue.length);
}
}
if (potentialEmojiInput !== null && potentialEmojiInput.length > 0) {
// now we check that this is indeed an emoji
// emojis can grow quite long, so a length check is of no help
// e.g. 1F3F4 E0067 E0062 E0065 E006E E0067 E007F ; fully-qualified # 🏴 England
// Oftentimes, emojis use Variation Selector-16 (U+FE0F), so that is a good hint
// http://emojipedia.org/variation-selector-16/
// > An invisible codepoint which specifies that the preceding character
// > should be displayed with emoji presentation. Only required if the
// > preceding character defaults to text presentation.
if (/\uFE0F/.test(potentialEmojiInput) || strings.containsEmoji(potentialEmojiInput)) {
return {
text: potentialEmojiInput,
replaceCharCnt: 0
};
}
}
}
if (currentSelectionStart === currentSelectionEnd) {
// composition accept case (noticed in FF + Japanese)
// [blahblah] => blahblah|
if (previousValue === currentValue
&& previousSelectionStart === 0
&& previousSelectionEnd === previousValue.length
&& currentSelectionStart === currentValue.length
&& currentValue.indexOf('\n') === -1) {
if (strings.containsFullWidthCharacter(currentValue)) {
return {
text: '',
replaceCharCnt: 0
};
}
}
// no current selection
var replacePreviousCharacters_1 = (previousPrefix.length - prefixLength);
// console.log('REMOVE PREVIOUS: ' + (previousPrefix.length - prefixLength) + ' chars');
return {
text: currentValue,
replaceCharCnt: replacePreviousCharacters_1
};
}
// there is a current selection => composition case
var replacePreviousCharacters = previousSelectionEnd - previousSelectionStart;
return {
text: currentValue,
replaceCharCnt: replacePreviousCharacters
};
};
TextAreaState.EMPTY = new TextAreaState('', 0, 0, null, null);
return TextAreaState;
}());
exports.TextAreaState = TextAreaState;
var PagedScreenReaderStrategy = /** @class */ (function () {
function PagedScreenReaderStrategy() {
}
PagedScreenReaderStrategy._getPageOfLine = function (lineNumber, linesPerPage) {
return Math.floor((lineNumber - 1) / linesPerPage);
};
PagedScreenReaderStrategy._getRangeForPage = function (page, linesPerPage) {
var offset = page * linesPerPage;
var startLineNumber = offset + 1;
var endLineNumber = offset + linesPerPage;
return new range_1.Range(startLineNumber, 1, endLineNumber + 1, 1);
};
PagedScreenReaderStrategy.fromEditorSelection = function (previousState, model, selection, linesPerPage, trimLongText) {
var selectionStartPage = PagedScreenReaderStrategy._getPageOfLine(selection.startLineNumber, linesPerPage);
var selectionStartPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionStartPage, linesPerPage);
var selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection.endLineNumber, linesPerPage);
var selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage, linesPerPage);
var pretextRange = selectionStartPageRange.intersectRanges(new range_1.Range(1, 1, selection.startLineNumber, selection.startColumn));
var pretext = model.getValueInRange(pretextRange, 1 /* LF */);
var lastLine = model.getLineCount();
var lastLineMaxColumn = model.getLineMaxColumn(lastLine);
var posttextRange = selectionEndPageRange.intersectRanges(new range_1.Range(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn));
var posttext = model.getValueInRange(posttextRange, 1 /* LF */);
var text;
if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
// take full selection
text = model.getValueInRange(selection, 1 /* LF */);
}
else {
var selectionRange1 = selectionStartPageRange.intersectRanges(selection);
var selectionRange2 = selectionEndPageRange.intersectRanges(selection);
text = (model.getValueInRange(selectionRange1, 1 /* LF */)
+ String.fromCharCode(8230)
+ model.getValueInRange(selectionRange2, 1 /* LF */));
}
// Chromium handles very poorly text even of a few thousand chars
// Cut text to avoid stalling the entire UI
if (trimLongText) {
var LIMIT_CHARS = 500;
if (pretext.length > LIMIT_CHARS) {
pretext = pretext.substring(pretext.length - LIMIT_CHARS, pretext.length);
}
if (posttext.length > LIMIT_CHARS) {
posttext = posttext.substring(0, LIMIT_CHARS);
}
if (text.length > 2 * LIMIT_CHARS) {
text = text.substring(0, LIMIT_CHARS) + String.fromCharCode(8230) + text.substring(text.length - LIMIT_CHARS, text.length);
}
}
return new TextAreaState(pretext + text + posttext, pretext.length, pretext.length + text.length, new position_1.Position(selection.startLineNumber, selection.startColumn), new position_1.Position(selection.endLineNumber, selection.endColumn));
};
return PagedScreenReaderStrategy;
}());
exports.PagedScreenReaderStrategy = PagedScreenReaderStrategy;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[188/*vs/editor/browser/widget/diffNavigator*/], __M([0/*require*/,1/*exports*/,124/*vs/base/common/assert*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,31/*vs/base/common/objects*/,3/*vs/editor/common/core/range*/]), function (require, exports, assert, event_1, lifecycle_1, objects, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var defaultOptions = {
followsCaret: true,
ignoreCharChanges: true,
alwaysRevealFirst: true
};
/**
* Create a new diff navigator for the provided diff editor.
*/
var DiffNavigator = /** @class */ (function (_super) {
__extends(DiffNavigator, _super);
function DiffNavigator(editor, options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this) || this;
_this._onDidUpdate = _this._register(new event_1.Emitter());
_this._editor = editor;
_this._options = objects.mixin(options, defaultOptions, false);
_this.disposed = false;
_this.nextIdx = -1;
_this.ranges = [];
_this.ignoreSelectionChange = false;
_this.revealFirst = Boolean(_this._options.alwaysRevealFirst);
// hook up to diff editor for diff, disposal, and caret move
_this._register(_this._editor.onDidDispose(function () { return _this.dispose(); }));
_this._register(_this._editor.onDidUpdateDiff(function () { return _this._onDiffUpdated(); }));
if (_this._options.followsCaret) {
_this._register(_this._editor.getModifiedEditor().onDidChangeCursorPosition(function (e) {
if (_this.ignoreSelectionChange) {
return;
}
_this.nextIdx = -1;
}));
}
if (_this._options.alwaysRevealFirst) {
_this._register(_this._editor.getModifiedEditor().onDidChangeModel(function (e) {
_this.revealFirst = true;
}));
}
// init things
_this._init();
return _this;
}
DiffNavigator.prototype._init = function () {
var changes = this._editor.getLineChanges();
if (!changes) {
return;
}
};
DiffNavigator.prototype._onDiffUpdated = function () {
this._init();
this._compute(this._editor.getLineChanges());
if (this.revealFirst) {
// Only reveal first on first non-null changes
if (this._editor.getLineChanges() !== null) {
this.revealFirst = false;
this.nextIdx = -1;
this.next(1 /* Immediate */);
}
}
};
DiffNavigator.prototype._compute = function (lineChanges) {
var _this = this;
// new ranges
this.ranges = [];
if (lineChanges) {
// create ranges from changes
lineChanges.forEach(function (lineChange) {
if (!_this._options.ignoreCharChanges && lineChange.charChanges) {
lineChange.charChanges.forEach(function (charChange) {
_this.ranges.push({
rhs: true,
range: new range_1.Range(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn)
});
});
}
else {
_this.ranges.push({
rhs: true,
range: new range_1.Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber, 1)
});
}
});
}
// sort
this.ranges.sort(function (left, right) {
if (left.range.getStartPosition().isBeforeOrEqual(right.range.getStartPosition())) {
return -1;
}
else if (right.range.getStartPosition().isBeforeOrEqual(left.range.getStartPosition())) {
return 1;
}
else {
return 0;
}
});
this._onDidUpdate.fire(this);
};
DiffNavigator.prototype._initIdx = function (fwd) {
var found = false;
var position = this._editor.getPosition();
if (!position) {
this.nextIdx = 0;
return;
}
for (var i = 0, len = this.ranges.length; i < len && !found; i++) {
var range = this.ranges[i].range;
if (position.isBeforeOrEqual(range.getStartPosition())) {
this.nextIdx = i + (fwd ? 0 : -1);
found = true;
}
}
if (!found) {
// after the last change
this.nextIdx = fwd ? 0 : this.ranges.length - 1;
}
if (this.nextIdx < 0) {
this.nextIdx = this.ranges.length - 1;
}
};
DiffNavigator.prototype._move = function (fwd, scrollType) {
assert.ok(!this.disposed, 'Illegal State - diff navigator has been disposed');
if (!this.canNavigate()) {
return;
}
if (this.nextIdx === -1) {
this._initIdx(fwd);
}
else if (fwd) {
this.nextIdx += 1;
if (this.nextIdx >= this.ranges.length) {
this.nextIdx = 0;
}
}
else {
this.nextIdx -= 1;
if (this.nextIdx < 0) {
this.nextIdx = this.ranges.length - 1;
}
}
var info = this.ranges[this.nextIdx];
this.ignoreSelectionChange = true;
try {
var pos = info.range.getStartPosition();
this._editor.setPosition(pos);
this._editor.revealPositionInCenter(pos, scrollType);
}
finally {
this.ignoreSelectionChange = false;
}
};
DiffNavigator.prototype.canNavigate = function () {
return this.ranges && this.ranges.length > 0;
};
DiffNavigator.prototype.next = function (scrollType) {
if (scrollType === void 0) { scrollType = 0 /* Smooth */; }
this._move(true, scrollType);
};
DiffNavigator.prototype.previous = function (scrollType) {
if (scrollType === void 0) { scrollType = 0 /* Smooth */; }
this._move(false, scrollType);
};
DiffNavigator.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.ranges = [];
this.disposed = true;
};
return DiffNavigator;
}(lifecycle_1.Disposable));
exports.DiffNavigator = DiffNavigator;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[58/*vs/editor/common/core/editOperation*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var EditOperation = /** @class */ (function () {
function EditOperation() {
}
EditOperation.insert = function (position, text) {
return {
range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column),
text: text,
forceMoveMarkers: true
};
};
EditOperation.delete = function (range) {
return {
range: range,
text: null
};
};
EditOperation.replace = function (range, text) {
return {
range: range,
text: text
};
};
EditOperation.replaceMove = function (range, text) {
return {
range: range,
text: text,
forceMoveMarkers: true
};
};
return EditOperation;
}());
exports.EditOperation = EditOperation;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[338/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,58/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, editOperation_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TrimTrailingWhitespaceCommand = /** @class */ (function () {
function TrimTrailingWhitespaceCommand(selection, cursors) {
this._selection = selection;
this._cursors = cursors;
this._selectionId = null;
}
TrimTrailingWhitespaceCommand.prototype.getEditOperations = function (model, builder) {
var ops = trimTrailingWhitespace(model, this._cursors);
for (var i = 0, len = ops.length; i < len; i++) {
var op = ops[i];
builder.addEditOperation(op.range, op.text);
}
this._selectionId = builder.trackSelection(this._selection);
};
TrimTrailingWhitespaceCommand.prototype.computeCursorState = function (model, helper) {
return helper.getTrackedSelection(this._selectionId);
};
return TrimTrailingWhitespaceCommand;
}());
exports.TrimTrailingWhitespaceCommand = TrimTrailingWhitespaceCommand;
/**
* Generate commands for trimming trailing whitespace on a model and ignore lines on which cursors are sitting.
*/
function trimTrailingWhitespace(model, cursors) {
// Sort cursors ascending
cursors.sort(function (a, b) {
if (a.lineNumber === b.lineNumber) {
return a.column - b.column;
}
return a.lineNumber - b.lineNumber;
});
// Reduce multiple cursors on the same line and only keep the last one on the line
for (var i = cursors.length - 2; i >= 0; i--) {
if (cursors[i].lineNumber === cursors[i + 1].lineNumber) {
// Remove cursor at `i`
cursors.splice(i, 1);
}
}
var r = [];
var rLen = 0;
var cursorIndex = 0;
var cursorLen = cursors.length;
for (var lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
var lineContent = model.getLineContent(lineNumber);
var maxLineColumn = lineContent.length + 1;
var minEditColumn = 0;
if (cursorIndex < cursorLen && cursors[cursorIndex].lineNumber === lineNumber) {
minEditColumn = cursors[cursorIndex].column;
cursorIndex++;
if (minEditColumn === maxLineColumn) {
// The cursor is at the end of the line => no edits for sure on this line
continue;
}
}
if (lineContent.length === 0) {
continue;
}
var lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent);
var fromColumn = 0;
if (lastNonWhitespaceIndex === -1) {
// Entire line is whitespace
fromColumn = 1;
}
else if (lastNonWhitespaceIndex !== lineContent.length - 1) {
// There is trailing whitespace
fromColumn = lastNonWhitespaceIndex + 2;
}
else {
// There is no trailing whitespace
continue;
}
fromColumn = Math.max(minEditColumn, fromColumn);
r[rLen++] = editOperation_1.EditOperation.delete(new range_1.Range(lineNumber, fromColumn, lineNumber, maxLineColumn));
}
return r;
}
exports.trimTrailingWhitespace = trimTrailingWhitespace;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[339/*vs/editor/common/core/rgba*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A very VM friendly rgba datastructure.
* Please don't touch unless you take a look at the IR.
*/
var RGBA8 = /** @class */ (function () {
function RGBA8(r, g, b, a) {
this.r = RGBA8._clamp(r);
this.g = RGBA8._clamp(g);
this.b = RGBA8._clamp(b);
this.a = RGBA8._clamp(a);
}
RGBA8._clamp = function (c) {
if (c < 0) {
return 0;
}
if (c > 255) {
return 255;
}
return c | 0;
};
RGBA8.Empty = new RGBA8(0, 0, 0, 0);
return RGBA8;
}());
exports.RGBA8 = RGBA8;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[22/*vs/editor/common/core/selection*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, position_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A selection in the editor.
* The selection is a range that has an orientation.
*/
var Selection = /** @class */ (function (_super) {
__extends(Selection, _super);
function Selection(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) {
var _this = _super.call(this, selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) || this;
_this.selectionStartLineNumber = selectionStartLineNumber;
_this.selectionStartColumn = selectionStartColumn;
_this.positionLineNumber = positionLineNumber;
_this.positionColumn = positionColumn;
return _this;
}
/**
* Transform to a human-readable representation.
*/
Selection.prototype.toString = function () {
return '[' + this.selectionStartLineNumber + ',' + this.selectionStartColumn + ' -> ' + this.positionLineNumber + ',' + this.positionColumn + ']';
};
/**
* Test if equals other selection.
*/
Selection.prototype.equalsSelection = function (other) {
return (Selection.selectionsEqual(this, other));
};
/**
* Test if the two selections are equal.
*/
Selection.selectionsEqual = function (a, b) {
return (a.selectionStartLineNumber === b.selectionStartLineNumber &&
a.selectionStartColumn === b.selectionStartColumn &&
a.positionLineNumber === b.positionLineNumber &&
a.positionColumn === b.positionColumn);
};
/**
* Get directions (LTR or RTL).
*/
Selection.prototype.getDirection = function () {
if (this.selectionStartLineNumber === this.startLineNumber && this.selectionStartColumn === this.startColumn) {
return 0 /* LTR */;
}
return 1 /* RTL */;
};
/**
* Create a new selection with a different `positionLineNumber` and `positionColumn`.
*/
Selection.prototype.setEndPosition = function (endLineNumber, endColumn) {
if (this.getDirection() === 0 /* LTR */) {
return new Selection(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
}
return new Selection(endLineNumber, endColumn, this.startLineNumber, this.startColumn);
};
/**
* Get the position at `positionLineNumber` and `positionColumn`.
*/
Selection.prototype.getPosition = function () {
return new position_1.Position(this.positionLineNumber, this.positionColumn);
};
/**
* Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`.
*/
Selection.prototype.setStartPosition = function (startLineNumber, startColumn) {
if (this.getDirection() === 0 /* LTR */) {
return new Selection(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
}
return new Selection(this.endLineNumber, this.endColumn, startLineNumber, startColumn);
};
// ----
/**
* Create a `Selection` from one or two positions
*/
Selection.fromPositions = function (start, end) {
if (end === void 0) { end = start; }
return new Selection(start.lineNumber, start.column, end.lineNumber, end.column);
};
/**
* Create a `Selection` from an `ISelection`.
*/
Selection.liftSelection = function (sel) {
return new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
};
/**
* `a` equals `b`.
*/
Selection.selectionsArrEqual = function (a, b) {
if (a && !b || !a && b) {
return false;
}
if (!a && !b) {
return true;
}
if (a.length !== b.length) {
return false;
}
for (var i = 0, len = a.length; i < len; i++) {
if (!this.selectionsEqual(a[i], b[i])) {
return false;
}
}
return true;
};
/**
* Test if `obj` is an `ISelection`.
*/
Selection.isISelection = function (obj) {
return (obj
&& (typeof obj.selectionStartLineNumber === 'number')
&& (typeof obj.selectionStartColumn === 'number')
&& (typeof obj.positionLineNumber === 'number')
&& (typeof obj.positionColumn === 'number'));
};
/**
* Create with a direction.
*/
Selection.createWithDirection = function (startLineNumber, startColumn, endLineNumber, endColumn, direction) {
if (direction === 0 /* LTR */) {
return new Selection(startLineNumber, startColumn, endLineNumber, endColumn);
}
return new Selection(endLineNumber, endColumn, startLineNumber, startColumn);
};
return Selection;
}(range_1.Range));
exports.Selection = Selection;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[189/*vs/editor/browser/controller/textAreaInput*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,5/*vs/base/common/strings*/,187/*vs/editor/browser/controller/textAreaState*/,22/*vs/editor/common/core/selection*/,88/*vs/base/browser/canIUse*/]), function (require, exports, browser, dom, async_1, event_1, lifecycle_1, platform, strings, textAreaState_1, selection_1, canIUse_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CopyOptions = {
forceCopyWithSyntaxHighlighting: false
};
/**
* Every time we write to the clipboard, we record a bit of extra metadata here.
* Every time we read from the cipboard, if the text matches our last written text,
* we can fetch the previous metadata.
*/
var InMemoryClipboardMetadataManager = /** @class */ (function () {
function InMemoryClipboardMetadataManager() {
this._lastState = null;
}
InMemoryClipboardMetadataManager.prototype.set = function (lastCopiedValue, data) {
this._lastState = { lastCopiedValue: lastCopiedValue, data: data };
};
InMemoryClipboardMetadataManager.prototype.get = function (pastedText) {
if (this._lastState && this._lastState.lastCopiedValue === pastedText) {
// match!
return this._lastState.data;
}
this._lastState = null;
return null;
};
InMemoryClipboardMetadataManager.INSTANCE = new InMemoryClipboardMetadataManager();
return InMemoryClipboardMetadataManager;
}());
/**
* Writes screen reader content to the textarea and is able to analyze its input events to generate:
* - onCut
* - onPaste
* - onType
*
* Composition events are generated for presentation purposes (composition input is reflected in onType).
*/
var TextAreaInput = /** @class */ (function (_super) {
__extends(TextAreaInput, _super);
function TextAreaInput(host, textArea) {
var _this = _super.call(this) || this;
_this.textArea = textArea;
_this._onFocus = _this._register(new event_1.Emitter());
_this.onFocus = _this._onFocus.event;
_this._onBlur = _this._register(new event_1.Emitter());
_this.onBlur = _this._onBlur.event;
_this._onKeyDown = _this._register(new event_1.Emitter());
_this.onKeyDown = _this._onKeyDown.event;
_this._onKeyUp = _this._register(new event_1.Emitter());
_this.onKeyUp = _this._onKeyUp.event;
_this._onCut = _this._register(new event_1.Emitter());
_this.onCut = _this._onCut.event;
_this._onPaste = _this._register(new event_1.Emitter());
_this.onPaste = _this._onPaste.event;
_this._onType = _this._register(new event_1.Emitter());
_this.onType = _this._onType.event;
_this._onCompositionStart = _this._register(new event_1.Emitter());
_this.onCompositionStart = _this._onCompositionStart.event;
_this._onCompositionUpdate = _this._register(new event_1.Emitter());
_this.onCompositionUpdate = _this._onCompositionUpdate.event;
_this._onCompositionEnd = _this._register(new event_1.Emitter());
_this.onCompositionEnd = _this._onCompositionEnd.event;
_this._onSelectionChangeRequest = _this._register(new event_1.Emitter());
_this.onSelectionChangeRequest = _this._onSelectionChangeRequest.event;
_this._host = host;
_this._textArea = _this._register(new TextAreaWrapper(textArea));
_this._asyncTriggerCut = _this._register(new async_1.RunOnceScheduler(function () { return _this._onCut.fire(); }, 0));
_this._textAreaState = textAreaState_1.TextAreaState.EMPTY;
_this._selectionChangeListener = null;
_this.writeScreenReaderContent('ctor');
_this._hasFocus = false;
_this._isDoingComposition = false;
_this._nextCommand = 0 /* Type */;
_this._register(dom.addStandardDisposableListener(textArea.domNode, 'keydown', function (e) {
if (_this._isDoingComposition &&
(e.keyCode === 109 /* KEY_IN_COMPOSITION */ || e.keyCode === 1 /* Backspace */)) {
// Stop propagation for keyDown events if the IME is processing key input
e.stopPropagation();
}
if (e.equals(9 /* Escape */)) {
// Prevent default always for `Esc`, otherwise it will generate a keypress
// See https://msdn.microsoft.com/en-us/library/ie/ms536939(v=vs.85).aspx
e.preventDefault();
}
_this._onKeyDown.fire(e);
}));
_this._register(dom.addStandardDisposableListener(textArea.domNode, 'keyup', function (e) {
_this._onKeyUp.fire(e);
}));
_this._register(dom.addDisposableListener(textArea.domNode, 'compositionstart', function (e) {
if (_this._isDoingComposition) {
return;
}
_this._isDoingComposition = true;
// In IE we cannot set .value when handling 'compositionstart' because the entire composition will get canceled.
if (!browser.isEdgeOrIE) {
_this._setAndWriteTextAreaState('compositionstart', textAreaState_1.TextAreaState.EMPTY);
}
_this._onCompositionStart.fire();
}));
/**
* Deduce the typed input from a text area's value and the last observed state.
*/
var deduceInputFromTextAreaValue = function (couldBeEmojiInput) {
var oldState = _this._textAreaState;
var newState = textAreaState_1.TextAreaState.readFromTextArea(_this._textArea);
return [newState, textAreaState_1.TextAreaState.deduceInput(oldState, newState, couldBeEmojiInput)];
};
/**
* Deduce the composition input from a string.
*/
var deduceComposition = function (text) {
var oldState = _this._textAreaState;
var newState = textAreaState_1.TextAreaState.selectedText(text);
var typeInput = {
text: newState.value,
replaceCharCnt: oldState.selectionEnd - oldState.selectionStart
};
return [newState, typeInput];
};
var compositionDataInValid = function (locale) {
// https://github.com/Microsoft/monaco-editor/issues/339
// Multi-part Japanese compositions reset cursor in Edge/IE, Chinese and Korean IME don't have this issue.
// The reason that we can't use this path for all CJK IME is IE and Edge behave differently when handling Korean IME,
// which breaks this path of code.
if (browser.isEdgeOrIE && locale === 'ja') {
return true;
}
// https://github.com/Microsoft/monaco-editor/issues/545
// On IE11, we can't trust composition data when typing Chinese as IE11 doesn't emit correct
// events when users type numbers in IME.
// Chinese: zh-Hans-CN, zh-Hans-SG, zh-Hant-TW, zh-Hant-HK
if (browser.isIE && locale.indexOf('zh-Han') === 0) {
return true;
}
return false;
};
_this._register(dom.addDisposableListener(textArea.domNode, 'compositionupdate', function (e) {
if (compositionDataInValid(e.locale)) {
var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ false), newState_1 = _a[0], typeInput_1 = _a[1];
_this._textAreaState = newState_1;
_this._onType.fire(typeInput_1);
_this._onCompositionUpdate.fire(e);
return;
}
var _b = deduceComposition(e.data), newState = _b[0], typeInput = _b[1];
_this._textAreaState = newState;
_this._onType.fire(typeInput);
_this._onCompositionUpdate.fire(e);
}));
_this._register(dom.addDisposableListener(textArea.domNode, 'compositionend', function (e) {
// https://github.com/microsoft/monaco-editor/issues/1663
// On iOS 13.2, Chinese system IME randomly trigger an additional compositionend event with empty data
if (!_this._isDoingComposition) {
return;
}
if (compositionDataInValid(e.locale)) {
// https://github.com/Microsoft/monaco-editor/issues/339
var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ false), newState = _a[0], typeInput = _a[1];
_this._textAreaState = newState;
_this._onType.fire(typeInput);
}
else {
var _b = deduceComposition(e.data), newState = _b[0], typeInput = _b[1];
_this._textAreaState = newState;
_this._onType.fire(typeInput);
}
// Due to isEdgeOrIE (where the textarea was not cleared initially) and isChrome (the textarea is not updated correctly when composition ends)
// we cannot assume the text at the end consists only of the composited text
if (browser.isEdgeOrIE || browser.isChrome) {
_this._textAreaState = textAreaState_1.TextAreaState.readFromTextArea(_this._textArea);
}
if (!_this._isDoingComposition) {
return;
}
_this._isDoingComposition = false;
_this._onCompositionEnd.fire();
}));
_this._register(dom.addDisposableListener(textArea.domNode, 'input', function () {
// Pretend here we touched the text area, as the `input` event will most likely
// result in a `selectionchange` event which we want to ignore
_this._textArea.setIgnoreSelectionChangeTime('received input event');
if (_this._isDoingComposition) {
return;
}
var _a = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/ platform.isMacintosh), newState = _a[0], typeInput = _a[1];
if (typeInput.replaceCharCnt === 0 && typeInput.text.length === 1 && strings.isHighSurrogate(typeInput.text.charCodeAt(0))) {
// Ignore invalid input but keep it around for next time
return;
}
_this._textAreaState = newState;
if (_this._nextCommand === 0 /* Type */) {
if (typeInput.text !== '') {
_this._onType.fire(typeInput);
}
}
else {
if (typeInput.text !== '' || typeInput.replaceCharCnt !== 0) {
_this._firePaste(typeInput.text, null);
}
_this._nextCommand = 0 /* Type */;
}
}));
// --- Clipboard operations
_this._register(dom.addDisposableListener(textArea.domNode, 'cut', function (e) {
// Pretend here we touched the text area, as the `cut` event will most likely
// result in a `selectionchange` event which we want to ignore
_this._textArea.setIgnoreSelectionChangeTime('received cut event');
_this._ensureClipboardGetsEditorSelection(e);
_this._asyncTriggerCut.schedule();
}));
_this._register(dom.addDisposableListener(textArea.domNode, 'copy', function (e) {
_this._ensureClipboardGetsEditorSelection(e);
}));
_this._register(dom.addDisposableListener(textArea.domNode, 'paste', function (e) {
// Pretend here we touched the text area, as the `paste` event will most likely
// result in a `selectionchange` event which we want to ignore
_this._textArea.setIgnoreSelectionChangeTime('received paste event');
if (ClipboardEventUtils.canUseTextData(e)) {
var _a = ClipboardEventUtils.getTextData(e), pastePlainText = _a[0], metadata = _a[1];
if (pastePlainText !== '') {
_this._firePaste(pastePlainText, metadata);
}
}
else {
if (_this._textArea.getSelectionStart() !== _this._textArea.getSelectionEnd()) {
// Clean up the textarea, to get a clean paste
_this._setAndWriteTextAreaState('paste', textAreaState_1.TextAreaState.EMPTY);
}
_this._nextCommand = 1 /* Paste */;
}
}));
_this._register(dom.addDisposableListener(textArea.domNode, 'focus', function () {
_this._setHasFocus(true);
}));
_this._register(dom.addDisposableListener(textArea.domNode, 'blur', function () {
_this._setHasFocus(false);
}));
return _this;
}
TextAreaInput.prototype._installSelectionChangeListener = function () {
// See https://github.com/Microsoft/vscode/issues/27216
// When using a Braille display, it is possible for users to reposition the
// system caret. This is reflected in Chrome as a `selectionchange` event.
//
// The `selectionchange` event appears to be emitted under numerous other circumstances,
// so it is quite a challenge to distinguish a `selectionchange` coming in from a user
// using a Braille display from all the other cases.
//
// The problems with the `selectionchange` event are:
// * the event is emitted when the textarea is focused programmatically -- textarea.focus()
// * the event is emitted when the selection is changed in the textarea programmatically -- textarea.setSelectionRange(...)
// * the event is emitted when the value of the textarea is changed programmatically -- textarea.value = '...'
// * the event is emitted when tabbing into the textarea
// * the event is emitted asynchronously (sometimes with a delay as high as a few tens of ms)
// * the event sometimes comes in bursts for a single logical textarea operation
var _this = this;
// `selectionchange` events often come multiple times for a single logical change
// so throttle multiple `selectionchange` events that burst in a short period of time.
var previousSelectionChangeEventTime = 0;
return dom.addDisposableListener(document, 'selectionchange', function (e) {
if (!_this._hasFocus) {
return;
}
if (_this._isDoingComposition) {
return;
}
if (!browser.isChrome || !platform.isWindows) {
// Support only for Chrome on Windows until testing happens on other browsers + OS configurations
return;
}
var now = Date.now();
var delta1 = now - previousSelectionChangeEventTime;
previousSelectionChangeEventTime = now;
if (delta1 < 5) {
// received another `selectionchange` event within 5ms of the previous `selectionchange` event
// => ignore it
return;
}
var delta2 = now - _this._textArea.getIgnoreSelectionChangeTime();
_this._textArea.resetSelectionChangeTime();
if (delta2 < 100) {
// received a `selectionchange` event within 100ms since we touched the textarea
// => ignore it, since we caused it
return;
}
if (!_this._textAreaState.selectionStartPosition || !_this._textAreaState.selectionEndPosition) {
// Cannot correlate a position in the textarea with a position in the editor...
return;
}
var newValue = _this._textArea.getValue();
if (_this._textAreaState.value !== newValue) {
// Cannot correlate a position in the textarea with a position in the editor...
return;
}
var newSelectionStart = _this._textArea.getSelectionStart();
var newSelectionEnd = _this._textArea.getSelectionEnd();
if (_this._textAreaState.selectionStart === newSelectionStart && _this._textAreaState.selectionEnd === newSelectionEnd) {
// Nothing to do...
return;
}
var _newSelectionStartPosition = _this._textAreaState.deduceEditorPosition(newSelectionStart);
var newSelectionStartPosition = _this._host.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]);
var _newSelectionEndPosition = _this._textAreaState.deduceEditorPosition(newSelectionEnd);
var newSelectionEndPosition = _this._host.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]);
var newSelection = new selection_1.Selection(newSelectionStartPosition.lineNumber, newSelectionStartPosition.column, newSelectionEndPosition.lineNumber, newSelectionEndPosition.column);
_this._onSelectionChangeRequest.fire(newSelection);
});
};
TextAreaInput.prototype.dispose = function () {
_super.prototype.dispose.call(this);
if (this._selectionChangeListener) {
this._selectionChangeListener.dispose();
this._selectionChangeListener = null;
}
};
TextAreaInput.prototype.focusTextArea = function () {
// Setting this._hasFocus and writing the screen reader content
// will result in a focus() and setSelectionRange() in the textarea
this._setHasFocus(true);
// If the editor is off DOM, focus cannot be really set, so let's double check that we have managed to set the focus
this.refreshFocusState();
};
TextAreaInput.prototype.isFocused = function () {
return this._hasFocus;
};
TextAreaInput.prototype.refreshFocusState = function () {
var shadowRoot = dom.getShadowRoot(this.textArea.domNode);
if (shadowRoot) {
this._setHasFocus(shadowRoot.activeElement === this.textArea.domNode);
}
else if (dom.isInDOM(this.textArea.domNode)) {
this._setHasFocus(document.activeElement === this.textArea.domNode);
}
else {
this._setHasFocus(false);
}
};
TextAreaInput.prototype._setHasFocus = function (newHasFocus) {
if (this._hasFocus === newHasFocus) {
// no change
return;
}
this._hasFocus = newHasFocus;
if (this._selectionChangeListener) {
this._selectionChangeListener.dispose();
this._selectionChangeListener = null;
}
if (this._hasFocus) {
this._selectionChangeListener = this._installSelectionChangeListener();
}
if (this._hasFocus) {
if (browser.isEdge) {
// Edge has a bug where setting the selection range while the focus event
// is dispatching doesn't work. To reproduce, "tab into" the editor.
this._setAndWriteTextAreaState('focusgain', textAreaState_1.TextAreaState.EMPTY);
}
else {
this.writeScreenReaderContent('focusgain');
}
}
if (this._hasFocus) {
this._onFocus.fire();
}
else {
this._onBlur.fire();
}
};
TextAreaInput.prototype._setAndWriteTextAreaState = function (reason, textAreaState) {
if (!this._hasFocus) {
textAreaState = textAreaState.collapseSelection();
}
textAreaState.writeToTextArea(reason, this._textArea, this._hasFocus);
this._textAreaState = textAreaState;
};
TextAreaInput.prototype.writeScreenReaderContent = function (reason) {
if (this._isDoingComposition) {
// Do not write to the text area when doing composition
return;
}
this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent(this._textAreaState));
};
TextAreaInput.prototype._ensureClipboardGetsEditorSelection = function (e) {
var dataToCopy = this._host.getDataToCopy(ClipboardEventUtils.canUseTextData(e) && canIUse_1.BrowserFeatures.clipboard.richText);
var storedMetadata = {
version: 1,
isFromEmptySelection: dataToCopy.isFromEmptySelection,
multicursorText: dataToCopy.multicursorText,
mode: dataToCopy.mode
};
InMemoryClipboardMetadataManager.INSTANCE.set(
// When writing "LINE\r\n" to the clipboard and then pasting,
// Firefox pastes "LINE\n", so let's work around this quirk
(browser.isFirefox ? dataToCopy.text.replace(/\r\n/g, '\n') : dataToCopy.text), storedMetadata);
if (!ClipboardEventUtils.canUseTextData(e)) {
// Looks like an old browser. The strategy is to place the text
// we'd like to be copied to the clipboard in the textarea and select it.
this._setAndWriteTextAreaState('copy or cut', textAreaState_1.TextAreaState.selectedText(dataToCopy.text));
return;
}
ClipboardEventUtils.setTextData(e, dataToCopy.text, dataToCopy.html, storedMetadata);
};
TextAreaInput.prototype._firePaste = function (text, metadata) {
if (!metadata) {
// try the in-memory store
metadata = InMemoryClipboardMetadataManager.INSTANCE.get(text);
}
this._onPaste.fire({
text: text,
metadata: metadata
});
};
return TextAreaInput;
}(lifecycle_1.Disposable));
exports.TextAreaInput = TextAreaInput;
var ClipboardEventUtils = /** @class */ (function () {
function ClipboardEventUtils() {
}
ClipboardEventUtils.canUseTextData = function (e) {
if (e.clipboardData) {
return true;
}
if (window.clipboardData) {
return true;
}
return false;
};
ClipboardEventUtils.getTextData = function (e) {
if (e.clipboardData) {
e.preventDefault();
var text = e.clipboardData.getData('text/plain');
var metadata = null;
var rawmetadata = e.clipboardData.getData('vscode-editor-data');
if (typeof rawmetadata === 'string') {
try {
metadata = JSON.parse(rawmetadata);
if (metadata.version !== 1) {
metadata = null;
}
}
catch (err) {
// no problem!
}
}
return [text, metadata];
}
if (window.clipboardData) {
e.preventDefault();
var text = window.clipboardData.getData('Text');
return [text, null];
}
throw new Error('ClipboardEventUtils.getTextData: Cannot use text data!');
};
ClipboardEventUtils.setTextData = function (e, text, html, metadata) {
if (e.clipboardData) {
e.clipboardData.setData('text/plain', text);
if (typeof html === 'string') {
e.clipboardData.setData('text/html', html);
}
e.clipboardData.setData('vscode-editor-data', JSON.stringify(metadata));
e.preventDefault();
return;
}
if (window.clipboardData) {
window.clipboardData.setData('Text', text);
e.preventDefault();
return;
}
throw new Error('ClipboardEventUtils.setTextData: Cannot use text data!');
};
return ClipboardEventUtils;
}());
var TextAreaWrapper = /** @class */ (function (_super) {
__extends(TextAreaWrapper, _super);
function TextAreaWrapper(_textArea) {
var _this = _super.call(this) || this;
_this._actual = _textArea;
_this._ignoreSelectionChangeTime = 0;
return _this;
}
TextAreaWrapper.prototype.setIgnoreSelectionChangeTime = function (reason) {
this._ignoreSelectionChangeTime = Date.now();
};
TextAreaWrapper.prototype.getIgnoreSelectionChangeTime = function () {
return this._ignoreSelectionChangeTime;
};
TextAreaWrapper.prototype.resetSelectionChangeTime = function () {
this._ignoreSelectionChangeTime = 0;
};
TextAreaWrapper.prototype.getValue = function () {
// console.log('current value: ' + this._textArea.value);
return this._actual.domNode.value;
};
TextAreaWrapper.prototype.setValue = function (reason, value) {
var textArea = this._actual.domNode;
if (textArea.value === value) {
// No change
return;
}
// console.log('reason: ' + reason + ', current value: ' + textArea.value + ' => new value: ' + value);
this.setIgnoreSelectionChangeTime('setValue');
textArea.value = value;
};
TextAreaWrapper.prototype.getSelectionStart = function () {
return this._actual.domNode.selectionStart;
};
TextAreaWrapper.prototype.getSelectionEnd = function () {
return this._actual.domNode.selectionEnd;
};
TextAreaWrapper.prototype.setSelectionRange = function (reason, selectionStart, selectionEnd) {
var textArea = this._actual.domNode;
var activeElement = null;
var shadowRoot = dom.getShadowRoot(textArea);
if (shadowRoot) {
activeElement = shadowRoot.activeElement;
}
else {
activeElement = document.activeElement;
}
var currentIsFocused = (activeElement === textArea);
var currentSelectionStart = textArea.selectionStart;
var currentSelectionEnd = textArea.selectionEnd;
if (currentIsFocused && currentSelectionStart === selectionStart && currentSelectionEnd === selectionEnd) {
// No change
// Firefox iframe bug https://github.com/Microsoft/monaco-editor/issues/643#issuecomment-367871377
if (browser.isFirefox && window.parent !== window) {
textArea.focus();
}
return;
}
// console.log('reason: ' + reason + ', setSelectionRange: ' + selectionStart + ' -> ' + selectionEnd);
if (currentIsFocused) {
// No need to focus, only need to change the selection range
this.setIgnoreSelectionChangeTime('setSelectionRange');
textArea.setSelectionRange(selectionStart, selectionEnd);
if (browser.isFirefox && window.parent !== window) {
textArea.focus();
}
return;
}
// If the focus is outside the textarea, browsers will try really hard to reveal the textarea.
// Here, we try to undo the browser's desperate reveal.
try {
var scrollState = dom.saveParentsScrollTop(textArea);
this.setIgnoreSelectionChangeTime('setSelectionRange');
textArea.focus();
textArea.setSelectionRange(selectionStart, selectionEnd);
dom.restoreParentsScrollTop(textArea, scrollState);
}
catch (e) {
// Sometimes IE throws when setting selection (e.g. textarea is off-DOM)
}
};
return TextAreaWrapper;
}(lifecycle_1.Disposable));
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[80/*vs/editor/common/commands/replaceCommand*/], __M([0/*require*/,1/*exports*/,22/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ReplaceCommand = /** @class */ (function () {
function ReplaceCommand(range, text, insertsAutoWhitespace) {
if (insertsAutoWhitespace === void 0) { insertsAutoWhitespace = false; }
this._range = range;
this._text = text;
this.insertsAutoWhitespace = insertsAutoWhitespace;
}
ReplaceCommand.prototype.getEditOperations = function (model, builder) {
builder.addTrackedEditOperation(this._range, this._text);
};
ReplaceCommand.prototype.computeCursorState = function (model, helper) {
var inverseEditOperations = helper.getInverseEditOperations();
var srcRange = inverseEditOperations[0].range;
return new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn, srcRange.endLineNumber, srcRange.endColumn);
};
return ReplaceCommand;
}());
exports.ReplaceCommand = ReplaceCommand;
var ReplaceCommandThatSelectsText = /** @class */ (function () {
function ReplaceCommandThatSelectsText(range, text) {
this._range = range;
this._text = text;
}
ReplaceCommandThatSelectsText.prototype.getEditOperations = function (model, builder) {
builder.addTrackedEditOperation(this._range, this._text);
};
ReplaceCommandThatSelectsText.prototype.computeCursorState = function (model, helper) {
var inverseEditOperations = helper.getInverseEditOperations();
var srcRange = inverseEditOperations[0].range;
return new selection_1.Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.endLineNumber, srcRange.endColumn);
};
return ReplaceCommandThatSelectsText;
}());
exports.ReplaceCommandThatSelectsText = ReplaceCommandThatSelectsText;
var ReplaceCommandWithoutChangingPosition = /** @class */ (function () {
function ReplaceCommandWithoutChangingPosition(range, text, insertsAutoWhitespace) {
if (insertsAutoWhitespace === void 0) { insertsAutoWhitespace = false; }
this._range = range;
this._text = text;
this.insertsAutoWhitespace = insertsAutoWhitespace;
}
ReplaceCommandWithoutChangingPosition.prototype.getEditOperations = function (model, builder) {
builder.addTrackedEditOperation(this._range, this._text);
};
ReplaceCommandWithoutChangingPosition.prototype.computeCursorState = function (model, helper) {
var inverseEditOperations = helper.getInverseEditOperations();
var srcRange = inverseEditOperations[0].range;
return new selection_1.Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.startLineNumber, srcRange.startColumn);
};
return ReplaceCommandWithoutChangingPosition;
}());
exports.ReplaceCommandWithoutChangingPosition = ReplaceCommandWithoutChangingPosition;
var ReplaceCommandWithOffsetCursorState = /** @class */ (function () {
function ReplaceCommandWithOffsetCursorState(range, text, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace) {
if (insertsAutoWhitespace === void 0) { insertsAutoWhitespace = false; }
this._range = range;
this._text = text;
this._columnDeltaOffset = columnDeltaOffset;
this._lineNumberDeltaOffset = lineNumberDeltaOffset;
this.insertsAutoWhitespace = insertsAutoWhitespace;
}
ReplaceCommandWithOffsetCursorState.prototype.getEditOperations = function (model, builder) {
builder.addTrackedEditOperation(this._range, this._text);
};
ReplaceCommandWithOffsetCursorState.prototype.computeCursorState = function (model, helper) {
var inverseEditOperations = helper.getInverseEditOperations();
var srcRange = inverseEditOperations[0].range;
return new selection_1.Selection(srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + this._columnDeltaOffset, srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + this._columnDeltaOffset);
};
return ReplaceCommandWithOffsetCursorState;
}());
exports.ReplaceCommandWithOffsetCursorState = ReplaceCommandWithOffsetCursorState;
var ReplaceCommandThatPreservesSelection = /** @class */ (function () {
function ReplaceCommandThatPreservesSelection(editRange, text, initialSelection, forceMoveMarkers) {
if (forceMoveMarkers === void 0) { forceMoveMarkers = false; }
this._range = editRange;
this._text = text;
this._initialSelection = initialSelection;
this._forceMoveMarkers = forceMoveMarkers;
this._selectionId = null;
}
ReplaceCommandThatPreservesSelection.prototype.getEditOperations = function (model, builder) {
builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers);
this._selectionId = builder.trackSelection(this._initialSelection);
};
ReplaceCommandThatPreservesSelection.prototype.computeCursorState = function (model, helper) {
return helper.getTrackedSelection(this._selectionId);
};
return ReplaceCommandThatPreservesSelection;
}());
exports.ReplaceCommandThatPreservesSelection = ReplaceCommandThatPreservesSelection;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[340/*vs/editor/common/commands/surroundSelectionCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SurroundSelectionCommand = /** @class */ (function () {
function SurroundSelectionCommand(range, charBeforeSelection, charAfterSelection) {
this._range = range;
this._charBeforeSelection = charBeforeSelection;
this._charAfterSelection = charAfterSelection;
}
SurroundSelectionCommand.prototype.getEditOperations = function (model, builder) {
builder.addTrackedEditOperation(new range_1.Range(this._range.startLineNumber, this._range.startColumn, this._range.startLineNumber, this._range.startColumn), this._charBeforeSelection);
builder.addTrackedEditOperation(new range_1.Range(this._range.endLineNumber, this._range.endColumn, this._range.endLineNumber, this._range.endColumn), this._charAfterSelection);
};
SurroundSelectionCommand.prototype.computeCursorState = function (model, helper) {
var inverseEditOperations = helper.getInverseEditOperations();
var firstOperationRange = inverseEditOperations[0].range;
var secondOperationRange = inverseEditOperations[1].range;
return new selection_1.Selection(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length);
};
return SurroundSelectionCommand;
}());
exports.SurroundSelectionCommand = SurroundSelectionCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[106/*vs/editor/common/core/stringBuilder*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
if (typeof TextDecoder !== 'undefined') {
exports.createStringBuilder = function (capacity) { return new StringBuilder(capacity); };
}
else {
exports.createStringBuilder = function (capacity) { return new CompatStringBuilder(); };
}
var StringBuilder = /** @class */ (function () {
function StringBuilder(capacity) {
this._decoder = new TextDecoder('UTF-16LE');
this._capacity = capacity | 0;
this._buffer = new Uint16Array(this._capacity);
this._completedStrings = null;
this._bufferLength = 0;
}
StringBuilder.prototype.reset = function () {
this._completedStrings = null;
this._bufferLength = 0;
};
StringBuilder.prototype.build = function () {
if (this._completedStrings !== null) {
this._flushBuffer();
return this._completedStrings.join('');
}
return this._buildBuffer();
};
StringBuilder.prototype._buildBuffer = function () {
if (this._bufferLength === 0) {
return '';
}
var view = new Uint16Array(this._buffer.buffer, 0, this._bufferLength);
return this._decoder.decode(view);
};
StringBuilder.prototype._flushBuffer = function () {
var bufferString = this._buildBuffer();
this._bufferLength = 0;
if (this._completedStrings === null) {
this._completedStrings = [bufferString];
}
else {
this._completedStrings[this._completedStrings.length] = bufferString;
}
};
StringBuilder.prototype.write1 = function (charCode) {
var remainingSpace = this._capacity - this._bufferLength;
if (remainingSpace <= 1) {
if (remainingSpace === 0 || strings.isHighSurrogate(charCode)) {
this._flushBuffer();
}
}
this._buffer[this._bufferLength++] = charCode;
};
StringBuilder.prototype.appendASCII = function (charCode) {
if (this._bufferLength === this._capacity) {
// buffer is full
this._flushBuffer();
}
this._buffer[this._bufferLength++] = charCode;
};
StringBuilder.prototype.appendASCIIString = function (str) {
var strLen = str.length;
if (this._bufferLength + strLen >= this._capacity) {
// This string does not fit in the remaining buffer space
this._flushBuffer();
this._completedStrings[this._completedStrings.length] = str;
return;
}
for (var i = 0; i < strLen; i++) {
this._buffer[this._bufferLength++] = str.charCodeAt(i);
}
};
return StringBuilder;
}());
var CompatStringBuilder = /** @class */ (function () {
function CompatStringBuilder() {
this._pieces = [];
this._piecesLen = 0;
}
CompatStringBuilder.prototype.reset = function () {
this._pieces = [];
this._piecesLen = 0;
};
CompatStringBuilder.prototype.build = function () {
return this._pieces.join('');
};
CompatStringBuilder.prototype.write1 = function (charCode) {
this._pieces[this._piecesLen++] = String.fromCharCode(charCode);
};
CompatStringBuilder.prototype.appendASCII = function (charCode) {
this._pieces[this._piecesLen++] = String.fromCharCode(charCode);
};
CompatStringBuilder.prototype.appendASCIIString = function (str) {
this._pieces[this._piecesLen++] = str;
};
return CompatStringBuilder;
}());
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[143/*vs/editor/browser/view/viewLayer*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,106/*vs/editor/common/core/stringBuilder*/]), function (require, exports, fastDomNode_1, stringBuilder_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var RenderedLinesCollection = /** @class */ (function () {
function RenderedLinesCollection(createLine) {
this._createLine = createLine;
this._set(1, []);
}
RenderedLinesCollection.prototype.flush = function () {
this._set(1, []);
};
RenderedLinesCollection.prototype._set = function (rendLineNumberStart, lines) {
this._lines = lines;
this._rendLineNumberStart = rendLineNumberStart;
};
RenderedLinesCollection.prototype._get = function () {
return {
rendLineNumberStart: this._rendLineNumberStart,
lines: this._lines
};
};
/**
* @returns Inclusive line number that is inside this collection
*/
RenderedLinesCollection.prototype.getStartLineNumber = function () {
return this._rendLineNumberStart;
};
/**
* @returns Inclusive line number that is inside this collection
*/
RenderedLinesCollection.prototype.getEndLineNumber = function () {
return this._rendLineNumberStart + this._lines.length - 1;
};
RenderedLinesCollection.prototype.getCount = function () {
return this._lines.length;
};
RenderedLinesCollection.prototype.getLine = function (lineNumber) {
var lineIndex = lineNumber - this._rendLineNumberStart;
if (lineIndex < 0 || lineIndex >= this._lines.length) {
throw new Error('Illegal value for lineNumber');
}
return this._lines[lineIndex];
};
/**
* @returns Lines that were removed from this collection
*/
RenderedLinesCollection.prototype.onLinesDeleted = function (deleteFromLineNumber, deleteToLineNumber) {
if (this.getCount() === 0) {
// no lines
return null;
}
var startLineNumber = this.getStartLineNumber();
var endLineNumber = this.getEndLineNumber();
if (deleteToLineNumber < startLineNumber) {
// deleting above the viewport
var deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1;
this._rendLineNumberStart -= deleteCnt;
return null;
}
if (deleteFromLineNumber > endLineNumber) {
// deleted below the viewport
return null;
}
// Record what needs to be deleted
var deleteStartIndex = 0;
var deleteCount = 0;
for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
var lineIndex = lineNumber - this._rendLineNumberStart;
if (deleteFromLineNumber <= lineNumber && lineNumber <= deleteToLineNumber) {
// this is a line to be deleted
if (deleteCount === 0) {
// this is the first line to be deleted
deleteStartIndex = lineIndex;
deleteCount = 1;
}
else {
deleteCount++;
}
}
}
// Adjust this._rendLineNumberStart for lines deleted above
if (deleteFromLineNumber < startLineNumber) {
// Something was deleted above
var deleteAboveCount = 0;
if (deleteToLineNumber < startLineNumber) {
// the entire deleted lines are above
deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1;
}
else {
deleteAboveCount = startLineNumber - deleteFromLineNumber;
}
this._rendLineNumberStart -= deleteAboveCount;
}
var deleted = this._lines.splice(deleteStartIndex, deleteCount);
return deleted;
};
RenderedLinesCollection.prototype.onLinesChanged = function (changeFromLineNumber, changeToLineNumber) {
if (this.getCount() === 0) {
// no lines
return false;
}
var startLineNumber = this.getStartLineNumber();
var endLineNumber = this.getEndLineNumber();
var someoneNotified = false;
for (var changedLineNumber = changeFromLineNumber; changedLineNumber <= changeToLineNumber; changedLineNumber++) {
if (changedLineNumber >= startLineNumber && changedLineNumber <= endLineNumber) {
// Notify the line
this._lines[changedLineNumber - this._rendLineNumberStart].onContentChanged();
someoneNotified = true;
}
}
return someoneNotified;
};
RenderedLinesCollection.prototype.onLinesInserted = function (insertFromLineNumber, insertToLineNumber) {
if (this.getCount() === 0) {
// no lines
return null;
}
var insertCnt = insertToLineNumber - insertFromLineNumber + 1;
var startLineNumber = this.getStartLineNumber();
var endLineNumber = this.getEndLineNumber();
if (insertFromLineNumber <= startLineNumber) {
// inserting above the viewport
this._rendLineNumberStart += insertCnt;
return null;
}
if (insertFromLineNumber > endLineNumber) {
// inserting below the viewport
return null;
}
if (insertCnt + insertFromLineNumber > endLineNumber) {
// insert inside the viewport in such a way that all remaining lines are pushed outside
var deleted = this._lines.splice(insertFromLineNumber - this._rendLineNumberStart, endLineNumber - insertFromLineNumber + 1);
return deleted;
}
// insert inside the viewport, push out some lines, but not all remaining lines
var newLines = [];
for (var i = 0; i < insertCnt; i++) {
newLines[i] = this._createLine();
}
var insertIndex = insertFromLineNumber - this._rendLineNumberStart;
var beforeLines = this._lines.slice(0, insertIndex);
var afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt);
var deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length);
this._lines = beforeLines.concat(newLines).concat(afterLines);
return deletedLines;
};
RenderedLinesCollection.prototype.onTokensChanged = function (ranges) {
if (this.getCount() === 0) {
// no lines
return false;
}
var startLineNumber = this.getStartLineNumber();
var endLineNumber = this.getEndLineNumber();
var notifiedSomeone = false;
for (var i = 0, len = ranges.length; i < len; i++) {
var rng = ranges[i];
if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) {
// range outside viewport
continue;
}
var from = Math.max(startLineNumber, rng.fromLineNumber);
var to = Math.min(endLineNumber, rng.toLineNumber);
for (var lineNumber = from; lineNumber <= to; lineNumber++) {
var lineIndex = lineNumber - this._rendLineNumberStart;
this._lines[lineIndex].onTokensChanged();
notifiedSomeone = true;
}
}
return notifiedSomeone;
};
return RenderedLinesCollection;
}());
exports.RenderedLinesCollection = RenderedLinesCollection;
var VisibleLinesCollection = /** @class */ (function () {
function VisibleLinesCollection(host) {
var _this = this;
this._host = host;
this.domNode = this._createDomNode();
this._linesCollection = new RenderedLinesCollection(function () { return _this._host.createVisibleLine(); });
}
VisibleLinesCollection.prototype._createDomNode = function () {
var domNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
domNode.setClassName('view-layer');
domNode.setPosition('absolute');
domNode.domNode.setAttribute('role', 'presentation');
domNode.domNode.setAttribute('aria-hidden', 'true');
return domNode;
};
// ---- begin view event handlers
VisibleLinesCollection.prototype.onConfigurationChanged = function (e) {
if (e.hasChanged(107 /* layoutInfo */)) {
return true;
}
return false;
};
VisibleLinesCollection.prototype.onFlushed = function (e) {
this._linesCollection.flush();
// No need to clear the dom node because a full .innerHTML will occur in ViewLayerRenderer._render
return true;
};
VisibleLinesCollection.prototype.onLinesChanged = function (e) {
return this._linesCollection.onLinesChanged(e.fromLineNumber, e.toLineNumber);
};
VisibleLinesCollection.prototype.onLinesDeleted = function (e) {
var deleted = this._linesCollection.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
if (deleted) {
// Remove from DOM
for (var i = 0, len = deleted.length; i < len; i++) {
var lineDomNode = deleted[i].getDomNode();
if (lineDomNode) {
this.domNode.domNode.removeChild(lineDomNode);
}
}
}
return true;
};
VisibleLinesCollection.prototype.onLinesInserted = function (e) {
var deleted = this._linesCollection.onLinesInserted(e.fromLineNumber, e.toLineNumber);
if (deleted) {
// Remove from DOM
for (var i = 0, len = deleted.length; i < len; i++) {
var lineDomNode = deleted[i].getDomNode();
if (lineDomNode) {
this.domNode.domNode.removeChild(lineDomNode);
}
}
}
return true;
};
VisibleLinesCollection.prototype.onScrollChanged = function (e) {
return e.scrollTopChanged;
};
VisibleLinesCollection.prototype.onTokensChanged = function (e) {
return this._linesCollection.onTokensChanged(e.ranges);
};
VisibleLinesCollection.prototype.onZonesChanged = function (e) {
return true;
};
// ---- end view event handlers
VisibleLinesCollection.prototype.getStartLineNumber = function () {
return this._linesCollection.getStartLineNumber();
};
VisibleLinesCollection.prototype.getEndLineNumber = function () {
return this._linesCollection.getEndLineNumber();
};
VisibleLinesCollection.prototype.getVisibleLine = function (lineNumber) {
return this._linesCollection.getLine(lineNumber);
};
VisibleLinesCollection.prototype.renderLines = function (viewportData) {
var inp = this._linesCollection._get();
var renderer = new ViewLayerRenderer(this.domNode.domNode, this._host, viewportData);
var ctx = {
rendLineNumberStart: inp.rendLineNumberStart,
lines: inp.lines,
linesLength: inp.lines.length
};
// Decide if this render will do a single update (single large .innerHTML) or many updates (inserting/removing dom nodes)
var resCtx = renderer.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset);
this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines);
};
return VisibleLinesCollection;
}());
exports.VisibleLinesCollection = VisibleLinesCollection;
var ViewLayerRenderer = /** @class */ (function () {
function ViewLayerRenderer(domNode, host, viewportData) {
this.domNode = domNode;
this.host = host;
this.viewportData = viewportData;
}
ViewLayerRenderer.prototype.render = function (inContext, startLineNumber, stopLineNumber, deltaTop) {
var ctx = {
rendLineNumberStart: inContext.rendLineNumberStart,
lines: inContext.lines.slice(0),
linesLength: inContext.linesLength
};
if ((ctx.rendLineNumberStart + ctx.linesLength - 1 < startLineNumber) || (stopLineNumber < ctx.rendLineNumberStart)) {
// There is no overlap whatsoever
ctx.rendLineNumberStart = startLineNumber;
ctx.linesLength = stopLineNumber - startLineNumber + 1;
ctx.lines = [];
for (var x = startLineNumber; x <= stopLineNumber; x++) {
ctx.lines[x - startLineNumber] = this.host.createVisibleLine();
}
this._finishRendering(ctx, true, deltaTop);
return ctx;
}
// Update lines which will remain untouched
this._renderUntouchedLines(ctx, Math.max(startLineNumber - ctx.rendLineNumberStart, 0), Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1), deltaTop, startLineNumber);
if (ctx.rendLineNumberStart > startLineNumber) {
// Insert lines before
var fromLineNumber = startLineNumber;
var toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);
if (fromLineNumber <= toLineNumber) {
this._insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
ctx.linesLength += toLineNumber - fromLineNumber + 1;
}
}
else if (ctx.rendLineNumberStart < startLineNumber) {
// Remove lines before
var removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);
if (removeCnt > 0) {
this._removeLinesBefore(ctx, removeCnt);
ctx.linesLength -= removeCnt;
}
}
ctx.rendLineNumberStart = startLineNumber;
if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {
// Insert lines after
var fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;
var toLineNumber = stopLineNumber;
if (fromLineNumber <= toLineNumber) {
this._insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
ctx.linesLength += toLineNumber - fromLineNumber + 1;
}
}
else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {
// Remove lines after
var fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);
var toLineNumber = ctx.linesLength - 1;
var removeCnt = toLineNumber - fromLineNumber + 1;
if (removeCnt > 0) {
this._removeLinesAfter(ctx, removeCnt);
ctx.linesLength -= removeCnt;
}
}
this._finishRendering(ctx, false, deltaTop);
return ctx;
};
ViewLayerRenderer.prototype._renderUntouchedLines = function (ctx, startIndex, endIndex, deltaTop, deltaLN) {
var rendLineNumberStart = ctx.rendLineNumberStart;
var lines = ctx.lines;
for (var i = startIndex; i <= endIndex; i++) {
var lineNumber = rendLineNumberStart + i;
lines[i].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN]);
}
};
ViewLayerRenderer.prototype._insertLinesBefore = function (ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
var newLines = [];
var newLinesLen = 0;
for (var lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
newLines[newLinesLen++] = this.host.createVisibleLine();
}
ctx.lines = newLines.concat(ctx.lines);
};
ViewLayerRenderer.prototype._removeLinesBefore = function (ctx, removeCount) {
for (var i = 0; i < removeCount; i++) {
var lineDomNode = ctx.lines[i].getDomNode();
if (lineDomNode) {
this.domNode.removeChild(lineDomNode);
}
}
ctx.lines.splice(0, removeCount);
};
ViewLayerRenderer.prototype._insertLinesAfter = function (ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
var newLines = [];
var newLinesLen = 0;
for (var lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
newLines[newLinesLen++] = this.host.createVisibleLine();
}
ctx.lines = ctx.lines.concat(newLines);
};
ViewLayerRenderer.prototype._removeLinesAfter = function (ctx, removeCount) {
var removeIndex = ctx.linesLength - removeCount;
for (var i = 0; i < removeCount; i++) {
var lineDomNode = ctx.lines[removeIndex + i].getDomNode();
if (lineDomNode) {
this.domNode.removeChild(lineDomNode);
}
}
ctx.lines.splice(removeIndex, removeCount);
};
ViewLayerRenderer.prototype._finishRenderingNewLines = function (ctx, domNodeIsEmpty, newLinesHTML, wasNew) {
var lastChild = this.domNode.lastChild;
if (domNodeIsEmpty || !lastChild) {
this.domNode.innerHTML = newLinesHTML;
}
else {
lastChild.insertAdjacentHTML('afterend', newLinesHTML);
}
var currChild = this.domNode.lastChild;
for (var i = ctx.linesLength - 1; i >= 0; i--) {
var line = ctx.lines[i];
if (wasNew[i]) {
line.setDomNode(currChild);
currChild = currChild.previousSibling;
}
}
};
ViewLayerRenderer.prototype._finishRenderingInvalidLines = function (ctx, invalidLinesHTML, wasInvalid) {
var hugeDomNode = document.createElement('div');
hugeDomNode.innerHTML = invalidLinesHTML;
for (var i = 0; i < ctx.linesLength; i++) {
var line = ctx.lines[i];
if (wasInvalid[i]) {
var source = hugeDomNode.firstChild;
var lineDomNode = line.getDomNode();
lineDomNode.parentNode.replaceChild(source, lineDomNode);
line.setDomNode(source);
}
}
};
ViewLayerRenderer.prototype._finishRendering = function (ctx, domNodeIsEmpty, deltaTop) {
var sb = ViewLayerRenderer._sb;
var linesLength = ctx.linesLength;
var lines = ctx.lines;
var rendLineNumberStart = ctx.rendLineNumberStart;
var wasNew = [];
{
sb.reset();
var hadNewLine = false;
for (var i = 0; i < linesLength; i++) {
var line = lines[i];
wasNew[i] = false;
var lineDomNode = line.getDomNode();
if (lineDomNode) {
// line is not new
continue;
}
var renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this.viewportData, sb);
if (!renderResult) {
// line does not need rendering
continue;
}
wasNew[i] = true;
hadNewLine = true;
}
if (hadNewLine) {
this._finishRenderingNewLines(ctx, domNodeIsEmpty, sb.build(), wasNew);
}
}
{
sb.reset();
var hadInvalidLine = false;
var wasInvalid = [];
for (var i = 0; i < linesLength; i++) {
var line = lines[i];
wasInvalid[i] = false;
if (wasNew[i]) {
// line was new
continue;
}
var renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this.viewportData, sb);
if (!renderResult) {
// line does not need rendering
continue;
}
wasInvalid[i] = true;
hadInvalidLine = true;
}
if (hadInvalidLine) {
this._finishRenderingInvalidLines(ctx, sb.build(), wasInvalid);
}
}
};
ViewLayerRenderer._sb = stringBuilder_1.createStringBuilder(100000);
return ViewLayerRenderer;
}());
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[107/*vs/editor/common/core/token*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Token = /** @class */ (function () {
function Token(offset, type, language) {
this.offset = offset | 0; // @perf
this.type = type;
this.language = language;
}
Token.prototype.toString = function () {
return '(' + this.offset + ', ' + this.type + ')';
};
return Token;
}());
exports.Token = Token;
var TokenizationResult = /** @class */ (function () {
function TokenizationResult(tokens, endState) {
this.tokens = tokens;
this.endState = endState;
}
return TokenizationResult;
}());
exports.TokenizationResult = TokenizationResult;
var TokenizationResult2 = /** @class */ (function () {
function TokenizationResult2(tokens, endState) {
this.tokens = tokens;
this.endState = endState;
}
return TokenizationResult2;
}());
exports.TokenizationResult2 = TokenizationResult2;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[341/*vs/editor/common/diff/diffComputer*/], __M([0/*require*/,1/*exports*/,126/*vs/base/common/diff/diff*/,5/*vs/base/common/strings*/]), function (require, exports, diff_1, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MINIMUM_MATCHING_CHARACTER_LENGTH = 3;
function computeDiff(originalSequence, modifiedSequence, continueProcessingPredicate, pretty) {
var diffAlgo = new diff_1.LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate);
return diffAlgo.ComputeDiff(pretty);
}
var LineSequence = /** @class */ (function () {
function LineSequence(lines) {
var startColumns = [];
var endColumns = [];
for (var i = 0, length_1 = lines.length; i < length_1; i++) {
startColumns[i] = getFirstNonBlankColumn(lines[i], 1);
endColumns[i] = getLastNonBlankColumn(lines[i], 1);
}
this.lines = lines;
this._startColumns = startColumns;
this._endColumns = endColumns;
}
LineSequence.prototype.getElements = function () {
var elements = [];
for (var i = 0, len = this.lines.length; i < len; i++) {
elements[i] = this.lines[i].substring(this._startColumns[i] - 1, this._endColumns[i] - 1);
}
return elements;
};
LineSequence.prototype.getStartLineNumber = function (i) {
return i + 1;
};
LineSequence.prototype.getEndLineNumber = function (i) {
return i + 1;
};
LineSequence.prototype.createCharSequence = function (shouldIgnoreTrimWhitespace, startIndex, endIndex) {
var charCodes = [];
var lineNumbers = [];
var columns = [];
var len = 0;
for (var index = startIndex; index <= endIndex; index++) {
var lineContent = this.lines[index];
var startColumn = (shouldIgnoreTrimWhitespace ? this._startColumns[index] : 1);
var endColumn = (shouldIgnoreTrimWhitespace ? this._endColumns[index] : lineContent.length + 1);
for (var col = startColumn; col < endColumn; col++) {
charCodes[len] = lineContent.charCodeAt(col - 1);
lineNumbers[len] = index + 1;
columns[len] = col;
len++;
}
}
return new CharSequence(charCodes, lineNumbers, columns);
};
return LineSequence;
}());
var CharSequence = /** @class */ (function () {
function CharSequence(charCodes, lineNumbers, columns) {
this._charCodes = charCodes;
this._lineNumbers = lineNumbers;
this._columns = columns;
}
CharSequence.prototype.getElements = function () {
return this._charCodes;
};
CharSequence.prototype.getStartLineNumber = function (i) {
return this._lineNumbers[i];
};
CharSequence.prototype.getStartColumn = function (i) {
return this._columns[i];
};
CharSequence.prototype.getEndLineNumber = function (i) {
return this._lineNumbers[i];
};
CharSequence.prototype.getEndColumn = function (i) {
return this._columns[i] + 1;
};
return CharSequence;
}());
var CharChange = /** @class */ (function () {
function CharChange(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn) {
this.originalStartLineNumber = originalStartLineNumber;
this.originalStartColumn = originalStartColumn;
this.originalEndLineNumber = originalEndLineNumber;
this.originalEndColumn = originalEndColumn;
this.modifiedStartLineNumber = modifiedStartLineNumber;
this.modifiedStartColumn = modifiedStartColumn;
this.modifiedEndLineNumber = modifiedEndLineNumber;
this.modifiedEndColumn = modifiedEndColumn;
}
CharChange.createFromDiffChange = function (diffChange, originalCharSequence, modifiedCharSequence) {
var originalStartLineNumber;
var originalStartColumn;
var originalEndLineNumber;
var originalEndColumn;
var modifiedStartLineNumber;
var modifiedStartColumn;
var modifiedEndLineNumber;
var modifiedEndColumn;
if (diffChange.originalLength === 0) {
originalStartLineNumber = 0;
originalStartColumn = 0;
originalEndLineNumber = 0;
originalEndColumn = 0;
}
else {
originalStartLineNumber = originalCharSequence.getStartLineNumber(diffChange.originalStart);
originalStartColumn = originalCharSequence.getStartColumn(diffChange.originalStart);
originalEndLineNumber = originalCharSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
originalEndColumn = originalCharSequence.getEndColumn(diffChange.originalStart + diffChange.originalLength - 1);
}
if (diffChange.modifiedLength === 0) {
modifiedStartLineNumber = 0;
modifiedStartColumn = 0;
modifiedEndLineNumber = 0;
modifiedEndColumn = 0;
}
else {
modifiedStartLineNumber = modifiedCharSequence.getStartLineNumber(diffChange.modifiedStart);
modifiedStartColumn = modifiedCharSequence.getStartColumn(diffChange.modifiedStart);
modifiedEndLineNumber = modifiedCharSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
modifiedEndColumn = modifiedCharSequence.getEndColumn(diffChange.modifiedStart + diffChange.modifiedLength - 1);
}
return new CharChange(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn);
};
return CharChange;
}());
function postProcessCharChanges(rawChanges) {
if (rawChanges.length <= 1) {
return rawChanges;
}
var result = [rawChanges[0]];
var prevChange = result[0];
for (var i = 1, len = rawChanges.length; i < len; i++) {
var currChange = rawChanges[i];
var originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength);
var modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength);
// Both of the above should be equal, but the continueProcessingPredicate may prevent this from being true
var matchingLength = Math.min(originalMatchingLength, modifiedMatchingLength);
if (matchingLength < MINIMUM_MATCHING_CHARACTER_LENGTH) {
// Merge the current change into the previous one
prevChange.originalLength = (currChange.originalStart + currChange.originalLength) - prevChange.originalStart;
prevChange.modifiedLength = (currChange.modifiedStart + currChange.modifiedLength) - prevChange.modifiedStart;
}
else {
// Add the current change
result.push(currChange);
prevChange = currChange;
}
}
return result;
}
var LineChange = /** @class */ (function () {
function LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges) {
this.originalStartLineNumber = originalStartLineNumber;
this.originalEndLineNumber = originalEndLineNumber;
this.modifiedStartLineNumber = modifiedStartLineNumber;
this.modifiedEndLineNumber = modifiedEndLineNumber;
this.charChanges = charChanges;
}
LineChange.createFromDiffResult = function (shouldIgnoreTrimWhitespace, diffChange, originalLineSequence, modifiedLineSequence, continueCharDiff, shouldComputeCharChanges, shouldPostProcessCharChanges) {
var originalStartLineNumber;
var originalEndLineNumber;
var modifiedStartLineNumber;
var modifiedEndLineNumber;
var charChanges = undefined;
if (diffChange.originalLength === 0) {
originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart) - 1;
originalEndLineNumber = 0;
}
else {
originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart);
originalEndLineNumber = originalLineSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
}
if (diffChange.modifiedLength === 0) {
modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart) - 1;
modifiedEndLineNumber = 0;
}
else {
modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart);
modifiedEndLineNumber = modifiedLineSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
}
if (shouldComputeCharChanges && diffChange.originalLength > 0 && diffChange.originalLength < 20 && diffChange.modifiedLength > 0 && diffChange.modifiedLength < 20 && continueCharDiff()) {
// Compute character changes for diff chunks of at most 20 lines...
var originalCharSequence = originalLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1);
var modifiedCharSequence = modifiedLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1);
var rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueCharDiff, true).changes;
if (shouldPostProcessCharChanges) {
rawChanges = postProcessCharChanges(rawChanges);
}
charChanges = [];
for (var i = 0, length_2 = rawChanges.length; i < length_2; i++) {
charChanges.push(CharChange.createFromDiffChange(rawChanges[i], originalCharSequence, modifiedCharSequence));
}
}
return new LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges);
};
return LineChange;
}());
var DiffComputer = /** @class */ (function () {
function DiffComputer(originalLines, modifiedLines, opts) {
this.shouldComputeCharChanges = opts.shouldComputeCharChanges;
this.shouldPostProcessCharChanges = opts.shouldPostProcessCharChanges;
this.shouldIgnoreTrimWhitespace = opts.shouldIgnoreTrimWhitespace;
this.shouldMakePrettyDiff = opts.shouldMakePrettyDiff;
this.originalLines = originalLines;
this.modifiedLines = modifiedLines;
this.original = new LineSequence(originalLines);
this.modified = new LineSequence(modifiedLines);
this.continueLineDiff = createContinueProcessingPredicate(opts.maxComputationTime);
this.continueCharDiff = createContinueProcessingPredicate(opts.maxComputationTime === 0 ? 0 : Math.min(opts.maxComputationTime, 5000)); // never run after 5s for character changes...
}
DiffComputer.prototype.computeDiff = function () {
if (this.original.lines.length === 1 && this.original.lines[0].length === 0) {
// empty original => fast path
return {
quitEarly: false,
changes: [{
originalStartLineNumber: 1,
originalEndLineNumber: 1,
modifiedStartLineNumber: 1,
modifiedEndLineNumber: this.modified.lines.length,
charChanges: [{
modifiedEndColumn: 0,
modifiedEndLineNumber: 0,
modifiedStartColumn: 0,
modifiedStartLineNumber: 0,
originalEndColumn: 0,
originalEndLineNumber: 0,
originalStartColumn: 0,
originalStartLineNumber: 0
}]
}]
};
}
if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
// empty modified => fast path
return {
quitEarly: false,
changes: [{
originalStartLineNumber: 1,
originalEndLineNumber: this.original.lines.length,
modifiedStartLineNumber: 1,
modifiedEndLineNumber: 1,
charChanges: [{
modifiedEndColumn: 0,
modifiedEndLineNumber: 0,
modifiedStartColumn: 0,
modifiedStartLineNumber: 0,
originalEndColumn: 0,
originalEndLineNumber: 0,
originalStartColumn: 0,
originalStartLineNumber: 0
}]
}]
};
}
var diffResult = computeDiff(this.original, this.modified, this.continueLineDiff, this.shouldMakePrettyDiff);
var rawChanges = diffResult.changes;
var quitEarly = diffResult.quitEarly;
// The diff is always computed with ignoring trim whitespace
// This ensures we get the prettiest diff
if (this.shouldIgnoreTrimWhitespace) {
var lineChanges = [];
for (var i = 0, length_3 = rawChanges.length; i < length_3; i++) {
lineChanges.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, rawChanges[i], this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
}
return {
quitEarly: quitEarly,
changes: lineChanges
};
}
// Need to post-process and introduce changes where the trim whitespace is different
// Note that we are looping starting at -1 to also cover the lines before the first change
var result = [];
var originalLineIndex = 0;
var modifiedLineIndex = 0;
for (var i = -1 /* !!!! */, len = rawChanges.length; i < len; i++) {
var nextChange = (i + 1 < len ? rawChanges[i + 1] : null);
var originalStop = (nextChange ? nextChange.originalStart : this.originalLines.length);
var modifiedStop = (nextChange ? nextChange.modifiedStart : this.modifiedLines.length);
while (originalLineIndex < originalStop && modifiedLineIndex < modifiedStop) {
var originalLine = this.originalLines[originalLineIndex];
var modifiedLine = this.modifiedLines[modifiedLineIndex];
if (originalLine !== modifiedLine) {
// These lines differ only in trim whitespace
// Check the leading whitespace
{
var originalStartColumn = getFirstNonBlankColumn(originalLine, 1);
var modifiedStartColumn = getFirstNonBlankColumn(modifiedLine, 1);
while (originalStartColumn > 1 && modifiedStartColumn > 1) {
var originalChar = originalLine.charCodeAt(originalStartColumn - 2);
var modifiedChar = modifiedLine.charCodeAt(modifiedStartColumn - 2);
if (originalChar !== modifiedChar) {
break;
}
originalStartColumn--;
modifiedStartColumn--;
}
if (originalStartColumn > 1 || modifiedStartColumn > 1) {
this._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, 1, originalStartColumn, modifiedLineIndex + 1, 1, modifiedStartColumn);
}
}
// Check the trailing whitespace
{
var originalEndColumn = getLastNonBlankColumn(originalLine, 1);
var modifiedEndColumn = getLastNonBlankColumn(modifiedLine, 1);
var originalMaxColumn = originalLine.length + 1;
var modifiedMaxColumn = modifiedLine.length + 1;
while (originalEndColumn < originalMaxColumn && modifiedEndColumn < modifiedMaxColumn) {
var originalChar = originalLine.charCodeAt(originalEndColumn - 1);
var modifiedChar = originalLine.charCodeAt(modifiedEndColumn - 1);
if (originalChar !== modifiedChar) {
break;
}
originalEndColumn++;
modifiedEndColumn++;
}
if (originalEndColumn < originalMaxColumn || modifiedEndColumn < modifiedMaxColumn) {
this._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, originalEndColumn, originalMaxColumn, modifiedLineIndex + 1, modifiedEndColumn, modifiedMaxColumn);
}
}
}
originalLineIndex++;
modifiedLineIndex++;
}
if (nextChange) {
// Emit the actual change
result.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, nextChange, this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
originalLineIndex += nextChange.originalLength;
modifiedLineIndex += nextChange.modifiedLength;
}
}
return {
quitEarly: quitEarly,
changes: result
};
};
DiffComputer.prototype._pushTrimWhitespaceCharChange = function (result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
if (this._mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn)) {
// Merged into previous
return;
}
var charChanges = undefined;
if (this.shouldComputeCharChanges) {
charChanges = [new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn)];
}
result.push(new LineChange(originalLineNumber, originalLineNumber, modifiedLineNumber, modifiedLineNumber, charChanges));
};
DiffComputer.prototype._mergeTrimWhitespaceCharChange = function (result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
var len = result.length;
if (len === 0) {
return false;
}
var prevChange = result[len - 1];
if (prevChange.originalEndLineNumber === 0 || prevChange.modifiedEndLineNumber === 0) {
// Don't merge with inserts/deletes
return false;
}
if (prevChange.originalEndLineNumber + 1 === originalLineNumber && prevChange.modifiedEndLineNumber + 1 === modifiedLineNumber) {
prevChange.originalEndLineNumber = originalLineNumber;
prevChange.modifiedEndLineNumber = modifiedLineNumber;
if (this.shouldComputeCharChanges && prevChange.charChanges) {
prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
}
return true;
}
return false;
};
return DiffComputer;
}());
exports.DiffComputer = DiffComputer;
function getFirstNonBlankColumn(txt, defaultValue) {
var r = strings.firstNonWhitespaceIndex(txt);
if (r === -1) {
return defaultValue;
}
return r + 1;
}
function getLastNonBlankColumn(txt, defaultValue) {
var r = strings.lastNonWhitespaceIndex(txt);
if (r === -1) {
return defaultValue;
}
return r + 2;
}
function createContinueProcessingPredicate(maximumRuntime) {
if (maximumRuntime === 0) {
return function () { return true; };
}
var startTime = Date.now();
return function () {
return Date.now() - startTime < maximumRuntime;
};
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[190/*vs/editor/common/editorAction*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var InternalEditorAction = /** @class */ (function () {
function InternalEditorAction(id, label, alias, precondition, run, contextKeyService) {
this.id = id;
this.label = label;
this.alias = alias;
this._precondition = precondition;
this._run = run;
this._contextKeyService = contextKeyService;
}
InternalEditorAction.prototype.isSupported = function () {
return this._contextKeyService.contextMatchesRules(this._precondition);
};
InternalEditorAction.prototype.run = function () {
if (!this.isSupported()) {
return Promise.resolve(undefined);
}
var r = this._run();
return r ? r : Promise.resolve(undefined);
};
return InternalEditorAction;
}());
exports.InternalEditorAction = InternalEditorAction;
});
define(__m[68/*vs/editor/common/editorCommon*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @internal
*/
function isThemeColor(o) {
return o && typeof o.id === 'string';
}
exports.isThemeColor = isThemeColor;
/**
* The type of the `IEditor`.
*/
exports.EditorType = {
ICodeEditor: 'vs.editor.ICodeEditor',
IDiffEditor: 'vs.editor.IDiffEditor'
};
/**
* Built-in commands.
* @internal
*/
exports.Handler = {
ExecuteCommand: 'executeCommand',
ExecuteCommands: 'executeCommands',
Type: 'type',
ReplacePreviousChar: 'replacePreviousChar',
CompositionStart: 'compositionStart',
CompositionEnd: 'compositionEnd',
Paste: 'paste',
Cut: 'cut',
Undo: 'undo',
Redo: 'redo',
};
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[108/*vs/editor/browser/editorBrowser*/], __M([0/*require*/,1/*exports*/,68/*vs/editor/common/editorCommon*/]), function (require, exports, editorCommon) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
*@internal
*/
function isCodeEditor(thing) {
if (thing && typeof thing.getEditorType === 'function') {
return thing.getEditorType() === editorCommon.EditorType.ICodeEditor;
}
else {
return false;
}
}
exports.isCodeEditor = isCodeEditor;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[48/*vs/editor/common/model*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Vertical Lane in the overview ruler of the editor.
*/
var OverviewRulerLane;
(function (OverviewRulerLane) {
OverviewRulerLane[OverviewRulerLane["Left"] = 1] = "Left";
OverviewRulerLane[OverviewRulerLane["Center"] = 2] = "Center";
OverviewRulerLane[OverviewRulerLane["Right"] = 4] = "Right";
OverviewRulerLane[OverviewRulerLane["Full"] = 7] = "Full";
})(OverviewRulerLane = exports.OverviewRulerLane || (exports.OverviewRulerLane = {}));
/**
* Position in the minimap to render the decoration.
*/
var MinimapPosition;
(function (MinimapPosition) {
MinimapPosition[MinimapPosition["Inline"] = 1] = "Inline";
MinimapPosition[MinimapPosition["Gutter"] = 2] = "Gutter";
})(MinimapPosition = exports.MinimapPosition || (exports.MinimapPosition = {}));
var TextModelResolvedOptions = /** @class */ (function () {
/**
* @internal
*/
function TextModelResolvedOptions(src) {
this.tabSize = Math.max(1, src.tabSize | 0);
this.indentSize = src.tabSize | 0;
this.insertSpaces = Boolean(src.insertSpaces);
this.defaultEOL = src.defaultEOL | 0;
this.trimAutoWhitespace = Boolean(src.trimAutoWhitespace);
}
/**
* @internal
*/
TextModelResolvedOptions.prototype.equals = function (other) {
return (this.tabSize === other.tabSize
&& this.indentSize === other.indentSize
&& this.insertSpaces === other.insertSpaces
&& this.defaultEOL === other.defaultEOL
&& this.trimAutoWhitespace === other.trimAutoWhitespace);
};
/**
* @internal
*/
TextModelResolvedOptions.prototype.createChangeEvent = function (newOpts) {
return {
tabSize: this.tabSize !== newOpts.tabSize,
indentSize: this.indentSize !== newOpts.indentSize,
insertSpaces: this.insertSpaces !== newOpts.insertSpaces,
trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace,
};
};
return TextModelResolvedOptions;
}());
exports.TextModelResolvedOptions = TextModelResolvedOptions;
var FindMatch = /** @class */ (function () {
/**
* @internal
*/
function FindMatch(range, matches) {
this.range = range;
this.matches = matches;
}
return FindMatch;
}());
exports.FindMatch = FindMatch;
/**
* @internal
*/
var ApplyEditsResult = /** @class */ (function () {
function ApplyEditsResult(reverseEdits, changes, trimAutoWhitespaceLineNumbers) {
this.reverseEdits = reverseEdits;
this.changes = changes;
this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers;
}
return ApplyEditsResult;
}());
exports.ApplyEditsResult = ApplyEditsResult;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[342/*vs/editor/common/model/editStack*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/]), function (require, exports, errors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var EditStackElement = /** @class */ (function () {
function EditStackElement(beforeVersionId, beforeCursorState) {
this.beforeVersionId = beforeVersionId;
this.beforeCursorState = beforeCursorState;
this.afterCursorState = null;
this.afterVersionId = -1;
this.editOperations = [];
}
EditStackElement.prototype.undo = function (model) {
// Apply all operations in reverse order
for (var i = this.editOperations.length - 1; i >= 0; i--) {
this.editOperations[i] = {
operations: model.applyEdits(this.editOperations[i].operations)
};
}
};
EditStackElement.prototype.redo = function (model) {
// Apply all operations
for (var i = 0; i < this.editOperations.length; i++) {
this.editOperations[i] = {
operations: model.applyEdits(this.editOperations[i].operations)
};
}
};
return EditStackElement;
}());
function getModelEOL(model) {
var eol = model.getEOL();
if (eol === '\n') {
return 0 /* LF */;
}
else {
return 1 /* CRLF */;
}
}
var EOLStackElement = /** @class */ (function () {
function EOLStackElement(beforeVersionId, setEOL) {
this.beforeVersionId = beforeVersionId;
this.beforeCursorState = null;
this.afterCursorState = null;
this.afterVersionId = -1;
this.eol = setEOL;
}
EOLStackElement.prototype.undo = function (model) {
var redoEOL = getModelEOL(model);
model.setEOL(this.eol);
this.eol = redoEOL;
};
EOLStackElement.prototype.redo = function (model) {
var undoEOL = getModelEOL(model);
model.setEOL(this.eol);
this.eol = undoEOL;
};
return EOLStackElement;
}());
var EditStack = /** @class */ (function () {
function EditStack(model) {
this.model = model;
this.currentOpenStackElement = null;
this.past = [];
this.future = [];
}
EditStack.prototype.pushStackElement = function () {
if (this.currentOpenStackElement !== null) {
this.past.push(this.currentOpenStackElement);
this.currentOpenStackElement = null;
}
};
EditStack.prototype.clear = function () {
this.currentOpenStackElement = null;
this.past = [];
this.future = [];
};
EditStack.prototype.pushEOL = function (eol) {
// No support for parallel universes :(
this.future = [];
if (this.currentOpenStackElement) {
this.pushStackElement();
}
var prevEOL = getModelEOL(this.model);
var stackElement = new EOLStackElement(this.model.getAlternativeVersionId(), prevEOL);
this.model.setEOL(eol);
stackElement.afterVersionId = this.model.getVersionId();
this.currentOpenStackElement = stackElement;
this.pushStackElement();
};
EditStack.prototype.pushEditOperation = function (beforeCursorState, editOperations, cursorStateComputer) {
// No support for parallel universes :(
this.future = [];
var stackElement = null;
if (this.currentOpenStackElement) {
if (this.currentOpenStackElement instanceof EditStackElement) {
stackElement = this.currentOpenStackElement;
}
else {
this.pushStackElement();
}
}
if (!this.currentOpenStackElement) {
stackElement = new EditStackElement(this.model.getAlternativeVersionId(), beforeCursorState);
this.currentOpenStackElement = stackElement;
}
var inverseEditOperation = {
operations: this.model.applyEdits(editOperations)
};
stackElement.editOperations.push(inverseEditOperation);
stackElement.afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperation.operations);
stackElement.afterVersionId = this.model.getVersionId();
return stackElement.afterCursorState;
};
EditStack._computeCursorState = function (cursorStateComputer, inverseEditOperations) {
try {
return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;
}
catch (e) {
errors_1.onUnexpectedError(e);
return null;
}
};
EditStack.prototype.undo = function () {
this.pushStackElement();
if (this.past.length > 0) {
var pastStackElement = this.past.pop();
try {
pastStackElement.undo(this.model);
}
catch (e) {
errors_1.onUnexpectedError(e);
this.clear();
return null;
}
this.future.push(pastStackElement);
return {
selections: pastStackElement.beforeCursorState,
recordedVersionId: pastStackElement.beforeVersionId
};
}
return null;
};
EditStack.prototype.canUndo = function () {
return (this.past.length > 0) || this.currentOpenStackElement !== null;
};
EditStack.prototype.redo = function () {
if (this.future.length > 0) {
var futureStackElement = this.future.pop();
try {
futureStackElement.redo(this.model);
}
catch (e) {
errors_1.onUnexpectedError(e);
this.clear();
return null;
}
this.past.push(futureStackElement);
return {
selections: futureStackElement.afterCursorState,
recordedVersionId: futureStackElement.afterVersionId
};
}
return null;
};
EditStack.prototype.canRedo = function () {
return (this.future.length > 0);
};
return EditStack;
}());
exports.EditStack = EditStack;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[343/*vs/editor/common/model/indentationGuesser*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SpacesDiffResult = /** @class */ (function () {
function SpacesDiffResult() {
this.spacesDiff = 0;
this.looksLikeAlignment = false;
}
return SpacesDiffResult;
}());
/**
* Compute the diff in spaces between two line's indentation.
*/
function spacesDiff(a, aLength, b, bLength, result) {
result.spacesDiff = 0;
result.looksLikeAlignment = false;
// This can go both ways (e.g.):
// - a: "\t"
// - b: "\t "
// => This should count 1 tab and 4 spaces
var i;
for (i = 0; i < aLength && i < bLength; i++) {
var aCharCode = a.charCodeAt(i);
var bCharCode = b.charCodeAt(i);
if (aCharCode !== bCharCode) {
break;
}
}
var aSpacesCnt = 0, aTabsCount = 0;
for (var j = i; j < aLength; j++) {
var aCharCode = a.charCodeAt(j);
if (aCharCode === 32 /* Space */) {
aSpacesCnt++;
}
else {
aTabsCount++;
}
}
var bSpacesCnt = 0, bTabsCount = 0;
for (var j = i; j < bLength; j++) {
var bCharCode = b.charCodeAt(j);
if (bCharCode === 32 /* Space */) {
bSpacesCnt++;
}
else {
bTabsCount++;
}
}
if (aSpacesCnt > 0 && aTabsCount > 0) {
return;
}
if (bSpacesCnt > 0 && bTabsCount > 0) {
return;
}
var tabsDiff = Math.abs(aTabsCount - bTabsCount);
var spacesDiff = Math.abs(aSpacesCnt - bSpacesCnt);
if (tabsDiff === 0) {
// check if the indentation difference might be caused by alignment reasons
// sometime folks like to align their code, but this should not be used as a hint
result.spacesDiff = spacesDiff;
if (spacesDiff > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a.length && bSpacesCnt < b.length) {
if (b.charCodeAt(bSpacesCnt) !== 32 /* Space */ && a.charCodeAt(bSpacesCnt - 1) === 32 /* Space */) {
if (a.charCodeAt(a.length - 1) === 44 /* Comma */) {
// This looks like an alignment desire: e.g.
// const a = b + c,
// d = b - c;
result.looksLikeAlignment = true;
}
}
}
return;
}
if (spacesDiff % tabsDiff === 0) {
result.spacesDiff = spacesDiff / tabsDiff;
return;
}
}
function guessIndentation(source, defaultTabSize, defaultInsertSpaces) {
// Look at most at the first 10k lines
var linesCount = Math.min(source.getLineCount(), 10000);
var linesIndentedWithTabsCount = 0; // number of lines that contain at least one tab in indentation
var linesIndentedWithSpacesCount = 0; // number of lines that contain only spaces in indentation
var previousLineText = ''; // content of latest line that contained non-whitespace chars
var previousLineIndentation = 0; // index at which latest line contained the first non-whitespace char
var ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7]; // prefer even guesses for `tabSize`, limit to [2, 8].
var MAX_ALLOWED_TAB_SIZE_GUESS = 8; // max(ALLOWED_TAB_SIZE_GUESSES) = 8
var spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores
var tmp = new SpacesDiffResult();
for (var lineNumber = 1; lineNumber <= linesCount; lineNumber++) {
var currentLineLength = source.getLineLength(lineNumber);
var currentLineText = source.getLineContent(lineNumber);
// if the text buffer is chunk based, so long lines are cons-string, v8 will flattern the string when we check charCode.
// checking charCode on chunks directly is cheaper.
var useCurrentLineText = (currentLineLength <= 65536);
var currentLineHasContent = false; // does `currentLineText` contain non-whitespace chars
var currentLineIndentation = 0; // index at which `currentLineText` contains the first non-whitespace char
var currentLineSpacesCount = 0; // count of spaces found in `currentLineText` indentation
var currentLineTabsCount = 0; // count of tabs found in `currentLineText` indentation
for (var j = 0, lenJ = currentLineLength; j < lenJ; j++) {
var charCode = (useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j));
if (charCode === 9 /* Tab */) {
currentLineTabsCount++;
}
else if (charCode === 32 /* Space */) {
currentLineSpacesCount++;
}
else {
// Hit non whitespace character on this line
currentLineHasContent = true;
currentLineIndentation = j;
break;
}
}
// Ignore empty or only whitespace lines
if (!currentLineHasContent) {
continue;
}
if (currentLineTabsCount > 0) {
linesIndentedWithTabsCount++;
}
else if (currentLineSpacesCount > 1) {
linesIndentedWithSpacesCount++;
}
spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation, tmp);
if (tmp.looksLikeAlignment) {
// if defaultInsertSpaces === true && the spaces count == tabSize, we may want to count it as valid indentation
//
// - item1
// - item2
//
// otherwise skip this line entirely
//
// const a = 1,
// b = 2;
if (!(defaultInsertSpaces && defaultTabSize === tmp.spacesDiff)) {
continue;
}
}
var currentSpacesDiff = tmp.spacesDiff;
if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) {
spacesDiffCount[currentSpacesDiff]++;
}
previousLineText = currentLineText;
previousLineIndentation = currentLineIndentation;
}
var insertSpaces = defaultInsertSpaces;
if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) {
insertSpaces = (linesIndentedWithTabsCount < linesIndentedWithSpacesCount);
}
var tabSize = defaultTabSize;
// Guess tabSize only if inserting spaces...
if (insertSpaces) {
var tabSizeScore_1 = (insertSpaces ? 0 : 0.1 * linesCount);
// console.log("score threshold: " + tabSizeScore);
ALLOWED_TAB_SIZE_GUESSES.forEach(function (possibleTabSize) {
var possibleTabSizeScore = spacesDiffCount[possibleTabSize];
if (possibleTabSizeScore > tabSizeScore_1) {
tabSizeScore_1 = possibleTabSizeScore;
tabSize = possibleTabSize;
}
});
// Let a tabSize of 2 win even if it is not the maximum
// (only in case 4 was guessed)
if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) {
tabSize = 2;
}
}
// console.log('--------------------------');
// console.log('linesIndentedWithTabsCount: ' + linesIndentedWithTabsCount + ', linesIndentedWithSpacesCount: ' + linesIndentedWithSpacesCount);
// console.log('spacesDiffCount: ' + spacesDiffCount);
// console.log('tabSize: ' + tabSize + ', tabSizeScore: ' + tabSizeScore);
return {
insertSpaces: insertSpaces,
tabSize: tabSize
};
}
exports.guessIndentation = guessIndentation;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[344/*vs/editor/common/model/intervalTree*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getNodeColor(node) {
return ((node.metadata & 1 /* ColorMask */) >>> 0 /* ColorOffset */);
}
exports.getNodeColor = getNodeColor;
function setNodeColor(node, color) {
node.metadata = ((node.metadata & 254 /* ColorMaskInverse */) | (color << 0 /* ColorOffset */));
}
function getNodeIsVisited(node) {
return ((node.metadata & 2 /* IsVisitedMask */) >>> 1 /* IsVisitedOffset */) === 1;
}
function setNodeIsVisited(node, value) {
node.metadata = ((node.metadata & 253 /* IsVisitedMaskInverse */) | ((value ? 1 : 0) << 1 /* IsVisitedOffset */));
}
function getNodeIsForValidation(node) {
return ((node.metadata & 4 /* IsForValidationMask */) >>> 2 /* IsForValidationOffset */) === 1;
}
function setNodeIsForValidation(node, value) {
node.metadata = ((node.metadata & 251 /* IsForValidationMaskInverse */) | ((value ? 1 : 0) << 2 /* IsForValidationOffset */));
}
function getNodeIsInOverviewRuler(node) {
return ((node.metadata & 8 /* IsInOverviewRulerMask */) >>> 3 /* IsInOverviewRulerOffset */) === 1;
}
exports.getNodeIsInOverviewRuler = getNodeIsInOverviewRuler;
function setNodeIsInOverviewRuler(node, value) {
node.metadata = ((node.metadata & 247 /* IsInOverviewRulerMaskInverse */) | ((value ? 1 : 0) << 3 /* IsInOverviewRulerOffset */));
}
function getNodeStickiness(node) {
return ((node.metadata & 48 /* StickinessMask */) >>> 4 /* StickinessOffset */);
}
function _setNodeStickiness(node, stickiness) {
node.metadata = ((node.metadata & 207 /* StickinessMaskInverse */) | (stickiness << 4 /* StickinessOffset */));
}
function getCollapseOnReplaceEdit(node) {
return ((node.metadata & 64 /* CollapseOnReplaceEditMask */) >>> 6 /* CollapseOnReplaceEditOffset */) === 1;
}
function setCollapseOnReplaceEdit(node, value) {
node.metadata = ((node.metadata & 191 /* CollapseOnReplaceEditMaskInverse */) | ((value ? 1 : 0) << 6 /* CollapseOnReplaceEditOffset */));
}
var IntervalNode = /** @class */ (function () {
function IntervalNode(id, start, end) {
this.metadata = 0;
this.parent = this;
this.left = this;
this.right = this;
setNodeColor(this, 1 /* Red */);
this.start = start;
this.end = end;
// FORCE_OVERFLOWING_TEST: this.delta = start;
this.delta = 0;
this.maxEnd = end;
this.id = id;
this.ownerId = 0;
this.options = null;
setNodeIsForValidation(this, false);
_setNodeStickiness(this, 1 /* NeverGrowsWhenTypingAtEdges */);
setNodeIsInOverviewRuler(this, false);
setCollapseOnReplaceEdit(this, false);
this.cachedVersionId = 0;
this.cachedAbsoluteStart = start;
this.cachedAbsoluteEnd = end;
this.range = null;
setNodeIsVisited(this, false);
}
IntervalNode.prototype.reset = function (versionId, start, end, range) {
this.start = start;
this.end = end;
this.maxEnd = end;
this.cachedVersionId = versionId;
this.cachedAbsoluteStart = start;
this.cachedAbsoluteEnd = end;
this.range = range;
};
IntervalNode.prototype.setOptions = function (options) {
this.options = options;
var className = this.options.className;
setNodeIsForValidation(this, (className === "squiggly-error" /* EditorErrorDecoration */
|| className === "squiggly-warning" /* EditorWarningDecoration */
|| className === "squiggly-info" /* EditorInfoDecoration */));
_setNodeStickiness(this, this.options.stickiness);
setNodeIsInOverviewRuler(this, (this.options.overviewRuler && this.options.overviewRuler.color) ? true : false);
setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit);
};
IntervalNode.prototype.setCachedOffsets = function (absoluteStart, absoluteEnd, cachedVersionId) {
if (this.cachedVersionId !== cachedVersionId) {
this.range = null;
}
this.cachedVersionId = cachedVersionId;
this.cachedAbsoluteStart = absoluteStart;
this.cachedAbsoluteEnd = absoluteEnd;
};
IntervalNode.prototype.detach = function () {
this.parent = null;
this.left = null;
this.right = null;
};
return IntervalNode;
}());
exports.IntervalNode = IntervalNode;
exports.SENTINEL = new IntervalNode(null, 0, 0);
exports.SENTINEL.parent = exports.SENTINEL;
exports.SENTINEL.left = exports.SENTINEL;
exports.SENTINEL.right = exports.SENTINEL;
setNodeColor(exports.SENTINEL, 0 /* Black */);
var IntervalTree = /** @class */ (function () {
function IntervalTree() {
this.root = exports.SENTINEL;
this.requestNormalizeDelta = false;
}
IntervalTree.prototype.intervalSearch = function (start, end, filterOwnerId, filterOutValidation, cachedVersionId) {
if (this.root === exports.SENTINEL) {
return [];
}
return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId);
};
IntervalTree.prototype.search = function (filterOwnerId, filterOutValidation, cachedVersionId) {
if (this.root === exports.SENTINEL) {
return [];
}
return search(this, filterOwnerId, filterOutValidation, cachedVersionId);
};
/**
* Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
*/
IntervalTree.prototype.collectNodesFromOwner = function (ownerId) {
return collectNodesFromOwner(this, ownerId);
};
/**
* Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
*/
IntervalTree.prototype.collectNodesPostOrder = function () {
return collectNodesPostOrder(this);
};
IntervalTree.prototype.insert = function (node) {
rbTreeInsert(this, node);
this._normalizeDeltaIfNecessary();
};
IntervalTree.prototype.delete = function (node) {
rbTreeDelete(this, node);
this._normalizeDeltaIfNecessary();
};
IntervalTree.prototype.resolveNode = function (node, cachedVersionId) {
var initialNode = node;
var delta = 0;
while (node !== this.root) {
if (node === node.parent.right) {
delta += node.parent.delta;
}
node = node.parent;
}
var nodeStart = initialNode.start + delta;
var nodeEnd = initialNode.end + delta;
initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
};
IntervalTree.prototype.acceptReplace = function (offset, length, textLength, forceMoveMarkers) {
// Our strategy is to remove all directly impacted nodes, and then add them back to the tree.
// (1) collect all nodes that are intersecting this edit as nodes of interest
var nodesOfInterest = searchForEditing(this, offset, offset + length);
// (2) remove all nodes that are intersecting this edit
for (var i = 0, len = nodesOfInterest.length; i < len; i++) {
var node = nodesOfInterest[i];
rbTreeDelete(this, node);
}
this._normalizeDeltaIfNecessary();
// (3) edit all tree nodes except the nodes of interest
noOverlapReplace(this, offset, offset + length, textLength);
this._normalizeDeltaIfNecessary();
// (4) edit the nodes of interest and insert them back in the tree
for (var i = 0, len = nodesOfInterest.length; i < len; i++) {
var node = nodesOfInterest[i];
node.start = node.cachedAbsoluteStart;
node.end = node.cachedAbsoluteEnd;
nodeAcceptEdit(node, offset, (offset + length), textLength, forceMoveMarkers);
node.maxEnd = node.end;
rbTreeInsert(this, node);
}
this._normalizeDeltaIfNecessary();
};
IntervalTree.prototype._normalizeDeltaIfNecessary = function () {
if (!this.requestNormalizeDelta) {
return;
}
this.requestNormalizeDelta = false;
normalizeDelta(this);
};
return IntervalTree;
}());
exports.IntervalTree = IntervalTree;
//#region Delta Normalization
function normalizeDelta(T) {
var node = T.root;
var delta = 0;
while (node !== exports.SENTINEL) {
if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) {
// go left
node = node.left;
continue;
}
if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
// handle current node
node.start = delta + node.start;
node.end = delta + node.end;
node.delta = 0;
recomputeMaxEnd(node);
setNodeIsVisited(node, true);
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
node = node.parent;
}
setNodeIsVisited(T.root, false);
}
function adjustMarkerBeforeColumn(markerOffset, markerStickToPreviousCharacter, checkOffset, moveSemantics) {
if (markerOffset < checkOffset) {
return true;
}
if (markerOffset > checkOffset) {
return false;
}
if (moveSemantics === 1 /* ForceMove */) {
return false;
}
if (moveSemantics === 2 /* ForceStay */) {
return true;
}
return markerStickToPreviousCharacter;
}
/**
* This is a lot more complicated than strictly necessary to maintain the same behaviour
* as when decorations were implemented using two markers.
*/
function nodeAcceptEdit(node, start, end, textLength, forceMoveMarkers) {
var nodeStickiness = getNodeStickiness(node);
var startStickToPreviousCharacter = (nodeStickiness === 0 /* AlwaysGrowsWhenTypingAtEdges */
|| nodeStickiness === 2 /* GrowsOnlyWhenTypingBefore */);
var endStickToPreviousCharacter = (nodeStickiness === 1 /* NeverGrowsWhenTypingAtEdges */
|| nodeStickiness === 2 /* GrowsOnlyWhenTypingBefore */);
var deletingCnt = (end - start);
var insertingCnt = textLength;
var commonLength = Math.min(deletingCnt, insertingCnt);
var nodeStart = node.start;
var startDone = false;
var nodeEnd = node.end;
var endDone = false;
if (start <= nodeStart && nodeEnd <= end && getCollapseOnReplaceEdit(node)) {
// This edit encompasses the entire decoration range
// and the decoration has asked to become collapsed
node.start = start;
startDone = true;
node.end = start;
endDone = true;
}
{
var moveSemantics = forceMoveMarkers ? 1 /* ForceMove */ : (deletingCnt > 0 ? 2 /* ForceStay */ : 0 /* MarkerDefined */);
if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start, moveSemantics)) {
startDone = true;
}
if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start, moveSemantics)) {
endDone = true;
}
}
if (commonLength > 0 && !forceMoveMarkers) {
var moveSemantics = (deletingCnt > insertingCnt ? 2 /* ForceStay */ : 0 /* MarkerDefined */);
if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start + commonLength, moveSemantics)) {
startDone = true;
}
if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start + commonLength, moveSemantics)) {
endDone = true;
}
}
{
var moveSemantics = forceMoveMarkers ? 1 /* ForceMove */ : 0 /* MarkerDefined */;
if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, end, moveSemantics)) {
node.start = start + insertingCnt;
startDone = true;
}
if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, end, moveSemantics)) {
node.end = start + insertingCnt;
endDone = true;
}
}
// Finish
var deltaColumn = (insertingCnt - deletingCnt);
if (!startDone) {
node.start = Math.max(0, nodeStart + deltaColumn);
}
if (!endDone) {
node.end = Math.max(0, nodeEnd + deltaColumn);
}
if (node.start > node.end) {
node.end = node.start;
}
}
exports.nodeAcceptEdit = nodeAcceptEdit;
function searchForEditing(T, start, end) {
// https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
// Now, it is known that two intervals A and B overlap only when both
// A.low <= B.high and A.high >= B.low. When searching the trees for
// nodes overlapping with a given interval, you can immediately skip:
// a) all nodes to the right of nodes whose low value is past the end of the given interval.
// b) all nodes that have their maximum 'high' value below the start of the given interval.
var node = T.root;
var delta = 0;
var nodeMaxEnd = 0;
var nodeStart = 0;
var nodeEnd = 0;
var result = [];
var resultLen = 0;
while (node !== exports.SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
node = node.parent;
continue;
}
if (!getNodeIsVisited(node.left)) {
// first time seeing this node
nodeMaxEnd = delta + node.maxEnd;
if (nodeMaxEnd < start) {
// cover case b) from above
// there is no need to search this node or its children
setNodeIsVisited(node, true);
continue;
}
if (node.left !== exports.SENTINEL) {
// go left
node = node.left;
continue;
}
}
// handle current node
nodeStart = delta + node.start;
if (nodeStart > end) {
// cover case a) from above
// there is no need to search this node or its right subtree
setNodeIsVisited(node, true);
continue;
}
nodeEnd = delta + node.end;
if (nodeEnd >= start) {
node.setCachedOffsets(nodeStart, nodeEnd, 0);
result[resultLen++] = node;
}
setNodeIsVisited(node, true);
if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
return result;
}
function noOverlapReplace(T, start, end, textLength) {
// https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
// Now, it is known that two intervals A and B overlap only when both
// A.low <= B.high and A.high >= B.low. When searching the trees for
// nodes overlapping with a given interval, you can immediately skip:
// a) all nodes to the right of nodes whose low value is past the end of the given interval.
// b) all nodes that have their maximum 'high' value below the start of the given interval.
var node = T.root;
var delta = 0;
var nodeMaxEnd = 0;
var nodeStart = 0;
var editDelta = (textLength - (end - start));
while (node !== exports.SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
recomputeMaxEnd(node);
node = node.parent;
continue;
}
if (!getNodeIsVisited(node.left)) {
// first time seeing this node
nodeMaxEnd = delta + node.maxEnd;
if (nodeMaxEnd < start) {
// cover case b) from above
// there is no need to search this node or its children
setNodeIsVisited(node, true);
continue;
}
if (node.left !== exports.SENTINEL) {
// go left
node = node.left;
continue;
}
}
// handle current node
nodeStart = delta + node.start;
if (nodeStart > end) {
node.start += editDelta;
node.end += editDelta;
node.delta += editDelta;
if (node.delta < -1073741824 /* MIN_SAFE_DELTA */ || node.delta > 1073741824 /* MAX_SAFE_DELTA */) {
T.requestNormalizeDelta = true;
}
// cover case a) from above
// there is no need to search this node or its right subtree
setNodeIsVisited(node, true);
continue;
}
setNodeIsVisited(node, true);
if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
}
//#endregion
//#region Searching
function collectNodesFromOwner(T, ownerId) {
var node = T.root;
var result = [];
var resultLen = 0;
while (node !== exports.SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
node = node.parent;
continue;
}
if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) {
// go left
node = node.left;
continue;
}
// handle current node
if (node.ownerId === ownerId) {
result[resultLen++] = node;
}
setNodeIsVisited(node, true);
if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
// go right
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
return result;
}
function collectNodesPostOrder(T) {
var node = T.root;
var result = [];
var resultLen = 0;
while (node !== exports.SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
node = node.parent;
continue;
}
if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) {
// go left
node = node.left;
continue;
}
if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
// go right
node = node.right;
continue;
}
// handle current node
result[resultLen++] = node;
setNodeIsVisited(node, true);
}
setNodeIsVisited(T.root, false);
return result;
}
function search(T, filterOwnerId, filterOutValidation, cachedVersionId) {
var node = T.root;
var delta = 0;
var nodeStart = 0;
var nodeEnd = 0;
var result = [];
var resultLen = 0;
while (node !== exports.SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
node = node.parent;
continue;
}
if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) {
// go left
node = node.left;
continue;
}
// handle current node
nodeStart = delta + node.start;
nodeEnd = delta + node.end;
node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
var include = true;
if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
include = false;
}
if (filterOutValidation && getNodeIsForValidation(node)) {
include = false;
}
if (include) {
result[resultLen++] = node;
}
setNodeIsVisited(node, true);
if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
return result;
}
function intervalSearch(T, intervalStart, intervalEnd, filterOwnerId, filterOutValidation, cachedVersionId) {
// https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
// Now, it is known that two intervals A and B overlap only when both
// A.low <= B.high and A.high >= B.low. When searching the trees for
// nodes overlapping with a given interval, you can immediately skip:
// a) all nodes to the right of nodes whose low value is past the end of the given interval.
// b) all nodes that have their maximum 'high' value below the start of the given interval.
var node = T.root;
var delta = 0;
var nodeMaxEnd = 0;
var nodeStart = 0;
var nodeEnd = 0;
var result = [];
var resultLen = 0;
while (node !== exports.SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
node = node.parent;
continue;
}
if (!getNodeIsVisited(node.left)) {
// first time seeing this node
nodeMaxEnd = delta + node.maxEnd;
if (nodeMaxEnd < intervalStart) {
// cover case b) from above
// there is no need to search this node or its children
setNodeIsVisited(node, true);
continue;
}
if (node.left !== exports.SENTINEL) {
// go left
node = node.left;
continue;
}
}
// handle current node
nodeStart = delta + node.start;
if (nodeStart > intervalEnd) {
// cover case a) from above
// there is no need to search this node or its right subtree
setNodeIsVisited(node, true);
continue;
}
nodeEnd = delta + node.end;
if (nodeEnd >= intervalStart) {
// There is overlap
node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
var include = true;
if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
include = false;
}
if (filterOutValidation && getNodeIsForValidation(node)) {
include = false;
}
if (include) {
result[resultLen++] = node;
}
}
setNodeIsVisited(node, true);
if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
return result;
}
//#endregion
//#region Insertion
function rbTreeInsert(T, newNode) {
if (T.root === exports.SENTINEL) {
newNode.parent = exports.SENTINEL;
newNode.left = exports.SENTINEL;
newNode.right = exports.SENTINEL;
setNodeColor(newNode, 0 /* Black */);
T.root = newNode;
return T.root;
}
treeInsert(T, newNode);
recomputeMaxEndWalkToRoot(newNode.parent);
// repair tree
var x = newNode;
while (x !== T.root && getNodeColor(x.parent) === 1 /* Red */) {
if (x.parent === x.parent.parent.left) {
var y = x.parent.parent.right;
if (getNodeColor(y) === 1 /* Red */) {
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(y, 0 /* Black */);
setNodeColor(x.parent.parent, 1 /* Red */);
x = x.parent.parent;
}
else {
if (x === x.parent.right) {
x = x.parent;
leftRotate(T, x);
}
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(x.parent.parent, 1 /* Red */);
rightRotate(T, x.parent.parent);
}
}
else {
var y = x.parent.parent.left;
if (getNodeColor(y) === 1 /* Red */) {
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(y, 0 /* Black */);
setNodeColor(x.parent.parent, 1 /* Red */);
x = x.parent.parent;
}
else {
if (x === x.parent.left) {
x = x.parent;
rightRotate(T, x);
}
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(x.parent.parent, 1 /* Red */);
leftRotate(T, x.parent.parent);
}
}
}
setNodeColor(T.root, 0 /* Black */);
return newNode;
}
function treeInsert(T, z) {
var delta = 0;
var x = T.root;
var zAbsoluteStart = z.start;
var zAbsoluteEnd = z.end;
while (true) {
var cmp = intervalCompare(zAbsoluteStart, zAbsoluteEnd, x.start + delta, x.end + delta);
if (cmp < 0) {
// this node should be inserted to the left
// => it is not affected by the node's delta
if (x.left === exports.SENTINEL) {
z.start -= delta;
z.end -= delta;
z.maxEnd -= delta;
x.left = z;
break;
}
else {
x = x.left;
}
}
else {
// this node should be inserted to the right
// => it is not affected by the node's delta
if (x.right === exports.SENTINEL) {
z.start -= (delta + x.delta);
z.end -= (delta + x.delta);
z.maxEnd -= (delta + x.delta);
x.right = z;
break;
}
else {
delta += x.delta;
x = x.right;
}
}
}
z.parent = x;
z.left = exports.SENTINEL;
z.right = exports.SENTINEL;
setNodeColor(z, 1 /* Red */);
}
//#endregion
//#region Deletion
function rbTreeDelete(T, z) {
var x;
var y;
// RB-DELETE except we don't swap z and y in case c)
// i.e. we always delete what's pointed at by z.
if (z.left === exports.SENTINEL) {
x = z.right;
y = z;
// x's delta is no longer influenced by z's delta
x.delta += z.delta;
if (x.delta < -1073741824 /* MIN_SAFE_DELTA */ || x.delta > 1073741824 /* MAX_SAFE_DELTA */) {
T.requestNormalizeDelta = true;
}
x.start += z.delta;
x.end += z.delta;
}
else if (z.right === exports.SENTINEL) {
x = z.left;
y = z;
}
else {
y = leftest(z.right);
x = y.right;
// y's delta is no longer influenced by z's delta,
// but we don't want to walk the entire right-hand-side subtree of x.
// we therefore maintain z's delta in y, and adjust only x
x.start += y.delta;
x.end += y.delta;
x.delta += y.delta;
if (x.delta < -1073741824 /* MIN_SAFE_DELTA */ || x.delta > 1073741824 /* MAX_SAFE_DELTA */) {
T.requestNormalizeDelta = true;
}
y.start += z.delta;
y.end += z.delta;
y.delta = z.delta;
if (y.delta < -1073741824 /* MIN_SAFE_DELTA */ || y.delta > 1073741824 /* MAX_SAFE_DELTA */) {
T.requestNormalizeDelta = true;
}
}
if (y === T.root) {
T.root = x;
setNodeColor(x, 0 /* Black */);
z.detach();
resetSentinel();
recomputeMaxEnd(x);
T.root.parent = exports.SENTINEL;
return;
}
var yWasRed = (getNodeColor(y) === 1 /* Red */);
if (y === y.parent.left) {
y.parent.left = x;
}
else {
y.parent.right = x;
}
if (y === z) {
x.parent = y.parent;
}
else {
if (y.parent === z) {
x.parent = y;
}
else {
x.parent = y.parent;
}
y.left = z.left;
y.right = z.right;
y.parent = z.parent;
setNodeColor(y, getNodeColor(z));
if (z === T.root) {
T.root = y;
}
else {
if (z === z.parent.left) {
z.parent.left = y;
}
else {
z.parent.right = y;
}
}
if (y.left !== exports.SENTINEL) {
y.left.parent = y;
}
if (y.right !== exports.SENTINEL) {
y.right.parent = y;
}
}
z.detach();
if (yWasRed) {
recomputeMaxEndWalkToRoot(x.parent);
if (y !== z) {
recomputeMaxEndWalkToRoot(y);
recomputeMaxEndWalkToRoot(y.parent);
}
resetSentinel();
return;
}
recomputeMaxEndWalkToRoot(x);
recomputeMaxEndWalkToRoot(x.parent);
if (y !== z) {
recomputeMaxEndWalkToRoot(y);
recomputeMaxEndWalkToRoot(y.parent);
}
// RB-DELETE-FIXUP
var w;
while (x !== T.root && getNodeColor(x) === 0 /* Black */) {
if (x === x.parent.left) {
w = x.parent.right;
if (getNodeColor(w) === 1 /* Red */) {
setNodeColor(w, 0 /* Black */);
setNodeColor(x.parent, 1 /* Red */);
leftRotate(T, x.parent);
w = x.parent.right;
}
if (getNodeColor(w.left) === 0 /* Black */ && getNodeColor(w.right) === 0 /* Black */) {
setNodeColor(w, 1 /* Red */);
x = x.parent;
}
else {
if (getNodeColor(w.right) === 0 /* Black */) {
setNodeColor(w.left, 0 /* Black */);
setNodeColor(w, 1 /* Red */);
rightRotate(T, w);
w = x.parent.right;
}
setNodeColor(w, getNodeColor(x.parent));
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(w.right, 0 /* Black */);
leftRotate(T, x.parent);
x = T.root;
}
}
else {
w = x.parent.left;
if (getNodeColor(w) === 1 /* Red */) {
setNodeColor(w, 0 /* Black */);
setNodeColor(x.parent, 1 /* Red */);
rightRotate(T, x.parent);
w = x.parent.left;
}
if (getNodeColor(w.left) === 0 /* Black */ && getNodeColor(w.right) === 0 /* Black */) {
setNodeColor(w, 1 /* Red */);
x = x.parent;
}
else {
if (getNodeColor(w.left) === 0 /* Black */) {
setNodeColor(w.right, 0 /* Black */);
setNodeColor(w, 1 /* Red */);
leftRotate(T, w);
w = x.parent.left;
}
setNodeColor(w, getNodeColor(x.parent));
setNodeColor(x.parent, 0 /* Black */);
setNodeColor(w.left, 0 /* Black */);
rightRotate(T, x.parent);
x = T.root;
}
}
}
setNodeColor(x, 0 /* Black */);
resetSentinel();
}
function leftest(node) {
while (node.left !== exports.SENTINEL) {
node = node.left;
}
return node;
}
function resetSentinel() {
exports.SENTINEL.parent = exports.SENTINEL;
exports.SENTINEL.delta = 0; // optional
exports.SENTINEL.start = 0; // optional
exports.SENTINEL.end = 0; // optional
}
//#endregion
//#region Rotations
function leftRotate(T, x) {
var y = x.right; // set y.
y.delta += x.delta; // y's delta is no longer influenced by x's delta
if (y.delta < -1073741824 /* MIN_SAFE_DELTA */ || y.delta > 1073741824 /* MAX_SAFE_DELTA */) {
T.requestNormalizeDelta = true;
}
y.start += x.delta;
y.end += x.delta;
x.right = y.left; // turn y's left subtree into x's right subtree.
if (y.left !== exports.SENTINEL) {
y.left.parent = x;
}
y.parent = x.parent; // link x's parent to y.
if (x.parent === exports.SENTINEL) {
T.root = y;
}
else if (x === x.parent.left) {
x.parent.left = y;
}
else {
x.parent.right = y;
}
y.left = x; // put x on y's left.
x.parent = y;
recomputeMaxEnd(x);
recomputeMaxEnd(y);
}
function rightRotate(T, y) {
var x = y.left;
y.delta -= x.delta;
if (y.delta < -1073741824 /* MIN_SAFE_DELTA */ || y.delta > 1073741824 /* MAX_SAFE_DELTA */) {
T.requestNormalizeDelta = true;
}
y.start -= x.delta;
y.end -= x.delta;
y.left = x.right;
if (x.right !== exports.SENTINEL) {
x.right.parent = y;
}
x.parent = y.parent;
if (y.parent === exports.SENTINEL) {
T.root = x;
}
else if (y === y.parent.right) {
y.parent.right = x;
}
else {
y.parent.left = x;
}
x.right = y;
y.parent = x;
recomputeMaxEnd(y);
recomputeMaxEnd(x);
}
//#endregion
//#region max end computation
function computeMaxEnd(node) {
var maxEnd = node.end;
if (node.left !== exports.SENTINEL) {
var leftMaxEnd = node.left.maxEnd;
if (leftMaxEnd > maxEnd) {
maxEnd = leftMaxEnd;
}
}
if (node.right !== exports.SENTINEL) {
var rightMaxEnd = node.right.maxEnd + node.delta;
if (rightMaxEnd > maxEnd) {
maxEnd = rightMaxEnd;
}
}
return maxEnd;
}
function recomputeMaxEnd(node) {
node.maxEnd = computeMaxEnd(node);
}
exports.recomputeMaxEnd = recomputeMaxEnd;
function recomputeMaxEndWalkToRoot(node) {
while (node !== exports.SENTINEL) {
var maxEnd = computeMaxEnd(node);
if (node.maxEnd === maxEnd) {
// no need to go further
return;
}
node.maxEnd = maxEnd;
node = node.parent;
}
}
//#endregion
//#region utils
function intervalCompare(aStart, aEnd, bStart, bEnd) {
if (aStart === bStart) {
return aEnd - bEnd;
}
return aStart - bStart;
}
exports.intervalCompare = intervalCompare;
});
//#endregion
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[345/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TreeNode = /** @class */ (function () {
function TreeNode(piece, color) {
this.piece = piece;
this.color = color;
this.size_left = 0;
this.lf_left = 0;
this.parent = this;
this.left = this;
this.right = this;
}
TreeNode.prototype.next = function () {
if (this.right !== exports.SENTINEL) {
return leftest(this.right);
}
var node = this;
while (node.parent !== exports.SENTINEL) {
if (node.parent.left === node) {
break;
}
node = node.parent;
}
if (node.parent === exports.SENTINEL) {
return exports.SENTINEL;
}
else {
return node.parent;
}
};
TreeNode.prototype.prev = function () {
if (this.left !== exports.SENTINEL) {
return righttest(this.left);
}
var node = this;
while (node.parent !== exports.SENTINEL) {
if (node.parent.right === node) {
break;
}
node = node.parent;
}
if (node.parent === exports.SENTINEL) {
return exports.SENTINEL;
}
else {
return node.parent;
}
};
TreeNode.prototype.detach = function () {
this.parent = null;
this.left = null;
this.right = null;
};
return TreeNode;
}());
exports.TreeNode = TreeNode;
exports.SENTINEL = new TreeNode(null, 0 /* Black */);
exports.SENTINEL.parent = exports.SENTINEL;
exports.SENTINEL.left = exports.SENTINEL;
exports.SENTINEL.right = exports.SENTINEL;
exports.SENTINEL.color = 0 /* Black */;
function leftest(node) {
while (node.left !== exports.SENTINEL) {
node = node.left;
}
return node;
}
exports.leftest = leftest;
function righttest(node) {
while (node.right !== exports.SENTINEL) {
node = node.right;
}
return node;
}
exports.righttest = righttest;
function calculateSize(node) {
if (node === exports.SENTINEL) {
return 0;
}
return node.size_left + node.piece.length + calculateSize(node.right);
}
exports.calculateSize = calculateSize;
function calculateLF(node) {
if (node === exports.SENTINEL) {
return 0;
}
return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
}
exports.calculateLF = calculateLF;
function resetSentinel() {
exports.SENTINEL.parent = exports.SENTINEL;
}
exports.resetSentinel = resetSentinel;
function leftRotate(tree, x) {
var y = x.right;
// fix size_left
y.size_left += x.size_left + (x.piece ? x.piece.length : 0);
y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
x.right = y.left;
if (y.left !== exports.SENTINEL) {
y.left.parent = x;
}
y.parent = x.parent;
if (x.parent === exports.SENTINEL) {
tree.root = y;
}
else if (x.parent.left === x) {
x.parent.left = y;
}
else {
x.parent.right = y;
}
y.left = x;
x.parent = y;
}
exports.leftRotate = leftRotate;
function rightRotate(tree, y) {
var x = y.left;
y.left = x.right;
if (x.right !== exports.SENTINEL) {
x.right.parent = y;
}
x.parent = y.parent;
// fix size_left
y.size_left -= x.size_left + (x.piece ? x.piece.length : 0);
y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
if (y.parent === exports.SENTINEL) {
tree.root = x;
}
else if (y === y.parent.right) {
y.parent.right = x;
}
else {
y.parent.left = x;
}
x.right = y;
y.parent = x;
}
exports.rightRotate = rightRotate;
function rbDelete(tree, z) {
var x;
var y;
if (z.left === exports.SENTINEL) {
y = z;
x = y.right;
}
else if (z.right === exports.SENTINEL) {
y = z;
x = y.left;
}
else {
y = leftest(z.right);
x = y.right;
}
if (y === tree.root) {
tree.root = x;
// if x is null, we are removing the only node
x.color = 0 /* Black */;
z.detach();
resetSentinel();
tree.root.parent = exports.SENTINEL;
return;
}
var yWasRed = (y.color === 1 /* Red */);
if (y === y.parent.left) {
y.parent.left = x;
}
else {
y.parent.right = x;
}
if (y === z) {
x.parent = y.parent;
recomputeTreeMetadata(tree, x);
}
else {
if (y.parent === z) {
x.parent = y;
}
else {
x.parent = y.parent;
}
// as we make changes to x's hierarchy, update size_left of subtree first
recomputeTreeMetadata(tree, x);
y.left = z.left;
y.right = z.right;
y.parent = z.parent;
y.color = z.color;
if (z === tree.root) {
tree.root = y;
}
else {
if (z === z.parent.left) {
z.parent.left = y;
}
else {
z.parent.right = y;
}
}
if (y.left !== exports.SENTINEL) {
y.left.parent = y;
}
if (y.right !== exports.SENTINEL) {
y.right.parent = y;
}
// update metadata
// we replace z with y, so in this sub tree, the length change is z.item.length
y.size_left = z.size_left;
y.lf_left = z.lf_left;
recomputeTreeMetadata(tree, y);
}
z.detach();
if (x.parent.left === x) {
var newSizeLeft = calculateSize(x);
var newLFLeft = calculateLF(x);
if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) {
var delta = newSizeLeft - x.parent.size_left;
var lf_delta = newLFLeft - x.parent.lf_left;
x.parent.size_left = newSizeLeft;
x.parent.lf_left = newLFLeft;
updateTreeMetadata(tree, x.parent, delta, lf_delta);
}
}
recomputeTreeMetadata(tree, x.parent);
if (yWasRed) {
resetSentinel();
return;
}
// RB-DELETE-FIXUP
var w;
while (x !== tree.root && x.color === 0 /* Black */) {
if (x === x.parent.left) {
w = x.parent.right;
if (w.color === 1 /* Red */) {
w.color = 0 /* Black */;
x.parent.color = 1 /* Red */;
leftRotate(tree, x.parent);
w = x.parent.right;
}
if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {
w.color = 1 /* Red */;
x = x.parent;
}
else {
if (w.right.color === 0 /* Black */) {
w.left.color = 0 /* Black */;
w.color = 1 /* Red */;
rightRotate(tree, w);
w = x.parent.right;
}
w.color = x.parent.color;
x.parent.color = 0 /* Black */;
w.right.color = 0 /* Black */;
leftRotate(tree, x.parent);
x = tree.root;
}
}
else {
w = x.parent.left;
if (w.color === 1 /* Red */) {
w.color = 0 /* Black */;
x.parent.color = 1 /* Red */;
rightRotate(tree, x.parent);
w = x.parent.left;
}
if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {
w.color = 1 /* Red */;
x = x.parent;
}
else {
if (w.left.color === 0 /* Black */) {
w.right.color = 0 /* Black */;
w.color = 1 /* Red */;
leftRotate(tree, w);
w = x.parent.left;
}
w.color = x.parent.color;
x.parent.color = 0 /* Black */;
w.left.color = 0 /* Black */;
rightRotate(tree, x.parent);
x = tree.root;
}
}
}
x.color = 0 /* Black */;
resetSentinel();
}
exports.rbDelete = rbDelete;
function fixInsert(tree, x) {
recomputeTreeMetadata(tree, x);
while (x !== tree.root && x.parent.color === 1 /* Red */) {
if (x.parent === x.parent.parent.left) {
var y = x.parent.parent.right;
if (y.color === 1 /* Red */) {
x.parent.color = 0 /* Black */;
y.color = 0 /* Black */;
x.parent.parent.color = 1 /* Red */;
x = x.parent.parent;
}
else {
if (x === x.parent.right) {
x = x.parent;
leftRotate(tree, x);
}
x.parent.color = 0 /* Black */;
x.parent.parent.color = 1 /* Red */;
rightRotate(tree, x.parent.parent);
}
}
else {
var y = x.parent.parent.left;
if (y.color === 1 /* Red */) {
x.parent.color = 0 /* Black */;
y.color = 0 /* Black */;
x.parent.parent.color = 1 /* Red */;
x = x.parent.parent;
}
else {
if (x === x.parent.left) {
x = x.parent;
rightRotate(tree, x);
}
x.parent.color = 0 /* Black */;
x.parent.parent.color = 1 /* Red */;
leftRotate(tree, x.parent.parent);
}
}
}
tree.root.color = 0 /* Black */;
}
exports.fixInsert = fixInsert;
function updateTreeMetadata(tree, x, delta, lineFeedCntDelta) {
// node length change or line feed count change
while (x !== tree.root && x !== exports.SENTINEL) {
if (x.parent.left === x) {
x.parent.size_left += delta;
x.parent.lf_left += lineFeedCntDelta;
}
x = x.parent;
}
}
exports.updateTreeMetadata = updateTreeMetadata;
function recomputeTreeMetadata(tree, x) {
var delta = 0;
var lf_delta = 0;
if (x === tree.root) {
return;
}
if (delta === 0) {
// go upwards till the node whose left subtree is changed.
while (x !== tree.root && x === x.parent.right) {
x = x.parent;
}
if (x === tree.root) {
// well, it means we add a node to the end (inorder)
return;
}
// x is the node whose right subtree is changed.
x = x.parent;
delta = calculateSize(x.left) - x.size_left;
lf_delta = calculateLF(x.left) - x.lf_left;
x.size_left += delta;
x.lf_left += lf_delta;
}
// go upwards till root. O(logN)
while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) {
if (x.parent.left === x) {
x.parent.size_left += delta;
x.parent.lf_left += lf_delta;
}
x = x.parent;
}
}
exports.recomputeTreeMetadata = recomputeTreeMetadata;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[346/*vs/editor/common/model/textModelEvents*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* An event describing that a model has been reset to a new value.
* @internal
*/
var ModelRawFlush = /** @class */ (function () {
function ModelRawFlush() {
this.changeType = 1 /* Flush */;
}
return ModelRawFlush;
}());
exports.ModelRawFlush = ModelRawFlush;
/**
* An event describing that a line has changed in a model.
* @internal
*/
var ModelRawLineChanged = /** @class */ (function () {
function ModelRawLineChanged(lineNumber, detail) {
this.changeType = 2 /* LineChanged */;
this.lineNumber = lineNumber;
this.detail = detail;
}
return ModelRawLineChanged;
}());
exports.ModelRawLineChanged = ModelRawLineChanged;
/**
* An event describing that line(s) have been deleted in a model.
* @internal
*/
var ModelRawLinesDeleted = /** @class */ (function () {
function ModelRawLinesDeleted(fromLineNumber, toLineNumber) {
this.changeType = 3 /* LinesDeleted */;
this.fromLineNumber = fromLineNumber;
this.toLineNumber = toLineNumber;
}
return ModelRawLinesDeleted;
}());
exports.ModelRawLinesDeleted = ModelRawLinesDeleted;
/**
* An event describing that line(s) have been inserted in a model.
* @internal
*/
var ModelRawLinesInserted = /** @class */ (function () {
function ModelRawLinesInserted(fromLineNumber, toLineNumber, detail) {
this.changeType = 4 /* LinesInserted */;
this.fromLineNumber = fromLineNumber;
this.toLineNumber = toLineNumber;
this.detail = detail;
}
return ModelRawLinesInserted;
}());
exports.ModelRawLinesInserted = ModelRawLinesInserted;
/**
* An event describing that a model has had its EOL changed.
* @internal
*/
var ModelRawEOLChanged = /** @class */ (function () {
function ModelRawEOLChanged() {
this.changeType = 5 /* EOLChanged */;
}
return ModelRawEOLChanged;
}());
exports.ModelRawEOLChanged = ModelRawEOLChanged;
/**
* An event describing a change in the text of a model.
* @internal
*/
var ModelRawContentChangedEvent = /** @class */ (function () {
function ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing) {
this.changes = changes;
this.versionId = versionId;
this.isUndoing = isUndoing;
this.isRedoing = isRedoing;
}
ModelRawContentChangedEvent.prototype.containsEvent = function (type) {
for (var i = 0, len = this.changes.length; i < len; i++) {
var change = this.changes[i];
if (change.changeType === type) {
return true;
}
}
return false;
};
ModelRawContentChangedEvent.merge = function (a, b) {
var changes = [].concat(a.changes).concat(b.changes);
var versionId = b.versionId;
var isUndoing = (a.isUndoing || b.isUndoing);
var isRedoing = (a.isRedoing || b.isRedoing);
return new ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing);
};
return ModelRawContentChangedEvent;
}());
exports.ModelRawContentChangedEvent = ModelRawContentChangedEvent;
/**
* @internal
*/
var InternalModelContentChangeEvent = /** @class */ (function () {
function InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent) {
this.rawContentChangedEvent = rawContentChangedEvent;
this.contentChangedEvent = contentChangedEvent;
}
InternalModelContentChangeEvent.prototype.merge = function (other) {
var rawContentChangedEvent = ModelRawContentChangedEvent.merge(this.rawContentChangedEvent, other.rawContentChangedEvent);
var contentChangedEvent = InternalModelContentChangeEvent._mergeChangeEvents(this.contentChangedEvent, other.contentChangedEvent);
return new InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent);
};
InternalModelContentChangeEvent._mergeChangeEvents = function (a, b) {
var changes = [].concat(a.changes).concat(b.changes);
var eol = b.eol;
var versionId = b.versionId;
var isUndoing = (a.isUndoing || b.isUndoing);
var isRedoing = (a.isRedoing || b.isRedoing);
var isFlush = (a.isFlush || b.isFlush);
return {
changes: changes,
eol: eol,
versionId: versionId,
isUndoing: isUndoing,
isRedoing: isRedoing,
isFlush: isFlush
};
};
return InternalModelContentChangeEvent;
}());
exports.InternalModelContentChangeEvent = InternalModelContentChangeEvent;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[144/*vs/editor/common/model/textModelSearch*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,89/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,48/*vs/editor/common/model*/]), function (require, exports, strings, wordCharacterClassifier_1, position_1, range_1, model_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LIMIT_FIND_COUNT = 999;
var SearchParams = /** @class */ (function () {
function SearchParams(searchString, isRegex, matchCase, wordSeparators) {
this.searchString = searchString;
this.isRegex = isRegex;
this.matchCase = matchCase;
this.wordSeparators = wordSeparators;
}
SearchParams.prototype.parseSearchRequest = function () {
if (this.searchString === '') {
return null;
}
// Try to create a RegExp out of the params
var multiline;
if (this.isRegex) {
multiline = isMultilineRegexSource(this.searchString);
}
else {
multiline = (this.searchString.indexOf('\n') >= 0);
}
var regex = null;
try {
regex = strings.createRegExp(this.searchString, this.isRegex, {
matchCase: this.matchCase,
wholeWord: false,
multiline: multiline,
global: true,
unicode: true
});
}
catch (err) {
return null;
}
if (!regex) {
return null;
}
var canUseSimpleSearch = (!this.isRegex && !multiline);
if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) {
// casing might make a difference
canUseSimpleSearch = this.matchCase;
}
return new SearchData(regex, this.wordSeparators ? wordCharacterClassifier_1.getMapForWordSeparators(this.wordSeparators) : null, canUseSimpleSearch ? this.searchString : null);
};
return SearchParams;
}());
exports.SearchParams = SearchParams;
function isMultilineRegexSource(searchString) {
if (!searchString || searchString.length === 0) {
return false;
}
for (var i = 0, len = searchString.length; i < len; i++) {
var chCode = searchString.charCodeAt(i);
if (chCode === 92 /* Backslash */) {
// move to next char
i++;
if (i >= len) {
// string ends with a \
break;
}
var nextChCode = searchString.charCodeAt(i);
if (nextChCode === 110 /* n */ || nextChCode === 114 /* r */ || nextChCode === 87 /* W */ || nextChCode === 119 /* w */) {
return true;
}
}
}
return false;
}
exports.isMultilineRegexSource = isMultilineRegexSource;
var SearchData = /** @class */ (function () {
function SearchData(regex, wordSeparators, simpleSearch) {
this.regex = regex;
this.wordSeparators = wordSeparators;
this.simpleSearch = simpleSearch;
}
return SearchData;
}());
exports.SearchData = SearchData;
function createFindMatch(range, rawMatches, captureMatches) {
if (!captureMatches) {
return new model_1.FindMatch(range, null);
}
var matches = [];
for (var i = 0, len = rawMatches.length; i < len; i++) {
matches[i] = rawMatches[i];
}
return new model_1.FindMatch(range, matches);
}
exports.createFindMatch = createFindMatch;
var LineFeedCounter = /** @class */ (function () {
function LineFeedCounter(text) {
var lineFeedsOffsets = [];
var lineFeedsOffsetsLen = 0;
for (var i = 0, textLen = text.length; i < textLen; i++) {
if (text.charCodeAt(i) === 10 /* LineFeed */) {
lineFeedsOffsets[lineFeedsOffsetsLen++] = i;
}
}
this._lineFeedsOffsets = lineFeedsOffsets;
}
LineFeedCounter.prototype.findLineFeedCountBeforeOffset = function (offset) {
var lineFeedsOffsets = this._lineFeedsOffsets;
var min = 0;
var max = lineFeedsOffsets.length - 1;
if (max === -1) {
// no line feeds
return 0;
}
if (offset <= lineFeedsOffsets[0]) {
// before first line feed
return 0;
}
while (min < max) {
var mid = min + ((max - min) / 2 >> 0);
if (lineFeedsOffsets[mid] >= offset) {
max = mid - 1;
}
else {
if (lineFeedsOffsets[mid + 1] >= offset) {
// bingo!
min = mid;
max = mid;
}
else {
min = mid + 1;
}
}
}
return min + 1;
};
return LineFeedCounter;
}());
var TextModelSearch = /** @class */ (function () {
function TextModelSearch() {
}
TextModelSearch.findMatches = function (model, searchParams, searchRange, captureMatches, limitResultCount) {
var searchData = searchParams.parseSearchRequest();
if (!searchData) {
return [];
}
if (searchData.regex.multiline) {
return this._doFindMatchesMultiline(model, searchRange, new Searcher(searchData.wordSeparators, searchData.regex), captureMatches, limitResultCount);
}
return this._doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount);
};
/**
* Multiline search always executes on the lines concatenated with \n.
* We must therefore compensate for the count of \n in case the model is CRLF
*/
TextModelSearch._getMultilineMatchRange = function (model, deltaOffset, text, lfCounter, matchIndex, match0) {
var startOffset;
var lineFeedCountBeforeMatch = 0;
if (lfCounter) {
lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex);
startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch /* add as many \r as there were \n */;
}
else {
startOffset = deltaOffset + matchIndex;
}
var endOffset;
if (lfCounter) {
var lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length);
var lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch;
endOffset = startOffset + match0.length + lineFeedCountInMatch /* add as many \r as there were \n */;
}
else {
endOffset = startOffset + match0.length;
}
var startPosition = model.getPositionAt(startOffset);
var endPosition = model.getPositionAt(endOffset);
return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
};
TextModelSearch._doFindMatchesMultiline = function (model, searchRange, searcher, captureMatches, limitResultCount) {
var deltaOffset = model.getOffsetAt(searchRange.getStartPosition());
// We always execute multiline search over the lines joined with \n
// This makes it that \n will match the EOL for both CRLF and LF models
// We compensate for offset errors in `_getMultilineMatchRange`
var text = model.getValueInRange(searchRange, 1 /* LF */);
var lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null);
var result = [];
var counter = 0;
var m;
searcher.reset(0);
while ((m = searcher.next(text))) {
result[counter++] = createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches);
if (counter >= limitResultCount) {
return result;
}
}
return result;
};
TextModelSearch._doFindMatchesLineByLine = function (model, searchRange, searchData, captureMatches, limitResultCount) {
var result = [];
var resultLen = 0;
// Early case for a search range that starts & stops on the same line number
if (searchRange.startLineNumber === searchRange.endLineNumber) {
var text_1 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1);
resultLen = this._findMatchesInLine(searchData, text_1, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
return result;
}
// Collect results from first line
var text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1);
resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
// Collect results from middle lines
for (var lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) {
resultLen = this._findMatchesInLine(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result, captureMatches, limitResultCount);
}
// Collect results from last line
if (resultLen < limitResultCount) {
var text_2 = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1);
resultLen = this._findMatchesInLine(searchData, text_2, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount);
}
return result;
};
TextModelSearch._findMatchesInLine = function (searchData, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
var wordSeparators = searchData.wordSeparators;
if (!captureMatches && searchData.simpleSearch) {
var searchString = searchData.simpleSearch;
var searchStringLen = searchString.length;
var textLength = text.length;
var lastMatchIndex = -searchStringLen;
while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
if (!wordSeparators || isValidMatch(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) {
result[resultLen++] = new model_1.FindMatch(new range_1.Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
if (resultLen >= limitResultCount) {
return resultLen;
}
}
}
return resultLen;
}
var searcher = new Searcher(searchData.wordSeparators, searchData.regex);
var m;
// Reset regex to search from the beginning
searcher.reset(0);
do {
m = searcher.next(text);
if (m) {
result[resultLen++] = createFindMatch(new range_1.Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
if (resultLen >= limitResultCount) {
return resultLen;
}
}
} while (m);
return resultLen;
};
TextModelSearch.findNextMatch = function (model, searchParams, searchStart, captureMatches) {
var searchData = searchParams.parseSearchRequest();
if (!searchData) {
return null;
}
var searcher = new Searcher(searchData.wordSeparators, searchData.regex);
if (searchData.regex.multiline) {
return this._doFindNextMatchMultiline(model, searchStart, searcher, captureMatches);
}
return this._doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches);
};
TextModelSearch._doFindNextMatchMultiline = function (model, searchStart, searcher, captureMatches) {
var searchTextStart = new position_1.Position(searchStart.lineNumber, 1);
var deltaOffset = model.getOffsetAt(searchTextStart);
var lineCount = model.getLineCount();
// We always execute multiline search over the lines joined with \n
// This makes it that \n will match the EOL for both CRLF and LF models
// We compensate for offset errors in `_getMultilineMatchRange`
var text = model.getValueInRange(new range_1.Range(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)), 1 /* LF */);
var lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null);
searcher.reset(searchStart.column - 1);
var m = searcher.next(text);
if (m) {
return createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches);
}
if (searchStart.lineNumber !== 1 || searchStart.column !== 1) {
// Try again from the top
return this._doFindNextMatchMultiline(model, new position_1.Position(1, 1), searcher, captureMatches);
}
return null;
};
TextModelSearch._doFindNextMatchLineByLine = function (model, searchStart, searcher, captureMatches) {
var lineCount = model.getLineCount();
var startLineNumber = searchStart.lineNumber;
// Look in first line
var text = model.getLineContent(startLineNumber);
var r = this._findFirstMatchInLine(searcher, text, startLineNumber, searchStart.column, captureMatches);
if (r) {
return r;
}
for (var i = 1; i <= lineCount; i++) {
var lineIndex = (startLineNumber + i - 1) % lineCount;
var text_3 = model.getLineContent(lineIndex + 1);
var r_1 = this._findFirstMatchInLine(searcher, text_3, lineIndex + 1, 1, captureMatches);
if (r_1) {
return r_1;
}
}
return null;
};
TextModelSearch._findFirstMatchInLine = function (searcher, text, lineNumber, fromColumn, captureMatches) {
// Set regex to search from column
searcher.reset(fromColumn - 1);
var m = searcher.next(text);
if (m) {
return createFindMatch(new range_1.Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
}
return null;
};
TextModelSearch.findPreviousMatch = function (model, searchParams, searchStart, captureMatches) {
var searchData = searchParams.parseSearchRequest();
if (!searchData) {
return null;
}
var searcher = new Searcher(searchData.wordSeparators, searchData.regex);
if (searchData.regex.multiline) {
return this._doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches);
}
return this._doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches);
};
TextModelSearch._doFindPreviousMatchMultiline = function (model, searchStart, searcher, captureMatches) {
var matches = this._doFindMatchesMultiline(model, new range_1.Range(1, 1, searchStart.lineNumber, searchStart.column), searcher, captureMatches, 10 * LIMIT_FIND_COUNT);
if (matches.length > 0) {
return matches[matches.length - 1];
}
var lineCount = model.getLineCount();
if (searchStart.lineNumber !== lineCount || searchStart.column !== model.getLineMaxColumn(lineCount)) {
// Try again with all content
return this._doFindPreviousMatchMultiline(model, new position_1.Position(lineCount, model.getLineMaxColumn(lineCount)), searcher, captureMatches);
}
return null;
};
TextModelSearch._doFindPreviousMatchLineByLine = function (model, searchStart, searcher, captureMatches) {
var lineCount = model.getLineCount();
var startLineNumber = searchStart.lineNumber;
// Look in first line
var text = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1);
var r = this._findLastMatchInLine(searcher, text, startLineNumber, captureMatches);
if (r) {
return r;
}
for (var i = 1; i <= lineCount; i++) {
var lineIndex = (lineCount + startLineNumber - i - 1) % lineCount;
var text_4 = model.getLineContent(lineIndex + 1);
var r_2 = this._findLastMatchInLine(searcher, text_4, lineIndex + 1, captureMatches);
if (r_2) {
return r_2;
}
}
return null;
};
TextModelSearch._findLastMatchInLine = function (searcher, text, lineNumber, captureMatches) {
var bestResult = null;
var m;
searcher.reset(0);
while ((m = searcher.next(text))) {
bestResult = createFindMatch(new range_1.Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
}
return bestResult;
};
return TextModelSearch;
}());
exports.TextModelSearch = TextModelSearch;
function leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) {
if (matchStartIndex === 0) {
// Match starts at start of string
return true;
}
var charBefore = text.charCodeAt(matchStartIndex - 1);
if (wordSeparators.get(charBefore) !== 0 /* Regular */) {
// The character before the match is a word separator
return true;
}
if (charBefore === 13 /* CarriageReturn */ || charBefore === 10 /* LineFeed */) {
// The character before the match is line break or carriage return.
return true;
}
if (matchLength > 0) {
var firstCharInMatch = text.charCodeAt(matchStartIndex);
if (wordSeparators.get(firstCharInMatch) !== 0 /* Regular */) {
// The first character inside the match is a word separator
return true;
}
}
return false;
}
function rightIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) {
if (matchStartIndex + matchLength === textLength) {
// Match ends at end of string
return true;
}
var charAfter = text.charCodeAt(matchStartIndex + matchLength);
if (wordSeparators.get(charAfter) !== 0 /* Regular */) {
// The character after the match is a word separator
return true;
}
if (charAfter === 13 /* CarriageReturn */ || charAfter === 10 /* LineFeed */) {
// The character after the match is line break or carriage return.
return true;
}
if (matchLength > 0) {
var lastCharInMatch = text.charCodeAt(matchStartIndex + matchLength - 1);
if (wordSeparators.get(lastCharInMatch) !== 0 /* Regular */) {
// The last character in the match is a word separator
return true;
}
}
return false;
}
function isValidMatch(wordSeparators, text, textLength, matchStartIndex, matchLength) {
return (leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength)
&& rightIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength));
}
exports.isValidMatch = isValidMatch;
var Searcher = /** @class */ (function () {
function Searcher(wordSeparators, searchRegex) {
this._wordSeparators = wordSeparators;
this._searchRegex = searchRegex;
this._prevMatchStartIndex = -1;
this._prevMatchLength = 0;
}
Searcher.prototype.reset = function (lastIndex) {
this._searchRegex.lastIndex = lastIndex;
this._prevMatchStartIndex = -1;
this._prevMatchLength = 0;
};
Searcher.prototype.next = function (text) {
var textLength = text.length;
var m;
do {
if (this._prevMatchStartIndex + this._prevMatchLength === textLength) {
// Reached the end of the line
return null;
}
m = this._searchRegex.exec(text);
if (!m) {
return null;
}
var matchStartIndex = m.index;
var matchLength = m[0].length;
if (matchStartIndex === this._prevMatchStartIndex && matchLength === this._prevMatchLength) {
if (matchLength === 0) {
// the search result is an empty string and won't advance `regex.lastIndex`, so `regex.exec` will stuck here
// we attempt to recover from that by advancing by one
this._searchRegex.lastIndex += 1;
continue;
}
// Exit early if the regex matches the same range twice
return null;
}
this._prevMatchStartIndex = matchStartIndex;
this._prevMatchLength = matchLength;
if (!this._wordSeparators || isValidMatch(this._wordSeparators, text, textLength, matchStartIndex, matchLength)) {
return m;
}
} while (m);
return null;
};
return Searcher;
}());
exports.Searcher = Searcher;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[191/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,48/*vs/editor/common/model*/,345/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/,144/*vs/editor/common/model/textModelSearch*/]), function (require, exports, position_1, range_1, model_1, rbTreeBase_1, textModelSearch_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// const lfRegex = new RegExp(/\r\n|\r|\n/g);
exports.AverageBufferSize = 65535;
function createUintArray(arr) {
var r;
if (arr[arr.length - 1] < 65536) {
r = new Uint16Array(arr.length);
}
else {
r = new Uint32Array(arr.length);
}
r.set(arr, 0);
return r;
}
exports.createUintArray = createUintArray;
var LineStarts = /** @class */ (function () {
function LineStarts(lineStarts, cr, lf, crlf, isBasicASCII) {
this.lineStarts = lineStarts;
this.cr = cr;
this.lf = lf;
this.crlf = crlf;
this.isBasicASCII = isBasicASCII;
}
return LineStarts;
}());
exports.LineStarts = LineStarts;
function createLineStartsFast(str, readonly) {
if (readonly === void 0) { readonly = true; }
var r = [0], rLength = 1;
for (var i = 0, len = str.length; i < len; i++) {
var chr = str.charCodeAt(i);
if (chr === 13 /* CarriageReturn */) {
if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {
// \r\n... case
r[rLength++] = i + 2;
i++; // skip \n
}
else {
// \r... case
r[rLength++] = i + 1;
}
}
else if (chr === 10 /* LineFeed */) {
r[rLength++] = i + 1;
}
}
if (readonly) {
return createUintArray(r);
}
else {
return r;
}
}
exports.createLineStartsFast = createLineStartsFast;
function createLineStarts(r, str) {
r.length = 0;
r[0] = 0;
var rLength = 1;
var cr = 0, lf = 0, crlf = 0;
var isBasicASCII = true;
for (var i = 0, len = str.length; i < len; i++) {
var chr = str.charCodeAt(i);
if (chr === 13 /* CarriageReturn */) {
if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {
// \r\n... case
crlf++;
r[rLength++] = i + 2;
i++; // skip \n
}
else {
cr++;
// \r... case
r[rLength++] = i + 1;
}
}
else if (chr === 10 /* LineFeed */) {
lf++;
r[rLength++] = i + 1;
}
else {
if (isBasicASCII) {
if (chr !== 9 /* Tab */ && (chr < 32 || chr > 126)) {
isBasicASCII = false;
}
}
}
}
var result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII);
r.length = 0;
return result;
}
exports.createLineStarts = createLineStarts;
var Piece = /** @class */ (function () {
function Piece(bufferIndex, start, end, lineFeedCnt, length) {
this.bufferIndex = bufferIndex;
this.start = start;
this.end = end;
this.lineFeedCnt = lineFeedCnt;
this.length = length;
}
return Piece;
}());
exports.Piece = Piece;
var StringBuffer = /** @class */ (function () {
function StringBuffer(buffer, lineStarts) {
this.buffer = buffer;
this.lineStarts = lineStarts;
}
return StringBuffer;
}());
exports.StringBuffer = StringBuffer;
var PieceTreeSearchCache = /** @class */ (function () {
function PieceTreeSearchCache(limit) {
this._limit = limit;
this._cache = [];
}
PieceTreeSearchCache.prototype.get = function (offset) {
for (var i = this._cache.length - 1; i >= 0; i--) {
var nodePos = this._cache[i];
if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
return nodePos;
}
}
return null;
};
PieceTreeSearchCache.prototype.get2 = function (lineNumber) {
for (var i = this._cache.length - 1; i >= 0; i--) {
var nodePos = this._cache[i];
if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
return nodePos;
}
}
return null;
};
PieceTreeSearchCache.prototype.set = function (nodePosition) {
if (this._cache.length >= this._limit) {
this._cache.shift();
}
this._cache.push(nodePosition);
};
PieceTreeSearchCache.prototype.valdiate = function (offset) {
var hasInvalidVal = false;
var tmp = this._cache;
for (var i = 0; i < tmp.length; i++) {
var nodePos = tmp[i];
if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
tmp[i] = null;
hasInvalidVal = true;
continue;
}
}
if (hasInvalidVal) {
var newArr = [];
for (var _i = 0, tmp_1 = tmp; _i < tmp_1.length; _i++) {
var entry = tmp_1[_i];
if (entry !== null) {
newArr.push(entry);
}
}
this._cache = newArr;
}
};
return PieceTreeSearchCache;
}());
var PieceTreeBase = /** @class */ (function () {
function PieceTreeBase(chunks, eol, eolNormalized) {
this.create(chunks, eol, eolNormalized);
}
PieceTreeBase.prototype.create = function (chunks, eol, eolNormalized) {
this._buffers = [
new StringBuffer('', [0])
];
this._lastChangeBufferPos = { line: 0, column: 0 };
this.root = rbTreeBase_1.SENTINEL;
this._lineCnt = 1;
this._length = 0;
this._EOL = eol;
this._EOLLength = eol.length;
this._EOLNormalized = eolNormalized;
var lastNode = null;
for (var i = 0, len = chunks.length; i < len; i++) {
if (chunks[i].buffer.length > 0) {
if (!chunks[i].lineStarts) {
chunks[i].lineStarts = createLineStartsFast(chunks[i].buffer);
}
var piece = new Piece(i + 1, { line: 0, column: 0 }, { line: chunks[i].lineStarts.length - 1, column: chunks[i].buffer.length - chunks[i].lineStarts[chunks[i].lineStarts.length - 1] }, chunks[i].lineStarts.length - 1, chunks[i].buffer.length);
this._buffers.push(chunks[i]);
lastNode = this.rbInsertRight(lastNode, piece);
}
}
this._searchCache = new PieceTreeSearchCache(1);
this._lastVisitedLine = { lineNumber: 0, value: '' };
this.computeBufferMetadata();
};
PieceTreeBase.prototype.normalizeEOL = function (eol) {
var _this = this;
var averageBufferSize = exports.AverageBufferSize;
var min = averageBufferSize - Math.floor(averageBufferSize / 3);
var max = min * 2;
var tempChunk = '';
var tempChunkLen = 0;
var chunks = [];
this.iterate(this.root, function (node) {
var str = _this.getNodeContent(node);
var len = str.length;
if (tempChunkLen <= min || tempChunkLen + len < max) {
tempChunk += str;
tempChunkLen += len;
return true;
}
// flush anyways
var text = tempChunk.replace(/\r\n|\r|\n/g, eol);
chunks.push(new StringBuffer(text, createLineStartsFast(text)));
tempChunk = str;
tempChunkLen = len;
return true;
});
if (tempChunkLen > 0) {
var text = tempChunk.replace(/\r\n|\r|\n/g, eol);
chunks.push(new StringBuffer(text, createLineStartsFast(text)));
}
this.create(chunks, eol, true);
};
// #region Buffer API
PieceTreeBase.prototype.getEOL = function () {
return this._EOL;
};
PieceTreeBase.prototype.setEOL = function (newEOL) {
this._EOL = newEOL;
this._EOLLength = this._EOL.length;
this.normalizeEOL(newEOL);
};
PieceTreeBase.prototype.getOffsetAt = function (lineNumber, column) {
var leftLen = 0; // inorder
var x = this.root;
while (x !== rbTreeBase_1.SENTINEL) {
if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left + 1 >= lineNumber) {
x = x.left;
}
else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {
leftLen += x.size_left;
// lineNumber >= 2
var accumualtedValInCurrentIndex = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
return leftLen += accumualtedValInCurrentIndex + column - 1;
}
else {
lineNumber -= x.lf_left + x.piece.lineFeedCnt;
leftLen += x.size_left + x.piece.length;
x = x.right;
}
}
return leftLen;
};
PieceTreeBase.prototype.getPositionAt = function (offset) {
offset = Math.floor(offset);
offset = Math.max(0, offset);
var x = this.root;
var lfCnt = 0;
var originalOffset = offset;
while (x !== rbTreeBase_1.SENTINEL) {
if (x.size_left !== 0 && x.size_left >= offset) {
x = x.left;
}
else if (x.size_left + x.piece.length >= offset) {
var out = this.getIndexOf(x, offset - x.size_left);
lfCnt += x.lf_left + out.index;
if (out.index === 0) {
var lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
var column = originalOffset - lineStartOffset;
return new position_1.Position(lfCnt + 1, column + 1);
}
return new position_1.Position(lfCnt + 1, out.remainder + 1);
}
else {
offset -= x.size_left + x.piece.length;
lfCnt += x.lf_left + x.piece.lineFeedCnt;
if (x.right === rbTreeBase_1.SENTINEL) {
// last node
var lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
var column = originalOffset - offset - lineStartOffset;
return new position_1.Position(lfCnt + 1, column + 1);
}
else {
x = x.right;
}
}
}
return new position_1.Position(1, 1);
};
PieceTreeBase.prototype.getValueInRange = function (range, eol) {
if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
return '';
}
var startPosition = this.nodeAt2(range.startLineNumber, range.startColumn);
var endPosition = this.nodeAt2(range.endLineNumber, range.endColumn);
var value = this.getValueInRange2(startPosition, endPosition);
if (eol) {
if (eol !== this._EOL || !this._EOLNormalized) {
return value.replace(/\r\n|\r|\n/g, eol);
}
if (eol === this.getEOL() && this._EOLNormalized) {
if (eol === '\r\n') {
}
return value;
}
return value.replace(/\r\n|\r|\n/g, eol);
}
return value;
};
PieceTreeBase.prototype.getValueInRange2 = function (startPosition, endPosition) {
if (startPosition.node === endPosition.node) {
var node = startPosition.node;
var buffer_1 = this._buffers[node.piece.bufferIndex].buffer;
var startOffset_1 = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
return buffer_1.substring(startOffset_1 + startPosition.remainder, startOffset_1 + endPosition.remainder);
}
var x = startPosition.node;
var buffer = this._buffers[x.piece.bufferIndex].buffer;
var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
var ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
x = x.next();
while (x !== rbTreeBase_1.SENTINEL) {
var buffer_2 = this._buffers[x.piece.bufferIndex].buffer;
var startOffset_2 = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
if (x === endPosition.node) {
ret += buffer_2.substring(startOffset_2, startOffset_2 + endPosition.remainder);
break;
}
else {
ret += buffer_2.substr(startOffset_2, x.piece.length);
}
x = x.next();
}
return ret;
};
PieceTreeBase.prototype.getLinesContent = function () {
var _this = this;
var lines = [];
var linesLength = 0;
var currentLine = '';
var danglingCR = false;
this.iterate(this.root, function (node) {
if (node === rbTreeBase_1.SENTINEL) {
return true;
}
var piece = node.piece;
var pieceLength = piece.length;
if (pieceLength === 0) {
return true;
}
var buffer = _this._buffers[piece.bufferIndex].buffer;
var lineStarts = _this._buffers[piece.bufferIndex].lineStarts;
var pieceStartLine = piece.start.line;
var pieceEndLine = piece.end.line;
var pieceStartOffset = lineStarts[pieceStartLine] + piece.start.column;
if (danglingCR) {
if (buffer.charCodeAt(pieceStartOffset) === 10 /* LineFeed */) {
// pretend the \n was in the previous piece..
pieceStartOffset++;
pieceLength--;
}
lines[linesLength++] = currentLine;
currentLine = '';
danglingCR = false;
if (pieceLength === 0) {
return true;
}
}
if (pieceStartLine === pieceEndLine) {
// this piece has no new lines
if (!_this._EOLNormalized && buffer.charCodeAt(pieceStartOffset + pieceLength - 1) === 13 /* CarriageReturn */) {
danglingCR = true;
currentLine += buffer.substr(pieceStartOffset, pieceLength - 1);
}
else {
currentLine += buffer.substr(pieceStartOffset, pieceLength);
}
return true;
}
// add the text before the first line start in this piece
currentLine += (_this._EOLNormalized
? buffer.substring(pieceStartOffset, Math.max(pieceStartOffset, lineStarts[pieceStartLine + 1] - _this._EOLLength))
: buffer.substring(pieceStartOffset, lineStarts[pieceStartLine + 1]).replace(/(\r\n|\r|\n)$/, ''));
lines[linesLength++] = currentLine;
for (var line = pieceStartLine + 1; line < pieceEndLine; line++) {
currentLine = (_this._EOLNormalized
? buffer.substring(lineStarts[line], lineStarts[line + 1] - _this._EOLLength)
: buffer.substring(lineStarts[line], lineStarts[line + 1]).replace(/(\r\n|\r|\n)$/, ''));
lines[linesLength++] = currentLine;
}
if (!_this._EOLNormalized && buffer.charCodeAt(lineStarts[pieceEndLine] + piece.end.column - 1) === 13 /* CarriageReturn */) {
danglingCR = true;
if (piece.end.column === 0) {
// The last line ended with a \r, let's undo the push, it will be pushed by next iteration
linesLength--;
}
else {
currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column - 1);
}
}
else {
currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column);
}
return true;
});
if (danglingCR) {
lines[linesLength++] = currentLine;
currentLine = '';
}
lines[linesLength++] = currentLine;
return lines;
};
PieceTreeBase.prototype.getLength = function () {
return this._length;
};
PieceTreeBase.prototype.getLineCount = function () {
return this._lineCnt;
};
PieceTreeBase.prototype.getLineContent = function (lineNumber) {
if (this._lastVisitedLine.lineNumber === lineNumber) {
return this._lastVisitedLine.value;
}
this._lastVisitedLine.lineNumber = lineNumber;
if (lineNumber === this._lineCnt) {
this._lastVisitedLine.value = this.getLineRawContent(lineNumber);
}
else if (this._EOLNormalized) {
this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);
}
else {
this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, '');
}
return this._lastVisitedLine.value;
};
PieceTreeBase.prototype.getLineCharCode = function (lineNumber, index) {
var nodePos = this.nodeAt2(lineNumber, index + 1);
if (nodePos.remainder === nodePos.node.piece.length) {
// the char we want to fetch is at the head of next node.
var matchingNode = nodePos.node.next();
if (!matchingNode) {
return 0;
}
var buffer = this._buffers[matchingNode.piece.bufferIndex];
var startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
return buffer.buffer.charCodeAt(startOffset);
}
else {
var buffer = this._buffers[nodePos.node.piece.bufferIndex];
var startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
var targetOffset = startOffset + nodePos.remainder;
return buffer.buffer.charCodeAt(targetOffset);
}
};
PieceTreeBase.prototype.getLineLength = function (lineNumber) {
if (lineNumber === this.getLineCount()) {
var startOffset = this.getOffsetAt(lineNumber, 1);
return this.getLength() - startOffset;
}
return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength;
};
PieceTreeBase.prototype.findMatchesInNode = function (node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) {
var buffer = this._buffers[node.piece.bufferIndex];
var startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
var start = this.offsetInBuffer(node.piece.bufferIndex, startCursor);
var end = this.offsetInBuffer(node.piece.bufferIndex, endCursor);
var m;
// Reset regex to search from the beginning
var ret = { line: 0, column: 0 };
var searchText;
var offsetInBuffer;
if (searcher._wordSeparators) {
searchText = buffer.buffer.substring(start, end);
offsetInBuffer = function (offset) { return offset + start; };
searcher.reset(-1);
}
else {
searchText = buffer.buffer;
offsetInBuffer = function (offset) { return offset; };
searcher.reset(start);
}
do {
m = searcher.next(searchText);
if (m) {
if (offsetInBuffer(m.index) >= end) {
return resultLen;
}
this.positionInBuffer(node, offsetInBuffer(m.index) - startOffsetInBuffer, ret);
var lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret);
var retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;
var retEndColumn = retStartColumn + m[0].length;
result[resultLen++] = textModelSearch_1.createFindMatch(new range_1.Range(startLineNumber + lineFeedCnt, retStartColumn, startLineNumber + lineFeedCnt, retEndColumn), m, captureMatches);
if (offsetInBuffer(m.index) + m[0].length >= end) {
return resultLen;
}
if (resultLen >= limitResultCount) {
return resultLen;
}
}
} while (m);
return resultLen;
};
PieceTreeBase.prototype.findMatchesLineByLine = function (searchRange, searchData, captureMatches, limitResultCount) {
var result = [];
var resultLen = 0;
var searcher = new textModelSearch_1.Searcher(searchData.wordSeparators, searchData.regex);
var startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn);
if (startPosition === null) {
return [];
}
var endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn);
if (endPosition === null) {
return [];
}
var start = this.positionInBuffer(startPosition.node, startPosition.remainder);
var end = this.positionInBuffer(endPosition.node, endPosition.remainder);
if (startPosition.node === endPosition.node) {
this.findMatchesInNode(startPosition.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
return result;
}
var startLineNumber = searchRange.startLineNumber;
var currentNode = startPosition.node;
while (currentNode !== endPosition.node) {
var lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end);
if (lineBreakCnt >= 1) {
// last line break position
var lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts;
var startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start);
var nextLineStartOffset = lineStarts[start.line + lineBreakCnt];
var startColumn_1 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn_1, start, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result);
if (resultLen >= limitResultCount) {
return result;
}
startLineNumber += lineBreakCnt;
}
var startColumn_2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
// search for the remaining content
if (startLineNumber === searchRange.endLineNumber) {
var text = this.getLineContent(startLineNumber).substring(startColumn_2, searchRange.endColumn - 1);
resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn_2, resultLen, result, captureMatches, limitResultCount);
return result;
}
resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn_2), startLineNumber, startColumn_2, resultLen, result, captureMatches, limitResultCount);
if (resultLen >= limitResultCount) {
return result;
}
startLineNumber++;
startPosition = this.nodeAt2(startLineNumber, 1);
currentNode = startPosition.node;
start = this.positionInBuffer(startPosition.node, startPosition.remainder);
}
if (startLineNumber === searchRange.endLineNumber) {
var startColumn_3 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
var text = this.getLineContent(startLineNumber).substring(startColumn_3, searchRange.endColumn - 1);
resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn_3, resultLen, result, captureMatches, limitResultCount);
return result;
}
var startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
return result;
};
PieceTreeBase.prototype._findMatchesInLine = function (searchData, searcher, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
var wordSeparators = searchData.wordSeparators;
if (!captureMatches && searchData.simpleSearch) {
var searchString = searchData.simpleSearch;
var searchStringLen = searchString.length;
var textLength = text.length;
var lastMatchIndex = -searchStringLen;
while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
if (!wordSeparators || textModelSearch_1.isValidMatch(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) {
result[resultLen++] = new model_1.FindMatch(new range_1.Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
if (resultLen >= limitResultCount) {
return resultLen;
}
}
}
return resultLen;
}
var m;
// Reset regex to search from the beginning
searcher.reset(0);
do {
m = searcher.next(text);
if (m) {
result[resultLen++] = textModelSearch_1.createFindMatch(new range_1.Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
if (resultLen >= limitResultCount) {
return resultLen;
}
}
} while (m);
return resultLen;
};
// #endregion
// #region Piece Table
PieceTreeBase.prototype.insert = function (offset, value, eolNormalized) {
if (eolNormalized === void 0) { eolNormalized = false; }
this._EOLNormalized = this._EOLNormalized && eolNormalized;
this._lastVisitedLine.lineNumber = 0;
this._lastVisitedLine.value = '';
if (this.root !== rbTreeBase_1.SENTINEL) {
var _a = this.nodeAt(offset), node = _a.node, remainder = _a.remainder, nodeStartOffset = _a.nodeStartOffset;
var piece = node.piece;
var bufferIndex = piece.bufferIndex;
var insertPosInBuffer = this.positionInBuffer(node, remainder);
if (node.piece.bufferIndex === 0 &&
piece.end.line === this._lastChangeBufferPos.line &&
piece.end.column === this._lastChangeBufferPos.column &&
(nodeStartOffset + piece.length === offset) &&
value.length < exports.AverageBufferSize) {
// changed buffer
this.appendToNode(node, value);
this.computeBufferMetadata();
return;
}
if (nodeStartOffset === offset) {
this.insertContentToNodeLeft(value, node);
this._searchCache.valdiate(offset);
}
else if (nodeStartOffset + node.piece.length > offset) {
// we are inserting into the middle of a node.
var nodesToDel = [];
var newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer));
if (this.shouldCheckCRLF() && this.endWithCR(value)) {
var headOfRight = this.nodeCharCodeAt(node, remainder);
if (headOfRight === 10 /** \n */) {
var newStart = { line: newRightPiece.start.line + 1, column: 0 };
newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
value += '\n';
}
}
// reuse node for content before insertion point.
if (this.shouldCheckCRLF() && this.startWithLF(value)) {
var tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);
if (tailOfLeft === 13 /** \r */) {
var previousPos = this.positionInBuffer(node, remainder - 1);
this.deleteNodeTail(node, previousPos);
value = '\r' + value;
if (node.piece.length === 0) {
nodesToDel.push(node);
}
}
else {
this.deleteNodeTail(node, insertPosInBuffer);
}
}
else {
this.deleteNodeTail(node, insertPosInBuffer);
}
var newPieces = this.createNewPieces(value);
if (newRightPiece.length > 0) {
this.rbInsertRight(node, newRightPiece);
}
var tmpNode = node;
for (var k = 0; k < newPieces.length; k++) {
tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
}
this.deleteNodes(nodesToDel);
}
else {
this.insertContentToNodeRight(value, node);
}
}
else {
// insert new node
var pieces = this.createNewPieces(value);
var node = this.rbInsertLeft(null, pieces[0]);
for (var k = 1; k < pieces.length; k++) {
node = this.rbInsertRight(node, pieces[k]);
}
}
// todo, this is too brutal. Total line feed count should be updated the same way as lf_left.
this.computeBufferMetadata();
};
PieceTreeBase.prototype.delete = function (offset, cnt) {
this._lastVisitedLine.lineNumber = 0;
this._lastVisitedLine.value = '';
if (cnt <= 0 || this.root === rbTreeBase_1.SENTINEL) {
return;
}
var startPosition = this.nodeAt(offset);
var endPosition = this.nodeAt(offset + cnt);
var startNode = startPosition.node;
var endNode = endPosition.node;
if (startNode === endNode) {
var startSplitPosInBuffer_1 = this.positionInBuffer(startNode, startPosition.remainder);
var endSplitPosInBuffer_1 = this.positionInBuffer(startNode, endPosition.remainder);
if (startPosition.nodeStartOffset === offset) {
if (cnt === startNode.piece.length) { // delete node
var next = startNode.next();
rbTreeBase_1.rbDelete(this, startNode);
this.validateCRLFWithPrevNode(next);
this.computeBufferMetadata();
return;
}
this.deleteNodeHead(startNode, endSplitPosInBuffer_1);
this._searchCache.valdiate(offset);
this.validateCRLFWithPrevNode(startNode);
this.computeBufferMetadata();
return;
}
if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
this.deleteNodeTail(startNode, startSplitPosInBuffer_1);
this.validateCRLFWithNextNode(startNode);
this.computeBufferMetadata();
return;
}
// delete content in the middle, this node will be splitted to nodes
this.shrinkNode(startNode, startSplitPosInBuffer_1, endSplitPosInBuffer_1);
this.computeBufferMetadata();
return;
}
var nodesToDel = [];
var startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
this.deleteNodeTail(startNode, startSplitPosInBuffer);
this._searchCache.valdiate(offset);
if (startNode.piece.length === 0) {
nodesToDel.push(startNode);
}
// update last touched node
var endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
this.deleteNodeHead(endNode, endSplitPosInBuffer);
if (endNode.piece.length === 0) {
nodesToDel.push(endNode);
}
// delete nodes in between
var secondNode = startNode.next();
for (var node = secondNode; node !== rbTreeBase_1.SENTINEL && node !== endNode; node = node.next()) {
nodesToDel.push(node);
}
var prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
this.deleteNodes(nodesToDel);
this.validateCRLFWithNextNode(prev);
this.computeBufferMetadata();
};
PieceTreeBase.prototype.insertContentToNodeLeft = function (value, node) {
// we are inserting content to the beginning of node
var nodesToDel = [];
if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {
// move `\n` to new node.
var piece = node.piece;
var newStart = { line: piece.start.line + 1, column: 0 };
var nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1);
node.piece = nPiece;
value += '\n';
rbTreeBase_1.updateTreeMetadata(this, node, -1, -1);
if (node.piece.length === 0) {
nodesToDel.push(node);
}
}
var newPieces = this.createNewPieces(value);
var newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]);
for (var k = newPieces.length - 2; k >= 0; k--) {
newNode = this.rbInsertLeft(newNode, newPieces[k]);
}
this.validateCRLFWithPrevNode(newNode);
this.deleteNodes(nodesToDel);
};
PieceTreeBase.prototype.insertContentToNodeRight = function (value, node) {
// we are inserting to the right of this node.
if (this.adjustCarriageReturnFromNext(value, node)) {
// move \n to the new node.
value += '\n';
}
var newPieces = this.createNewPieces(value);
var newNode = this.rbInsertRight(node, newPieces[0]);
var tmpNode = newNode;
for (var k = 1; k < newPieces.length; k++) {
tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
}
this.validateCRLFWithPrevNode(newNode);
};
PieceTreeBase.prototype.positionInBuffer = function (node, remainder, ret) {
var piece = node.piece;
var bufferIndex = node.piece.bufferIndex;
var lineStarts = this._buffers[bufferIndex].lineStarts;
var startOffset = lineStarts[piece.start.line] + piece.start.column;
var offset = startOffset + remainder;
// binary search offset between startOffset and endOffset
var low = piece.start.line;
var high = piece.end.line;
var mid = 0;
var midStop = 0;
var midStart = 0;
while (low <= high) {
mid = low + ((high - low) / 2) | 0;
midStart = lineStarts[mid];
if (mid === high) {
break;
}
midStop = lineStarts[mid + 1];
if (offset < midStart) {
high = mid - 1;
}
else if (offset >= midStop) {
low = mid + 1;
}
else {
break;
}
}
if (ret) {
ret.line = mid;
ret.column = offset - midStart;
return null;
}
return {
line: mid,
column: offset - midStart
};
};
PieceTreeBase.prototype.getLineFeedCnt = function (bufferIndex, start, end) {
// we don't need to worry about start: abc\r|\n, or abc|\r, or abc|\n, or abc|\r\n doesn't change the fact that, there is one line break after start.
// now let's take care of end: abc\r|\n, if end is in between \r and \n, we need to add line feed count by 1
if (end.column === 0) {
return end.line - start.line;
}
var lineStarts = this._buffers[bufferIndex].lineStarts;
if (end.line === lineStarts.length - 1) { // it means, there is no \n after end, otherwise, there will be one more lineStart.
return end.line - start.line;
}
var nextLineStartOffset = lineStarts[end.line + 1];
var endOffset = lineStarts[end.line] + end.column;
if (nextLineStartOffset > endOffset + 1) { // there are more than 1 character after end, which means it can't be \n
return end.line - start.line;
}
// endOffset + 1 === nextLineStartOffset
// character at endOffset is \n, so we check the character before first
// if character at endOffset is \r, end.column is 0 and we can't get here.
var previousCharOffset = endOffset - 1; // end.column > 0 so it's okay.
var buffer = this._buffers[bufferIndex].buffer;
if (buffer.charCodeAt(previousCharOffset) === 13) {
return end.line - start.line + 1;
}
else {
return end.line - start.line;
}
};
PieceTreeBase.prototype.offsetInBuffer = function (bufferIndex, cursor) {
var lineStarts = this._buffers[bufferIndex].lineStarts;
return lineStarts[cursor.line] + cursor.column;
};
PieceTreeBase.prototype.deleteNodes = function (nodes) {
for (var i = 0; i < nodes.length; i++) {
rbTreeBase_1.rbDelete(this, nodes[i]);
}
};
PieceTreeBase.prototype.createNewPieces = function (text) {
if (text.length > exports.AverageBufferSize) {
// the content is large, operations like substring, charCode becomes slow
// so here we split it into smaller chunks, just like what we did for CR/LF normalization
var newPieces = [];
while (text.length > exports.AverageBufferSize) {
var lastChar = text.charCodeAt(exports.AverageBufferSize - 1);
var splitText = void 0;
if (lastChar === 13 /* CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
// last character is \r or a high surrogate => keep it back
splitText = text.substring(0, exports.AverageBufferSize - 1);
text = text.substring(exports.AverageBufferSize - 1);
}
else {
splitText = text.substring(0, exports.AverageBufferSize);
text = text.substring(exports.AverageBufferSize);
}
var lineStarts_1 = createLineStartsFast(splitText);
newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts_1.length - 1, column: splitText.length - lineStarts_1[lineStarts_1.length - 1] }, lineStarts_1.length - 1, splitText.length));
this._buffers.push(new StringBuffer(splitText, lineStarts_1));
}
var lineStarts_2 = createLineStartsFast(text);
newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts_2.length - 1, column: text.length - lineStarts_2[lineStarts_2.length - 1] }, lineStarts_2.length - 1, text.length));
this._buffers.push(new StringBuffer(text, lineStarts_2));
return newPieces;
}
var startOffset = this._buffers[0].buffer.length;
var lineStarts = createLineStartsFast(text, false);
var start = this._lastChangeBufferPos;
if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset
&& startOffset !== 0
&& this.startWithLF(text)
&& this.endWithCR(this._buffers[0].buffer) // todo, we can check this._lastChangeBufferPos's column as it's the last one
) {
this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1 };
start = this._lastChangeBufferPos;
for (var i = 0; i < lineStarts.length; i++) {
lineStarts[i] += startOffset + 1;
}
this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
this._buffers[0].buffer += '_' + text;
startOffset += 1;
}
else {
if (startOffset !== 0) {
for (var i = 0; i < lineStarts.length; i++) {
lineStarts[i] += startOffset;
}
}
this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
this._buffers[0].buffer += text;
}
var endOffset = this._buffers[0].buffer.length;
var endIndex = this._buffers[0].lineStarts.length - 1;
var endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
var endPos = { line: endIndex, column: endColumn };
var newPiece = new Piece(0, /** todo@peng */ start, endPos, this.getLineFeedCnt(0, start, endPos), endOffset - startOffset);
this._lastChangeBufferPos = endPos;
return [newPiece];
};
PieceTreeBase.prototype.getLineRawContent = function (lineNumber, endOffset) {
if (endOffset === void 0) { endOffset = 0; }
var x = this.root;
var ret = '';
var cache = this._searchCache.get2(lineNumber);
if (cache) {
x = cache.node;
var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1);
var buffer = this._buffers[x.piece.bufferIndex].buffer;
var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
ret = buffer.substring(startOffset + prevAccumualtedValue, startOffset + x.piece.length);
}
else {
var accumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber);
return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset);
}
}
else {
var nodeStartOffset = 0;
var originalLineNumber = lineNumber;
while (x !== rbTreeBase_1.SENTINEL) {
if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) {
x = x.left;
}
else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
var accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
var buffer = this._buffers[x.piece.bufferIndex].buffer;
var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
nodeStartOffset += x.size_left;
this._searchCache.set({
node: x,
nodeStartOffset: nodeStartOffset,
nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left)
});
return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset);
}
else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
var buffer = this._buffers[x.piece.bufferIndex].buffer;
var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
ret = buffer.substring(startOffset + prevAccumualtedValue, startOffset + x.piece.length);
break;
}
else {
lineNumber -= x.lf_left + x.piece.lineFeedCnt;
nodeStartOffset += x.size_left + x.piece.length;
x = x.right;
}
}
}
// search in order, to find the node contains end column
x = x.next();
while (x !== rbTreeBase_1.SENTINEL) {
var buffer = this._buffers[x.piece.bufferIndex].buffer;
if (x.piece.lineFeedCnt > 0) {
var accumualtedValue = this.getAccumulatedValue(x, 0);
var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
ret += buffer.substring(startOffset, startOffset + accumualtedValue - endOffset);
return ret;
}
else {
var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
ret += buffer.substr(startOffset, x.piece.length);
}
x = x.next();
}
return ret;
};
PieceTreeBase.prototype.computeBufferMetadata = function () {
var x = this.root;
var lfCnt = 1;
var len = 0;
while (x !== rbTreeBase_1.SENTINEL) {
lfCnt += x.lf_left + x.piece.lineFeedCnt;
len += x.size_left + x.piece.length;
x = x.right;
}
this._lineCnt = lfCnt;
this._length = len;
this._searchCache.valdiate(this._length);
};
// #region node operations
PieceTreeBase.prototype.getIndexOf = function (node, accumulatedValue) {
var piece = node.piece;
var pos = this.positionInBuffer(node, accumulatedValue);
var lineCnt = pos.line - piece.start.line;
if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) {
// we are checking the end of this node, so a CRLF check is necessary.
var realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos);
if (realLineCnt !== lineCnt) {
// aha yes, CRLF
return { index: realLineCnt, remainder: 0 };
}
}
return { index: lineCnt, remainder: pos.column };
};
PieceTreeBase.prototype.getAccumulatedValue = function (node, index) {
if (index < 0) {
return 0;
}
var piece = node.piece;
var lineStarts = this._buffers[piece.bufferIndex].lineStarts;
var expectedLineStartIndex = piece.start.line + index + 1;
if (expectedLineStartIndex > piece.end.line) {
return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;
}
else {
return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;
}
};
PieceTreeBase.prototype.deleteNodeTail = function (node, pos) {
var piece = node.piece;
var originalLFCnt = piece.lineFeedCnt;
var originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
var newEnd = pos;
var newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);
var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
var lf_delta = newLineFeedCnt - originalLFCnt;
var size_delta = newEndOffset - originalEndOffset;
var newLength = piece.length + size_delta;
node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
rbTreeBase_1.updateTreeMetadata(this, node, size_delta, lf_delta);
};
PieceTreeBase.prototype.deleteNodeHead = function (node, pos) {
var piece = node.piece;
var originalLFCnt = piece.lineFeedCnt;
var originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
var newStart = pos;
var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
var newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);
var lf_delta = newLineFeedCnt - originalLFCnt;
var size_delta = originalStartOffset - newStartOffset;
var newLength = piece.length + size_delta;
node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
rbTreeBase_1.updateTreeMetadata(this, node, size_delta, lf_delta);
};
PieceTreeBase.prototype.shrinkNode = function (node, start, end) {
var piece = node.piece;
var originalStartPos = piece.start;
var originalEndPos = piece.end;
// old piece, originalStartPos, start
var oldLength = piece.length;
var oldLFCnt = piece.lineFeedCnt;
var newEnd = start;
var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
var newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);
node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
rbTreeBase_1.updateTreeMetadata(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
// new right piece, end, originalEndPos
var newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end));
var newNode = this.rbInsertRight(node, newPiece);
this.validateCRLFWithPrevNode(newNode);
};
PieceTreeBase.prototype.appendToNode = function (node, value) {
if (this.adjustCarriageReturnFromNext(value, node)) {
value += '\n';
}
var hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node);
var startOffset = this._buffers[0].buffer.length;
this._buffers[0].buffer += value;
var lineStarts = createLineStartsFast(value, false);
for (var i = 0; i < lineStarts.length; i++) {
lineStarts[i] += startOffset;
}
if (hitCRLF) {
var prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];
this._buffers[0].lineStarts.pop();
// _lastChangeBufferPos is already wrong
this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset };
}
this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
var endIndex = this._buffers[0].lineStarts.length - 1;
var endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];
var newEnd = { line: endIndex, column: endColumn };
var newLength = node.piece.length + value.length;
var oldLineFeedCnt = node.piece.lineFeedCnt;
var newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd);
var lf_delta = newLineFeedCnt - oldLineFeedCnt;
node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
this._lastChangeBufferPos = newEnd;
rbTreeBase_1.updateTreeMetadata(this, node, value.length, lf_delta);
};
PieceTreeBase.prototype.nodeAt = function (offset) {
var x = this.root;
var cache = this._searchCache.get(offset);
if (cache) {
return {
node: cache.node,
nodeStartOffset: cache.nodeStartOffset,
remainder: offset - cache.nodeStartOffset
};
}
var nodeStartOffset = 0;
while (x !== rbTreeBase_1.SENTINEL) {
if (x.size_left > offset) {
x = x.left;
}
else if (x.size_left + x.piece.length >= offset) {
nodeStartOffset += x.size_left;
var ret = {
node: x,
remainder: offset - x.size_left,
nodeStartOffset: nodeStartOffset
};
this._searchCache.set(ret);
return ret;
}
else {
offset -= x.size_left + x.piece.length;
nodeStartOffset += x.size_left + x.piece.length;
x = x.right;
}
}
return null;
};
PieceTreeBase.prototype.nodeAt2 = function (lineNumber, column) {
var x = this.root;
var nodeStartOffset = 0;
while (x !== rbTreeBase_1.SENTINEL) {
if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) {
x = x.left;
}
else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
var accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
nodeStartOffset += x.size_left;
return {
node: x,
remainder: Math.min(prevAccumualtedValue + column - 1, accumualtedValue),
nodeStartOffset: nodeStartOffset
};
}
else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
if (prevAccumualtedValue + column - 1 <= x.piece.length) {
return {
node: x,
remainder: prevAccumualtedValue + column - 1,
nodeStartOffset: nodeStartOffset
};
}
else {
column -= x.piece.length - prevAccumualtedValue;
break;
}
}
else {
lineNumber -= x.lf_left + x.piece.lineFeedCnt;
nodeStartOffset += x.size_left + x.piece.length;
x = x.right;
}
}
// search in order, to find the node contains position.column
x = x.next();
while (x !== rbTreeBase_1.SENTINEL) {
if (x.piece.lineFeedCnt > 0) {
var accumualtedValue = this.getAccumulatedValue(x, 0);
var nodeStartOffset_1 = this.offsetOfNode(x);
return {
node: x,
remainder: Math.min(column - 1, accumualtedValue),
nodeStartOffset: nodeStartOffset_1
};
}
else {
if (x.piece.length >= column - 1) {
var nodeStartOffset_2 = this.offsetOfNode(x);
return {
node: x,
remainder: column - 1,
nodeStartOffset: nodeStartOffset_2
};
}
else {
column -= x.piece.length;
}
}
x = x.next();
}
return null;
};
PieceTreeBase.prototype.nodeCharCodeAt = function (node, offset) {
if (node.piece.lineFeedCnt < 1) {
return -1;
}
var buffer = this._buffers[node.piece.bufferIndex];
var newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset;
return buffer.buffer.charCodeAt(newOffset);
};
PieceTreeBase.prototype.offsetOfNode = function (node) {
if (!node) {
return 0;
}
var pos = node.size_left;
while (node !== this.root) {
if (node.parent.right === node) {
pos += node.parent.size_left + node.parent.piece.length;
}
node = node.parent;
}
return pos;
};
// #endregion
// #region CRLF
PieceTreeBase.prototype.shouldCheckCRLF = function () {
return !(this._EOLNormalized && this._EOL === '\n');
};
PieceTreeBase.prototype.startWithLF = function (val) {
if (typeof val === 'string') {
return val.charCodeAt(0) === 10;
}
if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) {
return false;
}
var piece = val.piece;
var lineStarts = this._buffers[piece.bufferIndex].lineStarts;
var line = piece.start.line;
var startOffset = lineStarts[line] + piece.start.column;
if (line === lineStarts.length - 1) {
// last line, so there is no line feed at the end of this line
return false;
}
var nextLineOffset = lineStarts[line + 1];
if (nextLineOffset > startOffset + 1) {
return false;
}
return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
};
PieceTreeBase.prototype.endWithCR = function (val) {
if (typeof val === 'string') {
return val.charCodeAt(val.length - 1) === 13;
}
if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) {
return false;
}
return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;
};
PieceTreeBase.prototype.validateCRLFWithPrevNode = function (nextNode) {
if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {
var node = nextNode.prev();
if (this.endWithCR(node)) {
this.fixCRLF(node, nextNode);
}
}
};
PieceTreeBase.prototype.validateCRLFWithNextNode = function (node) {
if (this.shouldCheckCRLF() && this.endWithCR(node)) {
var nextNode = node.next();
if (this.startWithLF(nextNode)) {
this.fixCRLF(node, nextNode);
}
}
};
PieceTreeBase.prototype.fixCRLF = function (prev, next) {
var nodesToDel = [];
// update node
var lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;
var newEnd;
if (prev.piece.end.column === 0) {
// it means, last line ends with \r, not \r\n
newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 };
}
else {
// \r\n
newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 };
}
var prevNewLength = prev.piece.length - 1;
var prevNewLFCnt = prev.piece.lineFeedCnt - 1;
prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
rbTreeBase_1.updateTreeMetadata(this, prev, -1, -1);
if (prev.piece.length === 0) {
nodesToDel.push(prev);
}
// update nextNode
var newStart = { line: next.piece.start.line + 1, column: 0 };
var newLength = next.piece.length - 1;
var newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);
next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
rbTreeBase_1.updateTreeMetadata(this, next, -1, -1);
if (next.piece.length === 0) {
nodesToDel.push(next);
}
// create new piece which contains \r\n
var pieces = this.createNewPieces('\r\n');
this.rbInsertRight(prev, pieces[0]);
// delete empty nodes
for (var i = 0; i < nodesToDel.length; i++) {
rbTreeBase_1.rbDelete(this, nodesToDel[i]);
}
};
PieceTreeBase.prototype.adjustCarriageReturnFromNext = function (value, node) {
if (this.shouldCheckCRLF() && this.endWithCR(value)) {
var nextNode = node.next();
if (this.startWithLF(nextNode)) {
// move `\n` forward
value += '\n';
if (nextNode.piece.length === 1) {
rbTreeBase_1.rbDelete(this, nextNode);
}
else {
var piece = nextNode.piece;
var newStart = { line: piece.start.line + 1, column: 0 };
var newLength = piece.length - 1;
var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
rbTreeBase_1.updateTreeMetadata(this, nextNode, -1, -1);
}
return true;
}
}
return false;
};
// #endregion
// #endregion
// #region Tree operations
PieceTreeBase.prototype.iterate = function (node, callback) {
if (node === rbTreeBase_1.SENTINEL) {
return callback(rbTreeBase_1.SENTINEL);
}
var leftRet = this.iterate(node.left, callback);
if (!leftRet) {
return leftRet;
}
return callback(node) && this.iterate(node.right, callback);
};
PieceTreeBase.prototype.getNodeContent = function (node) {
if (node === rbTreeBase_1.SENTINEL) {
return '';
}
var buffer = this._buffers[node.piece.bufferIndex];
var currentContent;
var piece = node.piece;
var startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
var endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
currentContent = buffer.buffer.substring(startOffset, endOffset);
return currentContent;
};
/**
* node node
* / \ / \
* a b <---- a b
* /
* z
*/
PieceTreeBase.prototype.rbInsertRight = function (node, p) {
var z = new rbTreeBase_1.TreeNode(p, 1 /* Red */);
z.left = rbTreeBase_1.SENTINEL;
z.right = rbTreeBase_1.SENTINEL;
z.parent = rbTreeBase_1.SENTINEL;
z.size_left = 0;
z.lf_left = 0;
var x = this.root;
if (x === rbTreeBase_1.SENTINEL) {
this.root = z;
z.color = 0 /* Black */;
}
else if (node.right === rbTreeBase_1.SENTINEL) {
node.right = z;
z.parent = node;
}
else {
var nextNode = rbTreeBase_1.leftest(node.right);
nextNode.left = z;
z.parent = nextNode;
}
rbTreeBase_1.fixInsert(this, z);
return z;
};
/**
* node node
* / \ / \
* a b ----> a b
* \
* z
*/
PieceTreeBase.prototype.rbInsertLeft = function (node, p) {
var z = new rbTreeBase_1.TreeNode(p, 1 /* Red */);
z.left = rbTreeBase_1.SENTINEL;
z.right = rbTreeBase_1.SENTINEL;
z.parent = rbTreeBase_1.SENTINEL;
z.size_left = 0;
z.lf_left = 0;
if (this.root === rbTreeBase_1.SENTINEL) {
this.root = z;
z.color = 0 /* Black */;
}
else if (node.left === rbTreeBase_1.SENTINEL) {
node.left = z;
z.parent = node;
}
else {
var prevNode = rbTreeBase_1.righttest(node.left); // a
prevNode.right = z;
z.parent = prevNode;
}
rbTreeBase_1.fixInsert(this, z);
return z;
};
return PieceTreeBase;
}());
exports.PieceTreeBase = PieceTreeBase;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[347/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/,48/*vs/editor/common/model*/,191/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/]), function (require, exports, strings, range_1, model_1, pieceTreeBase_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PieceTreeTextBuffer = /** @class */ (function () {
function PieceTreeTextBuffer(chunks, BOM, eol, containsRTL, isBasicASCII, eolNormalized) {
this._BOM = BOM;
this._mightContainNonBasicASCII = !isBasicASCII;
this._mightContainRTL = containsRTL;
this._pieceTree = new pieceTreeBase_1.PieceTreeBase(chunks, eol, eolNormalized);
}
PieceTreeTextBuffer.prototype.mightContainRTL = function () {
return this._mightContainRTL;
};
PieceTreeTextBuffer.prototype.mightContainNonBasicASCII = function () {
return this._mightContainNonBasicASCII;
};
PieceTreeTextBuffer.prototype.getBOM = function () {
return this._BOM;
};
PieceTreeTextBuffer.prototype.getEOL = function () {
return this._pieceTree.getEOL();
};
PieceTreeTextBuffer.prototype.getOffsetAt = function (lineNumber, column) {
return this._pieceTree.getOffsetAt(lineNumber, column);
};
PieceTreeTextBuffer.prototype.getPositionAt = function (offset) {
return this._pieceTree.getPositionAt(offset);
};
PieceTreeTextBuffer.prototype.getRangeAt = function (start, length) {
var end = start + length;
var startPosition = this.getPositionAt(start);
var endPosition = this.getPositionAt(end);
return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
};
PieceTreeTextBuffer.prototype.getValueInRange = function (range, eol) {
if (eol === void 0) { eol = 0 /* TextDefined */; }
if (range.isEmpty()) {
return '';
}
var lineEnding = this._getEndOfLine(eol);
return this._pieceTree.getValueInRange(range, lineEnding);
};
PieceTreeTextBuffer.prototype.getValueLengthInRange = function (range, eol) {
if (eol === void 0) { eol = 0 /* TextDefined */; }
if (range.isEmpty()) {
return 0;
}
if (range.startLineNumber === range.endLineNumber) {
return (range.endColumn - range.startColumn);
}
var startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn);
var endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn);
return endOffset - startOffset;
};
PieceTreeTextBuffer.prototype.getCharacterCountInRange = function (range, eol) {
if (eol === void 0) { eol = 0 /* TextDefined */; }
if (this._mightContainNonBasicASCII) {
// we must count by iterating
var result = 0;
var fromLineNumber = range.startLineNumber;
var toLineNumber = range.endLineNumber;
for (var lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
var lineContent = this.getLineContent(lineNumber);
var fromOffset = (lineNumber === fromLineNumber ? range.startColumn - 1 : 0);
var toOffset = (lineNumber === toLineNumber ? range.endColumn - 1 : lineContent.length);
for (var offset = fromOffset; offset < toOffset; offset++) {
if (strings.isHighSurrogate(lineContent.charCodeAt(offset))) {
result = result + 1;
offset = offset + 1;
}
else {
result = result + 1;
}
}
}
result += this._getEndOfLine(eol).length * (toLineNumber - fromLineNumber);
return result;
}
return this.getValueLengthInRange(range, eol);
};
PieceTreeTextBuffer.prototype.getLength = function () {
return this._pieceTree.getLength();
};
PieceTreeTextBuffer.prototype.getLineCount = function () {
return this._pieceTree.getLineCount();
};
PieceTreeTextBuffer.prototype.getLinesContent = function () {
return this._pieceTree.getLinesContent();
};
PieceTreeTextBuffer.prototype.getLineContent = function (lineNumber) {
return this._pieceTree.getLineContent(lineNumber);
};
PieceTreeTextBuffer.prototype.getLineCharCode = function (lineNumber, index) {
return this._pieceTree.getLineCharCode(lineNumber, index);
};
PieceTreeTextBuffer.prototype.getLineLength = function (lineNumber) {
return this._pieceTree.getLineLength(lineNumber);
};
PieceTreeTextBuffer.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) {
var result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber));
if (result === -1) {
return 0;
}
return result + 1;
};
PieceTreeTextBuffer.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) {
var result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber));
if (result === -1) {
return 0;
}
return result + 2;
};
PieceTreeTextBuffer.prototype._getEndOfLine = function (eol) {
switch (eol) {
case 1 /* LF */:
return '\n';
case 2 /* CRLF */:
return '\r\n';
case 0 /* TextDefined */:
return this.getEOL();
}
throw new Error('Unknown EOL preference');
};
PieceTreeTextBuffer.prototype.setEOL = function (newEOL) {
this._pieceTree.setEOL(newEOL);
};
PieceTreeTextBuffer.prototype.applyEdits = function (rawOperations, recordTrimAutoWhitespace) {
var mightContainRTL = this._mightContainRTL;
var mightContainNonBasicASCII = this._mightContainNonBasicASCII;
var canReduceOperations = true;
var operations = [];
for (var i = 0; i < rawOperations.length; i++) {
var op = rawOperations[i];
if (canReduceOperations && op._isTracked) {
canReduceOperations = false;
}
var validatedRange = op.range;
if (!mightContainRTL && op.text) {
// check if the new inserted text contains RTL
mightContainRTL = strings.containsRTL(op.text);
}
if (!mightContainNonBasicASCII && op.text) {
mightContainNonBasicASCII = !strings.isBasicASCII(op.text);
}
operations[i] = {
sortIndex: i,
identifier: op.identifier || null,
range: validatedRange,
rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn),
rangeLength: this.getValueLengthInRange(validatedRange),
lines: op.text ? op.text.split(/\r\n|\r|\n/) : null,
forceMoveMarkers: Boolean(op.forceMoveMarkers),
isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
};
}
// Sort operations ascending
operations.sort(PieceTreeTextBuffer._sortOpsAscending);
var hasTouchingRanges = false;
for (var i = 0, count = operations.length - 1; i < count; i++) {
var rangeEnd = operations[i].range.getEndPosition();
var nextRangeStart = operations[i + 1].range.getStartPosition();
if (nextRangeStart.isBeforeOrEqual(rangeEnd)) {
if (nextRangeStart.isBefore(rangeEnd)) {
// overlapping ranges
throw new Error('Overlapping ranges are not allowed!');
}
hasTouchingRanges = true;
}
}
if (canReduceOperations) {
operations = this._reduceOperations(operations);
}
// Delta encode operations
var reverseRanges = PieceTreeTextBuffer._getInverseEditRanges(operations);
var newTrimAutoWhitespaceCandidates = [];
for (var i = 0; i < operations.length; i++) {
var op = operations[i];
var reverseRange = reverseRanges[i];
if (recordTrimAutoWhitespace && op.isAutoWhitespaceEdit && op.range.isEmpty()) {
// Record already the future line numbers that might be auto whitespace removal candidates on next edit
for (var lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) {
var currentLineContent = '';
if (lineNumber === reverseRange.startLineNumber) {
currentLineContent = this.getLineContent(op.range.startLineNumber);
if (strings.firstNonWhitespaceIndex(currentLineContent) !== -1) {
continue;
}
}
newTrimAutoWhitespaceCandidates.push({ lineNumber: lineNumber, oldContent: currentLineContent });
}
}
}
var reverseOperations = [];
for (var i = 0; i < operations.length; i++) {
var op = operations[i];
var reverseRange = reverseRanges[i];
reverseOperations[i] = {
sortIndex: op.sortIndex,
identifier: op.identifier,
range: reverseRange,
text: this.getValueInRange(op.range),
forceMoveMarkers: op.forceMoveMarkers
};
}
// Can only sort reverse operations when the order is not significant
if (!hasTouchingRanges) {
reverseOperations.sort(function (a, b) { return a.sortIndex - b.sortIndex; });
}
this._mightContainRTL = mightContainRTL;
this._mightContainNonBasicASCII = mightContainNonBasicASCII;
var contentChanges = this._doApplyEdits(operations);
var trimAutoWhitespaceLineNumbers = null;
if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {
// sort line numbers auto whitespace removal candidates for next edit descending
newTrimAutoWhitespaceCandidates.sort(function (a, b) { return b.lineNumber - a.lineNumber; });
trimAutoWhitespaceLineNumbers = [];
for (var i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) {
var lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber;
if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) {
// Do not have the same line number twice
continue;
}
var prevContent = newTrimAutoWhitespaceCandidates[i].oldContent;
var lineContent = this.getLineContent(lineNumber);
if (lineContent.length === 0 || lineContent === prevContent || strings.firstNonWhitespaceIndex(lineContent) !== -1) {
continue;
}
trimAutoWhitespaceLineNumbers.push(lineNumber);
}
}
return new model_1.ApplyEditsResult(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers);
};
/**
* Transform operations such that they represent the same logic edit,
* but that they also do not cause OOM crashes.
*/
PieceTreeTextBuffer.prototype._reduceOperations = function (operations) {
if (operations.length < 1000) {
// We know from empirical testing that a thousand edits work fine regardless of their shape.
return operations;
}
// At one point, due to how events are emitted and how each operation is handled,
// some operations can trigger a high amount of temporary string allocations,
// that will immediately get edited again.
// e.g. a formatter inserting ridiculous ammounts of \n on a model with a single line
// Therefore, the strategy is to collapse all the operations into a huge single edit operation
return [this._toSingleEditOperation(operations)];
};
PieceTreeTextBuffer.prototype._toSingleEditOperation = function (operations) {
var forceMoveMarkers = false, firstEditRange = operations[0].range, lastEditRange = operations[operations.length - 1].range, entireEditRange = new range_1.Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn), lastEndLineNumber = firstEditRange.startLineNumber, lastEndColumn = firstEditRange.startColumn, result = [];
for (var i = 0, len = operations.length; i < len; i++) {
var operation = operations[i], range = operation.range;
forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;
// (1) -- Push old text
for (var lineNumber = lastEndLineNumber; lineNumber < range.startLineNumber; lineNumber++) {
if (lineNumber === lastEndLineNumber) {
result.push(this.getLineContent(lineNumber).substring(lastEndColumn - 1));
}
else {
result.push('\n');
result.push(this.getLineContent(lineNumber));
}
}
if (range.startLineNumber === lastEndLineNumber) {
result.push(this.getLineContent(range.startLineNumber).substring(lastEndColumn - 1, range.startColumn - 1));
}
else {
result.push('\n');
result.push(this.getLineContent(range.startLineNumber).substring(0, range.startColumn - 1));
}
// (2) -- Push new text
if (operation.lines) {
for (var j = 0, lenJ = operation.lines.length; j < lenJ; j++) {
if (j !== 0) {
result.push('\n');
}
result.push(operation.lines[j]);
}
}
lastEndLineNumber = operation.range.endLineNumber;
lastEndColumn = operation.range.endColumn;
}
return {
sortIndex: 0,
identifier: operations[0].identifier,
range: entireEditRange,
rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
rangeLength: this.getValueLengthInRange(entireEditRange, 0 /* TextDefined */),
lines: result.join('').split('\n'),
forceMoveMarkers: forceMoveMarkers,
isAutoWhitespaceEdit: false
};
};
PieceTreeTextBuffer.prototype._doApplyEdits = function (operations) {
operations.sort(PieceTreeTextBuffer._sortOpsDescending);
var contentChanges = [];
// operations are from bottom to top
for (var i = 0; i < operations.length; i++) {
var op = operations[i];
var startLineNumber = op.range.startLineNumber;
var startColumn = op.range.startColumn;
var endLineNumber = op.range.endLineNumber;
var endColumn = op.range.endColumn;
if (startLineNumber === endLineNumber && startColumn === endColumn && (!op.lines || op.lines.length === 0)) {
// no-op
continue;
}
var deletingLinesCnt = endLineNumber - startLineNumber;
var insertingLinesCnt = (op.lines ? op.lines.length - 1 : 0);
var editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
var text = (op.lines ? op.lines.join(this.getEOL()) : '');
if (text) {
// replacement
this._pieceTree.delete(op.rangeOffset, op.rangeLength);
this._pieceTree.insert(op.rangeOffset, text, true);
}
else {
// deletion
this._pieceTree.delete(op.rangeOffset, op.rangeLength);
}
if (editingLinesCnt < insertingLinesCnt) {
var newLinesContent = [];
for (var j = editingLinesCnt + 1; j <= insertingLinesCnt; j++) {
newLinesContent.push(op.lines[j]);
}
newLinesContent[newLinesContent.length - 1] = this.getLineContent(startLineNumber + insertingLinesCnt - 1);
}
var contentChangeRange = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
contentChanges.push({
range: contentChangeRange,
rangeLength: op.rangeLength,
text: text,
rangeOffset: op.rangeOffset,
forceMoveMarkers: op.forceMoveMarkers
});
}
return contentChanges;
};
PieceTreeTextBuffer.prototype.findMatchesLineByLine = function (searchRange, searchData, captureMatches, limitResultCount) {
return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
};
/**
* Assumes `operations` are validated and sorted ascending
*/
PieceTreeTextBuffer._getInverseEditRanges = function (operations) {
var result = [];
var prevOpEndLineNumber = 0;
var prevOpEndColumn = 0;
var prevOp = null;
for (var i = 0, len = operations.length; i < len; i++) {
var op = operations[i];
var startLineNumber = void 0;
var startColumn = void 0;
if (prevOp) {
if (prevOp.range.endLineNumber === op.range.startLineNumber) {
startLineNumber = prevOpEndLineNumber;
startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn);
}
else {
startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber);
startColumn = op.range.startColumn;
}
}
else {
startLineNumber = op.range.startLineNumber;
startColumn = op.range.startColumn;
}
var resultRange = void 0;
if (op.lines && op.lines.length > 0) {
// the operation inserts something
var lineCount = op.lines.length;
var firstLine = op.lines[0];
var lastLine = op.lines[lineCount - 1];
if (lineCount === 1) {
// single line insert
resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber, startColumn + firstLine.length);
}
else {
// multi line insert
resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, lastLine.length + 1);
}
}
else {
// There is nothing to insert
resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber, startColumn);
}
prevOpEndLineNumber = resultRange.endLineNumber;
prevOpEndColumn = resultRange.endColumn;
result.push(resultRange);
prevOp = op;
}
return result;
};
PieceTreeTextBuffer._sortOpsAscending = function (a, b) {
var r = range_1.Range.compareRangesUsingEnds(a.range, b.range);
if (r === 0) {
return a.sortIndex - b.sortIndex;
}
return r;
};
PieceTreeTextBuffer._sortOpsDescending = function (a, b) {
var r = range_1.Range.compareRangesUsingEnds(a.range, b.range);
if (r === 0) {
return b.sortIndex - a.sortIndex;
}
return -r;
};
return PieceTreeTextBuffer;
}());
exports.PieceTreeTextBuffer = PieceTreeTextBuffer;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[348/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,191/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,347/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/]), function (require, exports, strings, pieceTreeBase_1, pieceTreeTextBuffer_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PieceTreeTextBufferFactory = /** @class */ (function () {
function PieceTreeTextBufferFactory(_chunks, _bom, _cr, _lf, _crlf, _containsRTL, _isBasicASCII, _normalizeEOL) {
this._chunks = _chunks;
this._bom = _bom;
this._cr = _cr;
this._lf = _lf;
this._crlf = _crlf;
this._containsRTL = _containsRTL;
this._isBasicASCII = _isBasicASCII;
this._normalizeEOL = _normalizeEOL;
}
PieceTreeTextBufferFactory.prototype._getEOL = function (defaultEOL) {
var totalEOLCount = this._cr + this._lf + this._crlf;
var totalCRCount = this._cr + this._crlf;
if (totalEOLCount === 0) {
// This is an empty file or a file with precisely one line
return (defaultEOL === 1 /* LF */ ? '\n' : '\r\n');
}
if (totalCRCount > totalEOLCount / 2) {
// More than half of the file contains \r\n ending lines
return '\r\n';
}
// At least one line more ends in \n
return '\n';
};
PieceTreeTextBufferFactory.prototype.create = function (defaultEOL) {
var eol = this._getEOL(defaultEOL);
var chunks = this._chunks;
if (this._normalizeEOL &&
((eol === '\r\n' && (this._cr > 0 || this._lf > 0))
|| (eol === '\n' && (this._cr > 0 || this._crlf > 0)))) {
// Normalize pieces
for (var i = 0, len = chunks.length; i < len; i++) {
var str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol);
var newLineStart = pieceTreeBase_1.createLineStartsFast(str);
chunks[i] = new pieceTreeBase_1.StringBuffer(str, newLineStart);
}
}
return new pieceTreeTextBuffer_1.PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._isBasicASCII, this._normalizeEOL);
};
return PieceTreeTextBufferFactory;
}());
exports.PieceTreeTextBufferFactory = PieceTreeTextBufferFactory;
var PieceTreeTextBufferBuilder = /** @class */ (function () {
function PieceTreeTextBufferBuilder() {
this.chunks = [];
this.BOM = '';
this._hasPreviousChar = false;
this._previousChar = 0;
this._tmpLineStarts = [];
this.cr = 0;
this.lf = 0;
this.crlf = 0;
this.containsRTL = false;
this.isBasicASCII = true;
}
PieceTreeTextBufferBuilder.prototype.acceptChunk = function (chunk) {
if (chunk.length === 0) {
return;
}
if (this.chunks.length === 0) {
if (strings.startsWithUTF8BOM(chunk)) {
this.BOM = strings.UTF8_BOM_CHARACTER;
chunk = chunk.substr(1);
}
}
var lastChar = chunk.charCodeAt(chunk.length - 1);
if (lastChar === 13 /* CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
// last character is \r or a high surrogate => keep it back
this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);
this._hasPreviousChar = true;
this._previousChar = lastChar;
}
else {
this._acceptChunk1(chunk, false);
this._hasPreviousChar = false;
this._previousChar = lastChar;
}
};
PieceTreeTextBufferBuilder.prototype._acceptChunk1 = function (chunk, allowEmptyStrings) {
if (!allowEmptyStrings && chunk.length === 0) {
// Nothing to do
return;
}
if (this._hasPreviousChar) {
this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);
}
else {
this._acceptChunk2(chunk);
}
};
PieceTreeTextBufferBuilder.prototype._acceptChunk2 = function (chunk) {
var lineStarts = pieceTreeBase_1.createLineStarts(this._tmpLineStarts, chunk);
this.chunks.push(new pieceTreeBase_1.StringBuffer(chunk, lineStarts.lineStarts));
this.cr += lineStarts.cr;
this.lf += lineStarts.lf;
this.crlf += lineStarts.crlf;
if (this.isBasicASCII) {
this.isBasicASCII = lineStarts.isBasicASCII;
}
if (!this.isBasicASCII && !this.containsRTL) {
// No need to check if is basic ASCII
this.containsRTL = strings.containsRTL(chunk);
}
};
PieceTreeTextBufferBuilder.prototype.finish = function (normalizeEOL) {
if (normalizeEOL === void 0) { normalizeEOL = true; }
this._finish();
return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, this.containsRTL, this.isBasicASCII, normalizeEOL);
};
PieceTreeTextBufferBuilder.prototype._finish = function () {
if (this.chunks.length === 0) {
this._acceptChunk1('', true);
}
if (this._hasPreviousChar) {
this._hasPreviousChar = false;
// recreate last chunk
var lastChunk = this.chunks[this.chunks.length - 1];
lastChunk.buffer += String.fromCharCode(this._previousChar);
var newLineStarts = pieceTreeBase_1.createLineStartsFast(lastChunk.buffer);
lastChunk.lineStarts = newLineStarts;
if (this._previousChar === 13 /* CarriageReturn */) {
this.cr++;
}
}
};
return PieceTreeTextBufferBuilder;
}());
exports.PieceTreeTextBufferBuilder = PieceTreeTextBufferBuilder;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[109/*vs/editor/common/model/wordHelper*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.USUAL_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:\'",.<>/?';
/**
* Create a word definition regular expression based on default word separators.
* Optionally provide allowed separators that should be included in words.
*
* The default would look like this:
* /(-?\d*\.\d\w*)|([^\`\~\!\@\#\$\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g
*/
function createWordRegExp(allowInWords) {
if (allowInWords === void 0) { allowInWords = ''; }
var source = '(-?\\d*\\.\\d\\w*)|([^';
for (var _i = 0, USUAL_WORD_SEPARATORS_1 = exports.USUAL_WORD_SEPARATORS; _i < USUAL_WORD_SEPARATORS_1.length; _i++) {
var sep = USUAL_WORD_SEPARATORS_1[_i];
if (allowInWords.indexOf(sep) >= 0) {
continue;
}
source += '\\' + sep;
}
source += '\\s]+)';
return new RegExp(source, 'g');
}
// catches numbers (including floating numbers) in the first group, and alphanum in the second
exports.DEFAULT_WORD_REGEXP = createWordRegExp();
function ensureValidWordDefinition(wordDefinition) {
var result = exports.DEFAULT_WORD_REGEXP;
if (wordDefinition && (wordDefinition instanceof RegExp)) {
if (!wordDefinition.global) {
var flags = 'g';
if (wordDefinition.ignoreCase) {
flags += 'i';
}
if (wordDefinition.multiline) {
flags += 'm';
}
if (wordDefinition.unicode) {
flags += 'u';
}
result = new RegExp(wordDefinition.source, flags);
}
else {
result = wordDefinition;
}
}
result.lastIndex = 0;
return result;
}
exports.ensureValidWordDefinition = ensureValidWordDefinition;
function getWordAtPosFast(column, wordDefinition, text, textOffset) {
// find whitespace enclosed text around column and match from there
var pos = column - 1 - textOffset;
var start = text.lastIndexOf(' ', pos - 1) + 1;
wordDefinition.lastIndex = start;
var match;
while (match = wordDefinition.exec(text)) {
var matchIndex = match.index || 0;
if (matchIndex <= pos && wordDefinition.lastIndex >= pos) {
return {
word: match[0],
startColumn: textOffset + 1 + matchIndex,
endColumn: textOffset + 1 + wordDefinition.lastIndex
};
}
}
return null;
}
function getWordAtPosSlow(column, wordDefinition, text, textOffset) {
// matches all words starting at the beginning
// of the input until it finds a match that encloses
// the desired column. slow but correct
var pos = column - 1 - textOffset;
wordDefinition.lastIndex = 0;
var match;
while (match = wordDefinition.exec(text)) {
var matchIndex = match.index || 0;
if (matchIndex > pos) {
// |nW -> matched only after the pos
return null;
}
else if (wordDefinition.lastIndex >= pos) {
// W|W -> match encloses pos
return {
word: match[0],
startColumn: textOffset + 1 + matchIndex,
endColumn: textOffset + 1 + wordDefinition.lastIndex
};
}
}
return null;
}
function getWordAtText(column, wordDefinition, text, textOffset) {
// if `words` can contain whitespace character we have to use the slow variant
// otherwise we use the fast variant of finding a word
wordDefinition.lastIndex = 0;
var match = wordDefinition.exec(text);
if (!match) {
return null;
}
// todo@joh the `match` could already be the (first) word
var ret = match[0].indexOf(' ') >= 0
// did match a word which contains a space character -> use slow word find
? getWordAtPosSlow(column, wordDefinition, text, textOffset)
// sane word definition -> use fast word find
: getWordAtPosFast(column, wordDefinition, text, textOffset);
// both (getWordAtPosFast and getWordAtPosSlow) leave the wordDefinition-RegExp
// in an undefined state and to not confuse other users of the wordDefinition
// we reset the lastIndex
wordDefinition.lastIndex = 0;
return ret;
}
exports.getWordAtText = getWordAtText;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[349/*vs/editor/common/modes/abstractMode*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FrankensteinMode = /** @class */ (function () {
function FrankensteinMode(languageIdentifier) {
this._languageIdentifier = languageIdentifier;
}
FrankensteinMode.prototype.getId = function () {
return this._languageIdentifier.language;
};
return FrankensteinMode;
}());
exports.FrankensteinMode = FrankensteinMode;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[90/*vs/editor/common/modes/languageConfiguration*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Describes what to do with the indentation when pressing Enter.
*/
var IndentAction;
(function (IndentAction) {
/**
* Insert new line and copy the previous line's indentation.
*/
IndentAction[IndentAction["None"] = 0] = "None";
/**
* Insert new line and indent once (relative to the previous line's indentation).
*/
IndentAction[IndentAction["Indent"] = 1] = "Indent";
/**
* Insert two new lines:
* - the first one indented which will hold the cursor
* - the second one at the same indentation level
*/
IndentAction[IndentAction["IndentOutdent"] = 2] = "IndentOutdent";
/**
* Insert new line and outdent once (relative to the previous line's indentation).
*/
IndentAction[IndentAction["Outdent"] = 3] = "Outdent";
})(IndentAction = exports.IndentAction || (exports.IndentAction = {}));
/**
* @internal
*/
var StandardAutoClosingPairConditional = /** @class */ (function () {
function StandardAutoClosingPairConditional(source) {
this.open = source.open;
this.close = source.close;
// initially allowed in all tokens
this._standardTokenMask = 0;
if (Array.isArray(source.notIn)) {
for (var i = 0, len = source.notIn.length; i < len; i++) {
var notIn = source.notIn[i];
switch (notIn) {
case 'string':
this._standardTokenMask |= 2 /* String */;
break;
case 'comment':
this._standardTokenMask |= 1 /* Comment */;
break;
case 'regex':
this._standardTokenMask |= 4 /* RegEx */;
break;
}
}
}
}
StandardAutoClosingPairConditional.prototype.isOK = function (standardToken) {
return (this._standardTokenMask & standardToken) === 0;
};
return StandardAutoClosingPairConditional;
}());
exports.StandardAutoClosingPairConditional = StandardAutoClosingPairConditional;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[350/*vs/editor/common/modes/languageSelector*/], __M([0/*require*/,1/*exports*/,178/*vs/base/common/glob*/]), function (require, exports, glob_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function score(selector, candidateUri, candidateLanguage, candidateIsSynchronized) {
if (Array.isArray(selector)) {
// array -> take max individual value
var ret = 0;
for (var _i = 0, selector_1 = selector; _i < selector_1.length; _i++) {
var filter = selector_1[_i];
var value = score(filter, candidateUri, candidateLanguage, candidateIsSynchronized);
if (value === 10) {
return value; // already at the highest
}
if (value > ret) {
ret = value;
}
}
return ret;
}
else if (typeof selector === 'string') {
if (!candidateIsSynchronized) {
return 0;
}
// short-hand notion, desugars to
// 'fooLang' -> { language: 'fooLang'}
// '*' -> { language: '*' }
if (selector === '*') {
return 5;
}
else if (selector === candidateLanguage) {
return 10;
}
else {
return 0;
}
}
else if (selector) {
// filter -> select accordingly, use defaults for scheme
var language = selector.language, pattern = selector.pattern, scheme = selector.scheme, hasAccessToAllModels = selector.hasAccessToAllModels;
if (!candidateIsSynchronized && !hasAccessToAllModels) {
return 0;
}
var ret = 0;
if (scheme) {
if (scheme === candidateUri.scheme) {
ret = 10;
}
else if (scheme === '*') {
ret = 5;
}
else {
return 0;
}
}
if (language) {
if (language === candidateLanguage) {
ret = 10;
}
else if (language === '*') {
ret = Math.max(ret, 5);
}
else {
return 0;
}
}
if (pattern) {
if (pattern === candidateUri.fsPath || glob_1.match(pattern, candidateUri.fsPath)) {
ret = 10;
}
else {
return 0;
}
}
return ret;
}
else {
return 0;
}
}
exports.score = score;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[351/*vs/editor/common/modes/linkComputer*/], __M([0/*require*/,1/*exports*/,79/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Uint8Matrix = /** @class */ (function () {
function Uint8Matrix(rows, cols, defaultValue) {
var data = new Uint8Array(rows * cols);
for (var i = 0, len = rows * cols; i < len; i++) {
data[i] = defaultValue;
}
this._data = data;
this.rows = rows;
this.cols = cols;
}
Uint8Matrix.prototype.get = function (row, col) {
return this._data[row * this.cols + col];
};
Uint8Matrix.prototype.set = function (row, col, value) {
this._data[row * this.cols + col] = value;
};
return Uint8Matrix;
}());
exports.Uint8Matrix = Uint8Matrix;
var StateMachine = /** @class */ (function () {
function StateMachine(edges) {
var maxCharCode = 0;
var maxState = 0 /* Invalid */;
for (var i = 0, len = edges.length; i < len; i++) {
var _a = edges[i], from = _a[0], chCode = _a[1], to = _a[2];
if (chCode > maxCharCode) {
maxCharCode = chCode;
}
if (from > maxState) {
maxState = from;
}
if (to > maxState) {
maxState = to;
}
}
maxCharCode++;
maxState++;
var states = new Uint8Matrix(maxState, maxCharCode, 0 /* Invalid */);
for (var i = 0, len = edges.length; i < len; i++) {
var _b = edges[i], from = _b[0], chCode = _b[1], to = _b[2];
states.set(from, chCode, to);
}
this._states = states;
this._maxCharCode = maxCharCode;
}
StateMachine.prototype.nextState = function (currentState, chCode) {
if (chCode < 0 || chCode >= this._maxCharCode) {
return 0 /* Invalid */;
}
return this._states.get(currentState, chCode);
};
return StateMachine;
}());
exports.StateMachine = StateMachine;
// State machine for http:// or https:// or file://
var _stateMachine = null;
function getStateMachine() {
if (_stateMachine === null) {
_stateMachine = new StateMachine([
[1 /* Start */, 104 /* h */, 2 /* H */],
[1 /* Start */, 72 /* H */, 2 /* H */],
[1 /* Start */, 102 /* f */, 6 /* F */],
[1 /* Start */, 70 /* F */, 6 /* F */],
[2 /* H */, 116 /* t */, 3 /* HT */],
[2 /* H */, 84 /* T */, 3 /* HT */],
[3 /* HT */, 116 /* t */, 4 /* HTT */],
[3 /* HT */, 84 /* T */, 4 /* HTT */],
[4 /* HTT */, 112 /* p */, 5 /* HTTP */],
[4 /* HTT */, 80 /* P */, 5 /* HTTP */],
[5 /* HTTP */, 115 /* s */, 9 /* BeforeColon */],
[5 /* HTTP */, 83 /* S */, 9 /* BeforeColon */],
[5 /* HTTP */, 58 /* Colon */, 10 /* AfterColon */],
[6 /* F */, 105 /* i */, 7 /* FI */],
[6 /* F */, 73 /* I */, 7 /* FI */],
[7 /* FI */, 108 /* l */, 8 /* FIL */],
[7 /* FI */, 76 /* L */, 8 /* FIL */],
[8 /* FIL */, 101 /* e */, 9 /* BeforeColon */],
[8 /* FIL */, 69 /* E */, 9 /* BeforeColon */],
[9 /* BeforeColon */, 58 /* Colon */, 10 /* AfterColon */],
[10 /* AfterColon */, 47 /* Slash */, 11 /* AlmostThere */],
[11 /* AlmostThere */, 47 /* Slash */, 12 /* End */],
]);
}
return _stateMachine;
}
var _classifier = null;
function getClassifier() {
if (_classifier === null) {
_classifier = new characterClassifier_1.CharacterClassifier(0 /* None */);
var FORCE_TERMINATION_CHARACTERS = ' \t<>\'\"、。。、,.:;?!@#$%&*‘“〈《「『【〔([{「」}])〕】』」》〉”’`~…';
for (var i = 0; i < FORCE_TERMINATION_CHARACTERS.length; i++) {
_classifier.set(FORCE_TERMINATION_CHARACTERS.charCodeAt(i), 1 /* ForceTermination */);
}
var CANNOT_END_WITH_CHARACTERS = '.,;';
for (var i = 0; i < CANNOT_END_WITH_CHARACTERS.length; i++) {
_classifier.set(CANNOT_END_WITH_CHARACTERS.charCodeAt(i), 2 /* CannotEndIn */);
}
}
return _classifier;
}
var LinkComputer = /** @class */ (function () {
function LinkComputer() {
}
LinkComputer._createLink = function (classifier, line, lineNumber, linkBeginIndex, linkEndIndex) {
// Do not allow to end link in certain characters...
var lastIncludedCharIndex = linkEndIndex - 1;
do {
var chCode = line.charCodeAt(lastIncludedCharIndex);
var chClass = classifier.get(chCode);
if (chClass !== 2 /* CannotEndIn */) {
break;
}
lastIncludedCharIndex--;
} while (lastIncludedCharIndex > linkBeginIndex);
// Handle links enclosed in parens, square brackets and curlys.
if (linkBeginIndex > 0) {
var charCodeBeforeLink = line.charCodeAt(linkBeginIndex - 1);
var lastCharCodeInLink = line.charCodeAt(lastIncludedCharIndex);
if ((charCodeBeforeLink === 40 /* OpenParen */ && lastCharCodeInLink === 41 /* CloseParen */)
|| (charCodeBeforeLink === 91 /* OpenSquareBracket */ && lastCharCodeInLink === 93 /* CloseSquareBracket */)
|| (charCodeBeforeLink === 123 /* OpenCurlyBrace */ && lastCharCodeInLink === 125 /* CloseCurlyBrace */)) {
// Do not end in ) if ( is before the link start
// Do not end in ] if [ is before the link start
// Do not end in } if { is before the link start
lastIncludedCharIndex--;
}
}
return {
range: {
startLineNumber: lineNumber,
startColumn: linkBeginIndex + 1,
endLineNumber: lineNumber,
endColumn: lastIncludedCharIndex + 2
},
url: line.substring(linkBeginIndex, lastIncludedCharIndex + 1)
};
};
LinkComputer.computeLinks = function (model, stateMachine) {
if (stateMachine === void 0) { stateMachine = getStateMachine(); }
var classifier = getClassifier();
var result = [];
for (var i = 1, lineCount = model.getLineCount(); i <= lineCount; i++) {
var line = model.getLineContent(i);
var len = line.length;
var j = 0;
var linkBeginIndex = 0;
var linkBeginChCode = 0;
var state = 1 /* Start */;
var hasOpenParens = false;
var hasOpenSquareBracket = false;
var hasOpenCurlyBracket = false;
while (j < len) {
var resetStateMachine = false;
var chCode = line.charCodeAt(j);
if (state === 13 /* Accept */) {
var chClass = void 0;
switch (chCode) {
case 40 /* OpenParen */:
hasOpenParens = true;
chClass = 0 /* None */;
break;
case 41 /* CloseParen */:
chClass = (hasOpenParens ? 0 /* None */ : 1 /* ForceTermination */);
break;
case 91 /* OpenSquareBracket */:
hasOpenSquareBracket = true;
chClass = 0 /* None */;
break;
case 93 /* CloseSquareBracket */:
chClass = (hasOpenSquareBracket ? 0 /* None */ : 1 /* ForceTermination */);
break;
case 123 /* OpenCurlyBrace */:
hasOpenCurlyBracket = true;
chClass = 0 /* None */;
break;
case 125 /* CloseCurlyBrace */:
chClass = (hasOpenCurlyBracket ? 0 /* None */ : 1 /* ForceTermination */);
break;
/* The following three rules make it that ' or " or ` are allowed inside links if the link began with a different one */
case 39 /* SingleQuote */:
chClass = (linkBeginChCode === 34 /* DoubleQuote */ || linkBeginChCode === 96 /* BackTick */) ? 0 /* None */ : 1 /* ForceTermination */;
break;
case 34 /* DoubleQuote */:
chClass = (linkBeginChCode === 39 /* SingleQuote */ || linkBeginChCode === 96 /* BackTick */) ? 0 /* None */ : 1 /* ForceTermination */;
break;
case 96 /* BackTick */:
chClass = (linkBeginChCode === 39 /* SingleQuote */ || linkBeginChCode === 34 /* DoubleQuote */) ? 0 /* None */ : 1 /* ForceTermination */;
break;
case 42 /* Asterisk */:
// `*` terminates a link if the link began with `*`
chClass = (linkBeginChCode === 42 /* Asterisk */) ? 1 /* ForceTermination */ : 0 /* None */;
break;
case 124 /* Pipe */:
// `|` terminates a link if the link began with `|`
chClass = (linkBeginChCode === 124 /* Pipe */) ? 1 /* ForceTermination */ : 0 /* None */;
break;
default:
chClass = classifier.get(chCode);
}
// Check if character terminates link
if (chClass === 1 /* ForceTermination */) {
result.push(LinkComputer._createLink(classifier, line, i, linkBeginIndex, j));
resetStateMachine = true;
}
}
else if (state === 12 /* End */) {
var chClass = void 0;
if (chCode === 91 /* OpenSquareBracket */) {
// Allow for the authority part to contain ipv6 addresses which contain [ and ]
hasOpenSquareBracket = true;
chClass = 0 /* None */;
}
else {
chClass = classifier.get(chCode);
}
// Check if character terminates link
if (chClass === 1 /* ForceTermination */) {
resetStateMachine = true;
}
else {
state = 13 /* Accept */;
}
}
else {
state = stateMachine.nextState(state, chCode);
if (state === 0 /* Invalid */) {
resetStateMachine = true;
}
}
if (resetStateMachine) {
state = 1 /* Start */;
hasOpenParens = false;
hasOpenSquareBracket = false;
hasOpenCurlyBracket = false;
// Record where the link started
linkBeginIndex = j + 1;
linkBeginChCode = chCode;
}
j++;
}
if (state === 13 /* Accept */) {
result.push(LinkComputer._createLink(classifier, line, i, linkBeginIndex, len));
}
}
return result;
};
return LinkComputer;
}());
exports.LinkComputer = LinkComputer;
/**
* Returns an array of all links contains in the provided
* document. *Note* that this operation is computational
* expensive and should not run in the UI thread.
*/
function computeLinks(model) {
if (!model || typeof model.getLineCount !== 'function' || typeof model.getLineContent !== 'function') {
// Unknown caller!
return [];
}
return LinkComputer.computeLinks(model);
}
exports.computeLinks = computeLinks;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[145/*vs/editor/common/modes/supports*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function createScopedLineTokens(context, offset) {
var tokenCount = context.getCount();
var tokenIndex = context.findTokenIndexAtOffset(offset);
var desiredLanguageId = context.getLanguageId(tokenIndex);
var lastTokenIndex = tokenIndex;
while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) {
lastTokenIndex++;
}
var firstTokenIndex = tokenIndex;
while (firstTokenIndex > 0 && context.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) {
firstTokenIndex--;
}
return new ScopedLineTokens(context, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context.getStartOffset(firstTokenIndex), context.getEndOffset(lastTokenIndex));
}
exports.createScopedLineTokens = createScopedLineTokens;
var ScopedLineTokens = /** @class */ (function () {
function ScopedLineTokens(actual, languageId, firstTokenIndex, lastTokenIndex, firstCharOffset, lastCharOffset) {
this._actual = actual;
this.languageId = languageId;
this._firstTokenIndex = firstTokenIndex;
this._lastTokenIndex = lastTokenIndex;
this.firstCharOffset = firstCharOffset;
this._lastCharOffset = lastCharOffset;
}
ScopedLineTokens.prototype.getLineContent = function () {
var actualLineContent = this._actual.getLineContent();
return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset);
};
ScopedLineTokens.prototype.getActualLineContentBefore = function (offset) {
var actualLineContent = this._actual.getLineContent();
return actualLineContent.substring(0, this.firstCharOffset + offset);
};
ScopedLineTokens.prototype.getTokenCount = function () {
return this._lastTokenIndex - this._firstTokenIndex;
};
ScopedLineTokens.prototype.findTokenIndexAtOffset = function (offset) {
return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex;
};
ScopedLineTokens.prototype.getStandardTokenType = function (tokenIndex) {
return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex);
};
return ScopedLineTokens;
}());
exports.ScopedLineTokens = ScopedLineTokens;
function ignoreBracketsInToken(standardTokenType) {
return (standardTokenType & 7 /* value */) !== 0;
}
exports.ignoreBracketsInToken = ignoreBracketsInToken;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[352/*vs/editor/common/modes/supports/characterPair*/], __M([0/*require*/,1/*exports*/,90/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, languageConfiguration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CharacterPairSupport = /** @class */ (function () {
function CharacterPairSupport(config) {
if (config.autoClosingPairs) {
this._autoClosingPairs = config.autoClosingPairs.map(function (el) { return new languageConfiguration_1.StandardAutoClosingPairConditional(el); });
}
else if (config.brackets) {
this._autoClosingPairs = config.brackets.map(function (b) { return new languageConfiguration_1.StandardAutoClosingPairConditional({ open: b[0], close: b[1] }); });
}
else {
this._autoClosingPairs = [];
}
if (config.__electricCharacterSupport && config.__electricCharacterSupport.docComment) {
var docComment = config.__electricCharacterSupport.docComment;
// IDocComment is legacy, only partially supported
this._autoClosingPairs.push(new languageConfiguration_1.StandardAutoClosingPairConditional({ open: docComment.open, close: docComment.close || '' }));
}
this._autoCloseBefore = typeof config.autoCloseBefore === 'string' ? config.autoCloseBefore : CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED;
this._surroundingPairs = config.surroundingPairs || this._autoClosingPairs;
}
CharacterPairSupport.prototype.getAutoClosingPairs = function () {
return this._autoClosingPairs;
};
CharacterPairSupport.prototype.getAutoCloseBeforeSet = function () {
return this._autoCloseBefore;
};
CharacterPairSupport.shouldAutoClosePair = function (autoClosingPair, context, column) {
// Always complete on empty line
if (context.getTokenCount() === 0) {
return true;
}
var tokenIndex = context.findTokenIndexAtOffset(column - 2);
var standardTokenType = context.getStandardTokenType(tokenIndex);
return autoClosingPair.isOK(standardTokenType);
};
CharacterPairSupport.prototype.getSurroundingPairs = function () {
return this._surroundingPairs;
};
CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED = ';:.,=}])> \n\t';
return CharacterPairSupport;
}());
exports.CharacterPairSupport = CharacterPairSupport;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[353/*vs/editor/common/modes/supports/indentRules*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var IndentRulesSupport = /** @class */ (function () {
function IndentRulesSupport(indentationRules) {
this._indentationRules = indentationRules;
}
IndentRulesSupport.prototype.shouldIncrease = function (text) {
if (this._indentationRules) {
if (this._indentationRules.increaseIndentPattern && this._indentationRules.increaseIndentPattern.test(text)) {
return true;
}
// if (this._indentationRules.indentNextLinePattern && this._indentationRules.indentNextLinePattern.test(text)) {
// return true;
// }
}
return false;
};
IndentRulesSupport.prototype.shouldDecrease = function (text) {
if (this._indentationRules && this._indentationRules.decreaseIndentPattern && this._indentationRules.decreaseIndentPattern.test(text)) {
return true;
}
return false;
};
IndentRulesSupport.prototype.shouldIndentNextLine = function (text) {
if (this._indentationRules && this._indentationRules.indentNextLinePattern && this._indentationRules.indentNextLinePattern.test(text)) {
return true;
}
return false;
};
IndentRulesSupport.prototype.shouldIgnore = function (text) {
// the text matches `unIndentedLinePattern`
if (this._indentationRules && this._indentationRules.unIndentedLinePattern && this._indentationRules.unIndentedLinePattern.test(text)) {
return true;
}
return false;
};
IndentRulesSupport.prototype.getIndentMetadata = function (text) {
var ret = 0;
if (this.shouldIncrease(text)) {
ret += 1 /* INCREASE_MASK */;
}
if (this.shouldDecrease(text)) {
ret += 2 /* DECREASE_MASK */;
}
if (this.shouldIndentNextLine(text)) {
ret += 4 /* INDENT_NEXTLINE_MASK */;
}
if (this.shouldIgnore(text)) {
ret += 8 /* UNINDENT_MASK */;
}
return ret;
};
return IndentRulesSupport;
}());
exports.IndentRulesSupport = IndentRulesSupport;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[354/*vs/editor/common/modes/supports/inplaceReplaceSupport*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BasicInplaceReplace = /** @class */ (function () {
function BasicInplaceReplace() {
this._defaultValueSet = [
['true', 'false'],
['True', 'False'],
['Private', 'Public', 'Friend', 'ReadOnly', 'Partial', 'Protected', 'WriteOnly'],
['public', 'protected', 'private'],
];
}
BasicInplaceReplace.prototype.navigateValueSet = function (range1, text1, range2, text2, up) {
if (range1 && text1) {
var result = this.doNavigateValueSet(text1, up);
if (result) {
return {
range: range1,
value: result
};
}
}
if (range2 && text2) {
var result = this.doNavigateValueSet(text2, up);
if (result) {
return {
range: range2,
value: result
};
}
}
return null;
};
BasicInplaceReplace.prototype.doNavigateValueSet = function (text, up) {
var numberResult = this.numberReplace(text, up);
if (numberResult !== null) {
return numberResult;
}
return this.textReplace(text, up);
};
BasicInplaceReplace.prototype.numberReplace = function (value, up) {
var precision = Math.pow(10, value.length - (value.lastIndexOf('.') + 1));
var n1 = Number(value);
var n2 = parseFloat(value);
if (!isNaN(n1) && !isNaN(n2) && n1 === n2) {
if (n1 === 0 && !up) {
return null; // don't do negative
// } else if(n1 === 9 && up) {
// return null; // don't insert 10 into a number
}
else {
n1 = Math.floor(n1 * precision);
n1 += up ? precision : -precision;
return String(n1 / precision);
}
}
return null;
};
BasicInplaceReplace.prototype.textReplace = function (value, up) {
return this.valueSetsReplace(this._defaultValueSet, value, up);
};
BasicInplaceReplace.prototype.valueSetsReplace = function (valueSets, value, up) {
var result = null;
for (var i = 0, len = valueSets.length; result === null && i < len; i++) {
result = this.valueSetReplace(valueSets[i], value, up);
}
return result;
};
BasicInplaceReplace.prototype.valueSetReplace = function (valueSet, value, up) {
var idx = valueSet.indexOf(value);
if (idx >= 0) {
idx += up ? +1 : -1;
if (idx < 0) {
idx = valueSet.length - 1;
}
else {
idx %= valueSet.length;
}
return valueSet[idx];
}
return null;
};
BasicInplaceReplace.INSTANCE = new BasicInplaceReplace();
return BasicInplaceReplace;
}());
exports.BasicInplaceReplace = BasicInplaceReplace;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[355/*vs/editor/common/modes/supports/onEnter*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,5/*vs/base/common/strings*/,90/*vs/editor/common/modes/languageConfiguration*/]), function (require, exports, errors_1, strings, languageConfiguration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var OnEnterSupport = /** @class */ (function () {
function OnEnterSupport(opts) {
var _this = this;
opts = opts || {};
opts.brackets = opts.brackets || [
['(', ')'],
['{', '}'],
['[', ']']
];
this._brackets = [];
opts.brackets.forEach(function (bracket) {
var openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]);
var closeRegExp = OnEnterSupport._createCloseBracketRegExp(bracket[1]);
if (openRegExp && closeRegExp) {
_this._brackets.push({
open: bracket[0],
openRegExp: openRegExp,
close: bracket[1],
closeRegExp: closeRegExp,
});
}
});
this._regExpRules = opts.onEnterRules || [];
}
OnEnterSupport.prototype.onEnter = function (autoIndent, oneLineAboveText, beforeEnterText, afterEnterText) {
// (1): `regExpRules`
if (autoIndent >= 3 /* Advanced */) {
for (var i = 0, len = this._regExpRules.length; i < len; i++) {
var rule = this._regExpRules[i];
var regResult = [{
reg: rule.beforeText,
text: beforeEnterText
}, {
reg: rule.afterText,
text: afterEnterText
}, {
reg: rule.oneLineAboveText,
text: oneLineAboveText
}].every(function (obj) {
return obj.reg ? obj.reg.test(obj.text) : true;
});
if (regResult) {
return rule.action;
}
}
}
// (2): Special indent-outdent
if (autoIndent >= 2 /* Brackets */) {
if (beforeEnterText.length > 0 && afterEnterText.length > 0) {
for (var i = 0, len = this._brackets.length; i < len; i++) {
var bracket = this._brackets[i];
if (bracket.openRegExp.test(beforeEnterText) && bracket.closeRegExp.test(afterEnterText)) {
return { indentAction: languageConfiguration_1.IndentAction.IndentOutdent };
}
}
}
}
// (4): Open bracket based logic
if (autoIndent >= 2 /* Brackets */) {
if (beforeEnterText.length > 0) {
for (var i = 0, len = this._brackets.length; i < len; i++) {
var bracket = this._brackets[i];
if (bracket.openRegExp.test(beforeEnterText)) {
return { indentAction: languageConfiguration_1.IndentAction.Indent };
}
}
}
}
return null;
};
OnEnterSupport._createOpenBracketRegExp = function (bracket) {
var str = strings.escapeRegExpCharacters(bracket);
if (!/\B/.test(str.charAt(0))) {
str = '\\b' + str;
}
str += '\\s*$';
return OnEnterSupport._safeRegExp(str);
};
OnEnterSupport._createCloseBracketRegExp = function (bracket) {
var str = strings.escapeRegExpCharacters(bracket);
if (!/\B/.test(str.charAt(str.length - 1))) {
str = str + '\\b';
}
str = '^\\s*' + str;
return OnEnterSupport._safeRegExp(str);
};
OnEnterSupport._safeRegExp = function (def) {
try {
return new RegExp(def);
}
catch (err) {
errors_1.onUnexpectedError(err);
return null;
}
};
return OnEnterSupport;
}());
exports.OnEnterSupport = OnEnterSupport;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[146/*vs/editor/common/modes/supports/richEditBrackets*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var RichEditBracket = /** @class */ (function () {
function RichEditBracket(languageIdentifier, index, open, close, forwardRegex, reversedRegex) {
this.languageIdentifier = languageIdentifier;
this.index = index;
this.open = open;
this.close = close;
this.forwardRegex = forwardRegex;
this.reversedRegex = reversedRegex;
this._openSet = RichEditBracket._toSet(this.open);
this._closeSet = RichEditBracket._toSet(this.close);
}
RichEditBracket.prototype.isOpen = function (text) {
return this._openSet.has(text);
};
RichEditBracket.prototype.isClose = function (text) {
return this._closeSet.has(text);
};
RichEditBracket._toSet = function (arr) {
var result = new Set();
for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) {
var element = arr_1[_i];
result.add(element);
}
return result;
};
return RichEditBracket;
}());
exports.RichEditBracket = RichEditBracket;
function groupFuzzyBrackets(brackets) {
var N = brackets.length;
brackets = brackets.map(function (b) { return [b[0].toLowerCase(), b[1].toLowerCase()]; });
var group = [];
for (var i = 0; i < N; i++) {
group[i] = i;
}
var areOverlapping = function (a, b) {
var aOpen = a[0], aClose = a[1];
var bOpen = b[0], bClose = b[1];
return (aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose);
};
var mergeGroups = function (g1, g2) {
var newG = Math.min(g1, g2);
var oldG = Math.max(g1, g2);
for (var i = 0; i < N; i++) {
if (group[i] === oldG) {
group[i] = newG;
}
}
};
// group together brackets that have the same open or the same close sequence
for (var i = 0; i < N; i++) {
var a = brackets[i];
for (var j = i + 1; j < N; j++) {
var b = brackets[j];
if (areOverlapping(a, b)) {
mergeGroups(group[i], group[j]);
}
}
}
var result = [];
for (var g = 0; g < N; g++) {
var currentOpen = [];
var currentClose = [];
for (var i = 0; i < N; i++) {
if (group[i] === g) {
var _a = brackets[i], open_1 = _a[0], close_1 = _a[1];
currentOpen.push(open_1);
currentClose.push(close_1);
}
}
if (currentOpen.length > 0) {
result.push({
open: currentOpen,
close: currentClose
});
}
}
return result;
}
var RichEditBrackets = /** @class */ (function () {
function RichEditBrackets(languageIdentifier, _brackets) {
var brackets = groupFuzzyBrackets(_brackets);
this.brackets = brackets.map(function (b, index) {
return new RichEditBracket(languageIdentifier, index, b.open, b.close, getRegexForBracketPair(b.open, b.close, brackets, index), getReversedRegexForBracketPair(b.open, b.close, brackets, index));
});
this.forwardRegex = getRegexForBrackets(this.brackets);
this.reversedRegex = getReversedRegexForBrackets(this.brackets);
this.textIsBracket = {};
this.textIsOpenBracket = {};
this.maxBracketLength = 0;
for (var _i = 0, _a = this.brackets; _i < _a.length; _i++) {
var bracket = _a[_i];
for (var _b = 0, _c = bracket.open; _b < _c.length; _b++) {
var open_2 = _c[_b];
this.textIsBracket[open_2] = bracket;
this.textIsOpenBracket[open_2] = true;
this.maxBracketLength = Math.max(this.maxBracketLength, open_2.length);
}
for (var _d = 0, _e = bracket.close; _d < _e.length; _d++) {
var close_2 = _e[_d];
this.textIsBracket[close_2] = bracket;
this.textIsOpenBracket[close_2] = false;
this.maxBracketLength = Math.max(this.maxBracketLength, close_2.length);
}
}
}
return RichEditBrackets;
}());
exports.RichEditBrackets = RichEditBrackets;
function collectSuperstrings(str, brackets, currentIndex, dest) {
for (var i = 0, len = brackets.length; i < len; i++) {
if (i === currentIndex) {
continue;
}
var bracket = brackets[i];
for (var _i = 0, _a = bracket.open; _i < _a.length; _i++) {
var open_3 = _a[_i];
if (open_3.indexOf(str) >= 0) {
dest.push(open_3);
}
}
for (var _b = 0, _c = bracket.close; _b < _c.length; _b++) {
var close_3 = _c[_b];
if (close_3.indexOf(str) >= 0) {
dest.push(close_3);
}
}
}
}
function lengthcmp(a, b) {
return a.length - b.length;
}
function unique(arr) {
if (arr.length <= 1) {
return arr;
}
var result = [];
var seen = new Set();
for (var _i = 0, arr_2 = arr; _i < arr_2.length; _i++) {
var element = arr_2[_i];
if (seen.has(element)) {
continue;
}
result.push(element);
seen.add(element);
}
return result;
}
function getRegexForBracketPair(open, close, brackets, currentIndex) {
// search in all brackets for other brackets that are a superstring of these brackets
var pieces = [];
pieces = pieces.concat(open);
pieces = pieces.concat(close);
for (var i = 0, len = pieces.length; i < len; i++) {
collectSuperstrings(pieces[i], brackets, currentIndex, pieces);
}
pieces = unique(pieces);
pieces.sort(lengthcmp);
pieces.reverse();
return createBracketOrRegExp(pieces);
}
function getReversedRegexForBracketPair(open, close, brackets, currentIndex) {
// search in all brackets for other brackets that are a superstring of these brackets
var pieces = [];
pieces = pieces.concat(open);
pieces = pieces.concat(close);
for (var i = 0, len = pieces.length; i < len; i++) {
collectSuperstrings(pieces[i], brackets, currentIndex, pieces);
}
pieces = unique(pieces);
pieces.sort(lengthcmp);
pieces.reverse();
return createBracketOrRegExp(pieces.map(toReversedString));
}
function getRegexForBrackets(brackets) {
var pieces = [];
for (var _i = 0, brackets_1 = brackets; _i < brackets_1.length; _i++) {
var bracket = brackets_1[_i];
for (var _a = 0, _b = bracket.open; _a < _b.length; _a++) {
var open_4 = _b[_a];
pieces.push(open_4);
}
for (var _c = 0, _d = bracket.close; _c < _d.length; _c++) {
var close_4 = _d[_c];
pieces.push(close_4);
}
}
pieces = unique(pieces);
return createBracketOrRegExp(pieces);
}
function getReversedRegexForBrackets(brackets) {
var pieces = [];
for (var _i = 0, brackets_2 = brackets; _i < brackets_2.length; _i++) {
var bracket = brackets_2[_i];
for (var _a = 0, _b = bracket.open; _a < _b.length; _a++) {
var open_5 = _b[_a];
pieces.push(open_5);
}
for (var _c = 0, _d = bracket.close; _c < _d.length; _c++) {
var close_5 = _d[_c];
pieces.push(close_5);
}
}
pieces = unique(pieces);
return createBracketOrRegExp(pieces.map(toReversedString));
}
function prepareBracketForRegExp(str) {
// This bracket pair uses letters like e.g. "begin" - "end"
var insertWordBoundaries = (/^[\w ]+$/.test(str));
str = strings.escapeRegExpCharacters(str);
return (insertWordBoundaries ? "\\b" + str + "\\b" : str);
}
function createBracketOrRegExp(pieces) {
var regexStr = "(" + pieces.map(prepareBracketForRegExp).join(')|(') + ")";
return strings.createRegExp(regexStr, true);
}
var toReversedString = (function () {
function reverse(str) {
var reversedStr = '';
for (var i = str.length - 1; i >= 0; i--) {
reversedStr += str.charAt(i);
}
return reversedStr;
}
var lastInput = null;
var lastOutput = null;
return function toReversedString(str) {
if (lastInput !== str) {
lastInput = str;
lastOutput = reverse(lastInput);
}
return lastOutput;
};
})();
var BracketsUtils = /** @class */ (function () {
function BracketsUtils() {
}
BracketsUtils._findPrevBracketInText = function (reversedBracketRegex, lineNumber, reversedText, offset) {
var m = reversedText.match(reversedBracketRegex);
if (!m) {
return null;
}
var matchOffset = reversedText.length - (m.index || 0);
var matchLength = m[0].length;
var absoluteMatchOffset = offset + matchOffset;
return new range_1.Range(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1);
};
BracketsUtils.findPrevBracketInRange = function (reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) {
// Because JS does not support backwards regex search, we search forwards in a reversed string with a reversed regex ;)
var reversedLineText = toReversedString(lineText);
var reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset);
return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset);
};
BracketsUtils.findNextBracketInText = function (bracketRegex, lineNumber, text, offset) {
var m = text.match(bracketRegex);
if (!m) {
return null;
}
var matchOffset = m.index || 0;
var matchLength = m[0].length;
if (matchLength === 0) {
return null;
}
var absoluteMatchOffset = offset + matchOffset;
return new range_1.Range(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength);
};
BracketsUtils.findNextBracketInRange = function (bracketRegex, lineNumber, lineText, startOffset, endOffset) {
var substr = lineText.substring(startOffset, endOffset);
return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset);
};
return BracketsUtils;
}());
exports.BracketsUtils = BracketsUtils;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[356/*vs/editor/common/modes/supports/electricCharacter*/], __M([0/*require*/,1/*exports*/,145/*vs/editor/common/modes/supports*/,146/*vs/editor/common/modes/supports/richEditBrackets*/]), function (require, exports, supports_1, richEditBrackets_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BracketElectricCharacterSupport = /** @class */ (function () {
function BracketElectricCharacterSupport(richEditBrackets) {
this._richEditBrackets = richEditBrackets;
}
BracketElectricCharacterSupport.prototype.getElectricCharacters = function () {
var result = [];
if (this._richEditBrackets) {
for (var _i = 0, _a = this._richEditBrackets.brackets; _i < _a.length; _i++) {
var bracket = _a[_i];
for (var _b = 0, _c = bracket.close; _b < _c.length; _b++) {
var close_1 = _c[_b];
var lastChar = close_1.charAt(close_1.length - 1);
result.push(lastChar);
}
}
}
// Filter duplicate entries
result = result.filter(function (item, pos, array) {
return array.indexOf(item) === pos;
});
return result;
};
BracketElectricCharacterSupport.prototype.onElectricCharacter = function (character, context, column) {
if (!this._richEditBrackets || this._richEditBrackets.brackets.length === 0) {
return null;
}
var tokenIndex = context.findTokenIndexAtOffset(column - 1);
if (supports_1.ignoreBracketsInToken(context.getStandardTokenType(tokenIndex))) {
return null;
}
var reversedBracketRegex = this._richEditBrackets.reversedRegex;
var text = context.getLineContent().substring(0, column - 1) + character;
var r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, 1, text, 0, text.length);
if (!r) {
return null;
}
var bracketText = text.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
var isOpen = this._richEditBrackets.textIsOpenBracket[bracketText];
if (isOpen) {
return null;
}
var textBeforeBracket = context.getActualLineContentBefore(r.startColumn - 1);
if (!/^\s*$/.test(textBeforeBracket)) {
// There is other text on the line before the bracket
return null;
}
return {
matchOpenBracket: bracketText
};
};
return BracketElectricCharacterSupport;
}());
exports.BracketElectricCharacterSupport = BracketElectricCharacterSupport;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[41/*vs/editor/common/modes/languageConfigurationRegistry*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,109/*vs/editor/common/model/wordHelper*/,90/*vs/editor/common/modes/languageConfiguration*/,145/*vs/editor/common/modes/supports*/,352/*vs/editor/common/modes/supports/characterPair*/,356/*vs/editor/common/modes/supports/electricCharacter*/,353/*vs/editor/common/modes/supports/indentRules*/,355/*vs/editor/common/modes/supports/onEnter*/,146/*vs/editor/common/modes/supports/richEditBrackets*/]), function (require, exports, event_1, lifecycle_1, strings, wordHelper_1, languageConfiguration_1, supports_1, characterPair_1, electricCharacter_1, indentRules_1, onEnter_1, richEditBrackets_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var RichEditSupport = /** @class */ (function () {
function RichEditSupport(languageIdentifier, previous, rawConf) {
this._languageIdentifier = languageIdentifier;
this._brackets = null;
this._electricCharacter = null;
var prev = null;
if (previous) {
prev = previous._conf;
}
this._conf = RichEditSupport._mergeConf(prev, rawConf);
this._onEnterSupport = (this._conf.brackets || this._conf.indentationRules || this._conf.onEnterRules ? new onEnter_1.OnEnterSupport(this._conf) : null);
this.comments = RichEditSupport._handleComments(this._conf);
this.characterPair = new characterPair_1.CharacterPairSupport(this._conf);
this.wordDefinition = this._conf.wordPattern || wordHelper_1.DEFAULT_WORD_REGEXP;
this.indentationRules = this._conf.indentationRules;
if (this._conf.indentationRules) {
this.indentRulesSupport = new indentRules_1.IndentRulesSupport(this._conf.indentationRules);
}
else {
this.indentRulesSupport = null;
}
this.foldingRules = this._conf.folding || {};
}
Object.defineProperty(RichEditSupport.prototype, "brackets", {
get: function () {
if (!this._brackets && this._conf.brackets) {
this._brackets = new richEditBrackets_1.RichEditBrackets(this._languageIdentifier, this._conf.brackets);
}
return this._brackets;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RichEditSupport.prototype, "electricCharacter", {
get: function () {
if (!this._electricCharacter) {
this._electricCharacter = new electricCharacter_1.BracketElectricCharacterSupport(this.brackets);
}
return this._electricCharacter;
},
enumerable: true,
configurable: true
});
RichEditSupport.prototype.onEnter = function (autoIndent, oneLineAboveText, beforeEnterText, afterEnterText) {
if (!this._onEnterSupport) {
return null;
}
return this._onEnterSupport.onEnter(autoIndent, oneLineAboveText, beforeEnterText, afterEnterText);
};
RichEditSupport._mergeConf = function (prev, current) {
return {
comments: (prev ? current.comments || prev.comments : current.comments),
brackets: (prev ? current.brackets || prev.brackets : current.brackets),
wordPattern: (prev ? current.wordPattern || prev.wordPattern : current.wordPattern),
indentationRules: (prev ? current.indentationRules || prev.indentationRules : current.indentationRules),
onEnterRules: (prev ? current.onEnterRules || prev.onEnterRules : current.onEnterRules),
autoClosingPairs: (prev ? current.autoClosingPairs || prev.autoClosingPairs : current.autoClosingPairs),
surroundingPairs: (prev ? current.surroundingPairs || prev.surroundingPairs : current.surroundingPairs),
autoCloseBefore: (prev ? current.autoCloseBefore || prev.autoCloseBefore : current.autoCloseBefore),
folding: (prev ? current.folding || prev.folding : current.folding),
__electricCharacterSupport: (prev ? current.__electricCharacterSupport || prev.__electricCharacterSupport : current.__electricCharacterSupport),
};
};
RichEditSupport._handleComments = function (conf) {
var commentRule = conf.comments;
if (!commentRule) {
return null;
}
// comment configuration
var comments = {};
if (commentRule.lineComment) {
comments.lineCommentToken = commentRule.lineComment;
}
if (commentRule.blockComment) {
var _a = commentRule.blockComment, blockStart = _a[0], blockEnd = _a[1];
comments.blockCommentStartToken = blockStart;
comments.blockCommentEndToken = blockEnd;
}
return comments;
};
return RichEditSupport;
}());
exports.RichEditSupport = RichEditSupport;
var LanguageConfigurationChangeEvent = /** @class */ (function () {
function LanguageConfigurationChangeEvent(languageIdentifier) {
this.languageIdentifier = languageIdentifier;
}
return LanguageConfigurationChangeEvent;
}());
exports.LanguageConfigurationChangeEvent = LanguageConfigurationChangeEvent;
var LanguageConfigurationRegistryImpl = /** @class */ (function () {
function LanguageConfigurationRegistryImpl() {
this._entries = new Map();
this._onDidChange = new event_1.Emitter();
this.onDidChange = this._onDidChange.event;
}
LanguageConfigurationRegistryImpl.prototype.register = function (languageIdentifier, configuration) {
var _this = this;
var previous = this._getRichEditSupport(languageIdentifier.id);
var current = new RichEditSupport(languageIdentifier, previous, configuration);
this._entries.set(languageIdentifier.id, current);
this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier));
return lifecycle_1.toDisposable(function () {
if (_this._entries.get(languageIdentifier.id) === current) {
_this._entries.set(languageIdentifier.id, previous);
_this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageIdentifier));
}
});
};
LanguageConfigurationRegistryImpl.prototype._getRichEditSupport = function (languageId) {
return this._entries.get(languageId);
};
// begin electricCharacter
LanguageConfigurationRegistryImpl.prototype._getElectricCharacterSupport = function (languageId) {
var value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.electricCharacter || null;
};
LanguageConfigurationRegistryImpl.prototype.getElectricCharacters = function (languageId) {
var electricCharacterSupport = this._getElectricCharacterSupport(languageId);
if (!electricCharacterSupport) {
return [];
}
return electricCharacterSupport.getElectricCharacters();
};
/**
* Should return opening bracket type to match indentation with
*/
LanguageConfigurationRegistryImpl.prototype.onElectricCharacter = function (character, context, column) {
var scopedLineTokens = supports_1.createScopedLineTokens(context, column - 1);
var electricCharacterSupport = this._getElectricCharacterSupport(scopedLineTokens.languageId);
if (!electricCharacterSupport) {
return null;
}
return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset);
};
// end electricCharacter
LanguageConfigurationRegistryImpl.prototype.getComments = function (languageId) {
var value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.comments || null;
};
// begin characterPair
LanguageConfigurationRegistryImpl.prototype._getCharacterPairSupport = function (languageId) {
var value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.characterPair || null;
};
LanguageConfigurationRegistryImpl.prototype.getAutoClosingPairs = function (languageId) {
var characterPairSupport = this._getCharacterPairSupport(languageId);
if (!characterPairSupport) {
return [];
}
return characterPairSupport.getAutoClosingPairs();
};
LanguageConfigurationRegistryImpl.prototype.getAutoCloseBeforeSet = function (languageId) {
var characterPairSupport = this._getCharacterPairSupport(languageId);
if (!characterPairSupport) {
return characterPair_1.CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED;
}
return characterPairSupport.getAutoCloseBeforeSet();
};
LanguageConfigurationRegistryImpl.prototype.getSurroundingPairs = function (languageId) {
var characterPairSupport = this._getCharacterPairSupport(languageId);
if (!characterPairSupport) {
return [];
}
return characterPairSupport.getSurroundingPairs();
};
LanguageConfigurationRegistryImpl.prototype.shouldAutoClosePair = function (autoClosingPair, context, column) {
var scopedLineTokens = supports_1.createScopedLineTokens(context, column - 1);
return characterPair_1.CharacterPairSupport.shouldAutoClosePair(autoClosingPair, scopedLineTokens, column - scopedLineTokens.firstCharOffset);
};
// end characterPair
LanguageConfigurationRegistryImpl.prototype.getWordDefinition = function (languageId) {
var value = this._getRichEditSupport(languageId);
if (!value) {
return wordHelper_1.ensureValidWordDefinition(null);
}
return wordHelper_1.ensureValidWordDefinition(value.wordDefinition || null);
};
LanguageConfigurationRegistryImpl.prototype.getFoldingRules = function (languageId) {
var value = this._getRichEditSupport(languageId);
if (!value) {
return {};
}
return value.foldingRules;
};
// begin Indent Rules
LanguageConfigurationRegistryImpl.prototype.getIndentRulesSupport = function (languageId) {
var value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.indentRulesSupport || null;
};
/**
* Get nearest preceiding line which doesn't match unIndentPattern or contains all whitespace.
* Result:
* -1: run into the boundary of embedded languages
* 0: every line above are invalid
* else: nearest preceding line of the same language
*/
LanguageConfigurationRegistryImpl.prototype.getPrecedingValidLine = function (model, lineNumber, indentRulesSupport) {
var languageID = model.getLanguageIdAtPosition(lineNumber, 0);
if (lineNumber > 1) {
var lastLineNumber = void 0;
var resultLineNumber = -1;
for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
if (model.getLanguageIdAtPosition(lastLineNumber, 0) !== languageID) {
return resultLineNumber;
}
var text = model.getLineContent(lastLineNumber);
if (indentRulesSupport.shouldIgnore(text) || /^\s+$/.test(text) || text === '') {
resultLineNumber = lastLineNumber;
continue;
}
return lastLineNumber;
}
}
return -1;
};
/**
* Get inherited indentation from above lines.
* 1. Find the nearest preceding line which doesn't match unIndentedLinePattern.
* 2. If this line matches indentNextLinePattern or increaseIndentPattern, it means that the indent level of `lineNumber` should be 1 greater than this line.
* 3. If this line doesn't match any indent rules
* a. check whether the line above it matches indentNextLinePattern
* b. If not, the indent level of this line is the result
* c. If so, it means the indent of this line is *temporary*, go upward utill we find a line whose indent is not temporary (the same workflow a -> b -> c).
* 4. Otherwise, we fail to get an inherited indent from aboves. Return null and we should not touch the indent of `lineNumber`
*
* This function only return the inherited indent based on above lines, it doesn't check whether current line should decrease or not.
*/
LanguageConfigurationRegistryImpl.prototype.getInheritIndentForLine = function (autoIndent, model, lineNumber, honorIntentialIndent) {
if (honorIntentialIndent === void 0) { honorIntentialIndent = true; }
if (autoIndent < 4 /* Full */) {
return null;
}
var indentRulesSupport = this.getIndentRulesSupport(model.getLanguageIdentifier().id);
if (!indentRulesSupport) {
return null;
}
if (lineNumber <= 1) {
return {
indentation: '',
action: null
};
}
var precedingUnIgnoredLine = this.getPrecedingValidLine(model, lineNumber, indentRulesSupport);
if (precedingUnIgnoredLine < 0) {
return null;
}
else if (precedingUnIgnoredLine < 1) {
return {
indentation: '',
action: null
};
}
var precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
if (indentRulesSupport.shouldIncrease(precedingUnIgnoredLineContent) || indentRulesSupport.shouldIndentNextLine(precedingUnIgnoredLineContent)) {
return {
indentation: strings.getLeadingWhitespace(precedingUnIgnoredLineContent),
action: languageConfiguration_1.IndentAction.Indent,
line: precedingUnIgnoredLine
};
}
else if (indentRulesSupport.shouldDecrease(precedingUnIgnoredLineContent)) {
return {
indentation: strings.getLeadingWhitespace(precedingUnIgnoredLineContent),
action: null,
line: precedingUnIgnoredLine
};
}
else {
// precedingUnIgnoredLine can not be ignored.
// it doesn't increase indent of following lines
// it doesn't increase just next line
// so current line is not affect by precedingUnIgnoredLine
// and then we should get a correct inheritted indentation from above lines
if (precedingUnIgnoredLine === 1) {
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
action: null,
line: precedingUnIgnoredLine
};
}
var previousLine = precedingUnIgnoredLine - 1;
var previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine));
if (!(previousLineIndentMetadata & (1 /* INCREASE_MASK */ | 2 /* DECREASE_MASK */)) &&
(previousLineIndentMetadata & 4 /* INDENT_NEXTLINE_MASK */)) {
var stopLine = 0;
for (var i = previousLine - 1; i > 0; i--) {
if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i))) {
continue;
}
stopLine = i;
break;
}
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(stopLine + 1)),
action: null,
line: stopLine + 1
};
}
if (honorIntentialIndent) {
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
action: null,
line: precedingUnIgnoredLine
};
}
else {
// search from precedingUnIgnoredLine until we find one whose indent is not temporary
for (var i = precedingUnIgnoredLine; i > 0; i--) {
var lineContent = model.getLineContent(i);
if (indentRulesSupport.shouldIncrease(lineContent)) {
return {
indentation: strings.getLeadingWhitespace(lineContent),
action: languageConfiguration_1.IndentAction.Indent,
line: i
};
}
else if (indentRulesSupport.shouldIndentNextLine(lineContent)) {
var stopLine = 0;
for (var j = i - 1; j > 0; j--) {
if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i))) {
continue;
}
stopLine = j;
break;
}
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(stopLine + 1)),
action: null,
line: stopLine + 1
};
}
else if (indentRulesSupport.shouldDecrease(lineContent)) {
return {
indentation: strings.getLeadingWhitespace(lineContent),
action: null,
line: i
};
}
}
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(1)),
action: null,
line: 1
};
}
}
};
LanguageConfigurationRegistryImpl.prototype.getGoodIndentForLine = function (autoIndent, virtualModel, languageId, lineNumber, indentConverter) {
if (autoIndent < 4 /* Full */) {
return null;
}
var richEditSupport = this._getRichEditSupport(languageId);
if (!richEditSupport) {
return null;
}
var indentRulesSupport = this.getIndentRulesSupport(languageId);
if (!indentRulesSupport) {
return null;
}
var indent = this.getInheritIndentForLine(autoIndent, virtualModel, lineNumber);
var lineContent = virtualModel.getLineContent(lineNumber);
if (indent) {
var inheritLine = indent.line;
if (inheritLine !== undefined) {
var enterResult = richEditSupport.onEnter(autoIndent, '', virtualModel.getLineContent(inheritLine), '');
if (enterResult) {
var indentation = strings.getLeadingWhitespace(virtualModel.getLineContent(inheritLine));
if (enterResult.removeText) {
indentation = indentation.substring(0, indentation.length - enterResult.removeText);
}
if ((enterResult.indentAction === languageConfiguration_1.IndentAction.Indent) ||
(enterResult.indentAction === languageConfiguration_1.IndentAction.IndentOutdent)) {
indentation = indentConverter.shiftIndent(indentation);
}
else if (enterResult.indentAction === languageConfiguration_1.IndentAction.Outdent) {
indentation = indentConverter.unshiftIndent(indentation);
}
if (indentRulesSupport.shouldDecrease(lineContent)) {
indentation = indentConverter.unshiftIndent(indentation);
}
if (enterResult.appendText) {
indentation += enterResult.appendText;
}
return strings.getLeadingWhitespace(indentation);
}
}
if (indentRulesSupport.shouldDecrease(lineContent)) {
if (indent.action === languageConfiguration_1.IndentAction.Indent) {
return indent.indentation;
}
else {
return indentConverter.unshiftIndent(indent.indentation);
}
}
else {
if (indent.action === languageConfiguration_1.IndentAction.Indent) {
return indentConverter.shiftIndent(indent.indentation);
}
else {
return indent.indentation;
}
}
}
return null;
};
LanguageConfigurationRegistryImpl.prototype.getIndentForEnter = function (autoIndent, model, range, indentConverter) {
if (autoIndent < 4 /* Full */) {
return null;
}
model.forceTokenization(range.startLineNumber);
var lineTokens = model.getLineTokens(range.startLineNumber);
var scopedLineTokens = supports_1.createScopedLineTokens(lineTokens, range.startColumn - 1);
var scopedLineText = scopedLineTokens.getLineContent();
var embeddedLanguage = false;
var beforeEnterText;
if (scopedLineTokens.firstCharOffset > 0 && lineTokens.getLanguageId(0) !== scopedLineTokens.languageId) {
// we are in the embeded language content
embeddedLanguage = true; // if embeddedLanguage is true, then we don't touch the indentation of current line
beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
}
else {
beforeEnterText = lineTokens.getLineContent().substring(0, range.startColumn - 1);
}
var afterEnterText;
if (range.isEmpty()) {
afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
}
else {
var endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn);
afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
}
var indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId);
if (!indentRulesSupport) {
return null;
}
var beforeEnterResult = beforeEnterText;
var beforeEnterIndent = strings.getLeadingWhitespace(beforeEnterText);
var virtualModel = {
getLineTokens: function (lineNumber) {
return model.getLineTokens(lineNumber);
},
getLanguageIdentifier: function () {
return model.getLanguageIdentifier();
},
getLanguageIdAtPosition: function (lineNumber, column) {
return model.getLanguageIdAtPosition(lineNumber, column);
},
getLineContent: function (lineNumber) {
if (lineNumber === range.startLineNumber) {
return beforeEnterResult;
}
else {
return model.getLineContent(lineNumber);
}
}
};
var currentLineIndent = strings.getLeadingWhitespace(lineTokens.getLineContent());
var afterEnterAction = this.getInheritIndentForLine(autoIndent, virtualModel, range.startLineNumber + 1);
if (!afterEnterAction) {
var beforeEnter = embeddedLanguage ? currentLineIndent : beforeEnterIndent;
return {
beforeEnter: beforeEnter,
afterEnter: beforeEnter
};
}
var afterEnterIndent = embeddedLanguage ? currentLineIndent : afterEnterAction.indentation;
if (afterEnterAction.action === languageConfiguration_1.IndentAction.Indent) {
afterEnterIndent = indentConverter.shiftIndent(afterEnterIndent);
}
if (indentRulesSupport.shouldDecrease(afterEnterText)) {
afterEnterIndent = indentConverter.unshiftIndent(afterEnterIndent);
}
return {
beforeEnter: embeddedLanguage ? currentLineIndent : beforeEnterIndent,
afterEnter: afterEnterIndent
};
};
/**
* We should always allow intentional indentation. It means, if users change the indentation of `lineNumber` and the content of
* this line doesn't match decreaseIndentPattern, we should not adjust the indentation.
*/
LanguageConfigurationRegistryImpl.prototype.getIndentActionForType = function (autoIndent, model, range, ch, indentConverter) {
if (autoIndent < 4 /* Full */) {
return null;
}
var scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber, range.startColumn);
var indentRulesSupport = this.getIndentRulesSupport(scopedLineTokens.languageId);
if (!indentRulesSupport) {
return null;
}
var scopedLineText = scopedLineTokens.getLineContent();
var beforeTypeText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
// selection support
var afterTypeText;
if (range.isEmpty()) {
afterTypeText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
}
else {
var endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn);
afterTypeText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
}
// If previous content already matches decreaseIndentPattern, it means indentation of this line should already be adjusted
// Users might change the indentation by purpose and we should honor that instead of readjusting.
if (!indentRulesSupport.shouldDecrease(beforeTypeText + afterTypeText) && indentRulesSupport.shouldDecrease(beforeTypeText + ch + afterTypeText)) {
// after typing `ch`, the content matches decreaseIndentPattern, we should adjust the indent to a good manner.
// 1. Get inherited indent action
var r = this.getInheritIndentForLine(autoIndent, model, range.startLineNumber, false);
if (!r) {
return null;
}
var indentation = r.indentation;
if (r.action !== languageConfiguration_1.IndentAction.Indent) {
indentation = indentConverter.unshiftIndent(indentation);
}
return indentation;
}
return null;
};
LanguageConfigurationRegistryImpl.prototype.getIndentMetadata = function (model, lineNumber) {
var indentRulesSupport = this.getIndentRulesSupport(model.getLanguageIdentifier().id);
if (!indentRulesSupport) {
return null;
}
if (lineNumber < 1 || lineNumber > model.getLineCount()) {
return null;
}
return indentRulesSupport.getIndentMetadata(model.getLineContent(lineNumber));
};
// end Indent Rules
// begin onEnter
LanguageConfigurationRegistryImpl.prototype.getEnterAction = function (autoIndent, model, range) {
var scopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber, range.startColumn);
var richEditSupport = this._getRichEditSupport(scopedLineTokens.languageId);
if (!richEditSupport) {
return null;
}
var scopedLineText = scopedLineTokens.getLineContent();
var beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
// selection support
var afterEnterText;
if (range.isEmpty()) {
afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
}
else {
var endScopedLineTokens = this.getScopedLineTokens(model, range.endLineNumber, range.endColumn);
afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
}
var oneLineAboveText = '';
if (range.startLineNumber > 1 && scopedLineTokens.firstCharOffset === 0) {
// This is not the first line and the entire line belongs to this mode
var oneLineAboveScopedLineTokens = this.getScopedLineTokens(model, range.startLineNumber - 1);
if (oneLineAboveScopedLineTokens.languageId === scopedLineTokens.languageId) {
// The line above ends with text belonging to the same mode
oneLineAboveText = oneLineAboveScopedLineTokens.getLineContent();
}
}
var enterResult = richEditSupport.onEnter(autoIndent, oneLineAboveText, beforeEnterText, afterEnterText);
if (!enterResult) {
return null;
}
var indentAction = enterResult.indentAction;
var appendText = enterResult.appendText;
var removeText = enterResult.removeText || 0;
// Here we add `\t` to appendText first because enterAction is leveraging appendText and removeText to change indentation.
if (!appendText) {
if ((indentAction === languageConfiguration_1.IndentAction.Indent) ||
(indentAction === languageConfiguration_1.IndentAction.IndentOutdent)) {
appendText = '\t';
}
else {
appendText = '';
}
}
var indentation = this.getIndentationAtPosition(model, range.startLineNumber, range.startColumn);
if (removeText) {
indentation = indentation.substring(0, indentation.length - removeText);
}
return {
indentAction: indentAction,
appendText: appendText,
removeText: removeText,
indentation: indentation
};
};
LanguageConfigurationRegistryImpl.prototype.getIndentationAtPosition = function (model, lineNumber, column) {
var lineText = model.getLineContent(lineNumber);
var indentation = strings.getLeadingWhitespace(lineText);
if (indentation.length > column - 1) {
indentation = indentation.substring(0, column - 1);
}
return indentation;
};
LanguageConfigurationRegistryImpl.prototype.getScopedLineTokens = function (model, lineNumber, columnNumber) {
model.forceTokenization(lineNumber);
var lineTokens = model.getLineTokens(lineNumber);
var column = (typeof columnNumber === 'undefined' ? model.getLineMaxColumn(lineNumber) - 1 : columnNumber - 1);
return supports_1.createScopedLineTokens(lineTokens, column);
};
// end onEnter
LanguageConfigurationRegistryImpl.prototype.getBracketsSupport = function (languageId) {
var value = this._getRichEditSupport(languageId);
if (!value) {
return null;
}
return value.brackets || null;
};
return LanguageConfigurationRegistryImpl;
}());
exports.LanguageConfigurationRegistryImpl = LanguageConfigurationRegistryImpl;
exports.LanguageConfigurationRegistry = new LanguageConfigurationRegistryImpl();
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[357/*vs/editor/common/modes/supports/tokenization*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/color*/]), function (require, exports, color_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ParsedTokenThemeRule = /** @class */ (function () {
function ParsedTokenThemeRule(token, index, fontStyle, foreground, background) {
this.token = token;
this.index = index;
this.fontStyle = fontStyle;
this.foreground = foreground;
this.background = background;
}
return ParsedTokenThemeRule;
}());
exports.ParsedTokenThemeRule = ParsedTokenThemeRule;
/**
* Parse a raw theme into rules.
*/
function parseTokenTheme(source) {
if (!source || !Array.isArray(source)) {
return [];
}
var result = [], resultLen = 0;
for (var i = 0, len = source.length; i < len; i++) {
var entry = source[i];
var fontStyle = -1 /* NotSet */;
if (typeof entry.fontStyle === 'string') {
fontStyle = 0 /* None */;
var segments = entry.fontStyle.split(' ');
for (var j = 0, lenJ = segments.length; j < lenJ; j++) {
var segment = segments[j];
switch (segment) {
case 'italic':
fontStyle = fontStyle | 1 /* Italic */;
break;
case 'bold':
fontStyle = fontStyle | 2 /* Bold */;
break;
case 'underline':
fontStyle = fontStyle | 4 /* Underline */;
break;
}
}
}
var foreground = null;
if (typeof entry.foreground === 'string') {
foreground = entry.foreground;
}
var background = null;
if (typeof entry.background === 'string') {
background = entry.background;
}
result[resultLen++] = new ParsedTokenThemeRule(entry.token || '', i, fontStyle, foreground, background);
}
return result;
}
exports.parseTokenTheme = parseTokenTheme;
/**
* Resolve rules (i.e. inheritance).
*/
function resolveParsedTokenThemeRules(parsedThemeRules, customTokenColors) {
// Sort rules lexicographically, and then by index if necessary
parsedThemeRules.sort(function (a, b) {
var r = strcmp(a.token, b.token);
if (r !== 0) {
return r;
}
return a.index - b.index;
});
// Determine defaults
var defaultFontStyle = 0 /* None */;
var defaultForeground = '000000';
var defaultBackground = 'ffffff';
while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === '') {
var incomingDefaults = parsedThemeRules.shift();
if (incomingDefaults.fontStyle !== -1 /* NotSet */) {
defaultFontStyle = incomingDefaults.fontStyle;
}
if (incomingDefaults.foreground !== null) {
defaultForeground = incomingDefaults.foreground;
}
if (incomingDefaults.background !== null) {
defaultBackground = incomingDefaults.background;
}
}
var colorMap = new ColorMap();
// start with token colors from custom token themes
for (var _i = 0, customTokenColors_1 = customTokenColors; _i < customTokenColors_1.length; _i++) {
var color = customTokenColors_1[_i];
colorMap.getId(color);
}
var foregroundColorId = colorMap.getId(defaultForeground);
var backgroundColorId = colorMap.getId(defaultBackground);
var defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId);
var root = new ThemeTrieElement(defaults);
for (var i = 0, len = parsedThemeRules.length; i < len; i++) {
var rule = parsedThemeRules[i];
root.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));
}
return new TokenTheme(colorMap, root);
}
var colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/;
var ColorMap = /** @class */ (function () {
function ColorMap() {
this._lastColorId = 0;
this._id2color = [];
this._color2id = new Map();
}
ColorMap.prototype.getId = function (color) {
if (color === null) {
return 0;
}
var match = color.match(colorRegExp);
if (!match) {
throw new Error('Illegal value for token color: ' + color);
}
color = match[1].toUpperCase();
var value = this._color2id.get(color);
if (value) {
return value;
}
value = ++this._lastColorId;
this._color2id.set(color, value);
this._id2color[value] = color_1.Color.fromHex('#' + color);
return value;
};
ColorMap.prototype.getColorMap = function () {
return this._id2color.slice(0);
};
return ColorMap;
}());
exports.ColorMap = ColorMap;
var TokenTheme = /** @class */ (function () {
function TokenTheme(colorMap, root) {
this._colorMap = colorMap;
this._root = root;
this._cache = new Map();
}
TokenTheme.createFromRawTokenTheme = function (source, customTokenColors) {
return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors);
};
TokenTheme.createFromParsedTokenTheme = function (source, customTokenColors) {
return resolveParsedTokenThemeRules(source, customTokenColors);
};
TokenTheme.prototype.getColorMap = function () {
return this._colorMap.getColorMap();
};
TokenTheme.prototype._match = function (token) {
return this._root.match(token);
};
TokenTheme.prototype.match = function (languageId, token) {
// The cache contains the metadata without the language bits set.
var result = this._cache.get(token);
if (typeof result === 'undefined') {
var rule = this._match(token);
var standardToken = toStandardTokenType(token);
result = (rule.metadata
| (standardToken << 8 /* TOKEN_TYPE_OFFSET */)) >>> 0;
this._cache.set(token, result);
}
return (result
| (languageId << 0 /* LANGUAGEID_OFFSET */)) >>> 0;
};
return TokenTheme;
}());
exports.TokenTheme = TokenTheme;
var STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/;
function toStandardTokenType(tokenType) {
var m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP);
if (!m) {
return 0 /* Other */;
}
switch (m[1]) {
case 'comment':
return 1 /* Comment */;
case 'string':
return 2 /* String */;
case 'regex':
return 4 /* RegEx */;
case 'regexp':
return 4 /* RegEx */;
}
throw new Error('Unexpected match for standard token type!');
}
exports.toStandardTokenType = toStandardTokenType;
function strcmp(a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
exports.strcmp = strcmp;
var ThemeTrieElementRule = /** @class */ (function () {
function ThemeTrieElementRule(fontStyle, foreground, background) {
this._fontStyle = fontStyle;
this._foreground = foreground;
this._background = background;
this.metadata = ((this._fontStyle << 11 /* FONT_STYLE_OFFSET */)
| (this._foreground << 14 /* FOREGROUND_OFFSET */)
| (this._background << 23 /* BACKGROUND_OFFSET */)) >>> 0;
}
ThemeTrieElementRule.prototype.clone = function () {
return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background);
};
ThemeTrieElementRule.prototype.acceptOverwrite = function (fontStyle, foreground, background) {
if (fontStyle !== -1 /* NotSet */) {
this._fontStyle = fontStyle;
}
if (foreground !== 0 /* None */) {
this._foreground = foreground;
}
if (background !== 0 /* None */) {
this._background = background;
}
this.metadata = ((this._fontStyle << 11 /* FONT_STYLE_OFFSET */)
| (this._foreground << 14 /* FOREGROUND_OFFSET */)
| (this._background << 23 /* BACKGROUND_OFFSET */)) >>> 0;
};
return ThemeTrieElementRule;
}());
exports.ThemeTrieElementRule = ThemeTrieElementRule;
var ThemeTrieElement = /** @class */ (function () {
function ThemeTrieElement(mainRule) {
this._mainRule = mainRule;
this._children = new Map();
}
ThemeTrieElement.prototype.match = function (token) {
if (token === '') {
return this._mainRule;
}
var dotIndex = token.indexOf('.');
var head;
var tail;
if (dotIndex === -1) {
head = token;
tail = '';
}
else {
head = token.substring(0, dotIndex);
tail = token.substring(dotIndex + 1);
}
var child = this._children.get(head);
if (typeof child !== 'undefined') {
return child.match(tail);
}
return this._mainRule;
};
ThemeTrieElement.prototype.insert = function (token, fontStyle, foreground, background) {
if (token === '') {
// Merge into the main rule
this._mainRule.acceptOverwrite(fontStyle, foreground, background);
return;
}
var dotIndex = token.indexOf('.');
var head;
var tail;
if (dotIndex === -1) {
head = token;
tail = '';
}
else {
head = token.substring(0, dotIndex);
tail = token.substring(dotIndex + 1);
}
var child = this._children.get(head);
if (typeof child === 'undefined') {
child = new ThemeTrieElement(this._mainRule.clone());
this._children.set(head, child);
}
child.insert(tail, fontStyle, foreground, background);
};
return ThemeTrieElement;
}());
exports.ThemeTrieElement = ThemeTrieElement;
function generateTokensCSSForColorMap(colorMap) {
var rules = [];
for (var i = 1, len = colorMap.length; i < len; i++) {
var color = colorMap[i];
rules[i] = ".mtk" + i + " { color: " + color + "; }";
}
rules.push('.mtki { font-style: italic; }');
rules.push('.mtkb { font-weight: bold; }');
rules.push('.mtku { text-decoration: underline; text-underline-position: under; }');
return rules.join('\n');
}
exports.generateTokensCSSForColorMap = generateTokensCSSForColorMap;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[358/*vs/editor/common/modes/tokenizationRegistry*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/types*/,38/*vs/base/common/map*/]), function (require, exports, event_1, lifecycle_1, types_1, map_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TokenizationRegistryImpl = /** @class */ (function () {
function TokenizationRegistryImpl() {
this._map = new Map();
this._promises = new Map();
this._onDidChange = new event_1.Emitter();
this.onDidChange = this._onDidChange.event;
this._colorMap = null;
}
TokenizationRegistryImpl.prototype.fire = function (languages) {
this._onDidChange.fire({
changedLanguages: languages,
changedColorMap: false
});
};
TokenizationRegistryImpl.prototype.register = function (language, support) {
var _this = this;
this._map.set(language, support);
this.fire([language]);
return lifecycle_1.toDisposable(function () {
if (_this._map.get(language) !== support) {
return;
}
_this._map.delete(language);
_this.fire([language]);
});
};
TokenizationRegistryImpl.prototype.registerPromise = function (language, supportPromise) {
var _this = this;
var registration = null;
var isDisposed = false;
this._promises.set(language, supportPromise.then(function (support) {
_this._promises.delete(language);
if (isDisposed || !support) {
return;
}
registration = _this.register(language, support);
}));
return lifecycle_1.toDisposable(function () {
isDisposed = true;
if (registration) {
registration.dispose();
}
});
};
TokenizationRegistryImpl.prototype.getPromise = function (language) {
var _this = this;
var support = this.get(language);
if (support) {
return Promise.resolve(support);
}
var promise = this._promises.get(language);
if (promise) {
return promise.then(function (_) { return _this.get(language); });
}
return null;
};
TokenizationRegistryImpl.prototype.get = function (language) {
return types_1.withUndefinedAsNull(this._map.get(language));
};
TokenizationRegistryImpl.prototype.setColorMap = function (colorMap) {
this._colorMap = colorMap;
this._onDidChange.fire({
changedLanguages: map_1.keys(this._map),
changedColorMap: true
});
};
TokenizationRegistryImpl.prototype.getColorMap = function () {
return this._colorMap;
};
TokenizationRegistryImpl.prototype.getDefaultBackground = function () {
if (this._colorMap && this._colorMap.length > 2 /* DefaultBackground */) {
return this._colorMap[2 /* DefaultBackground */];
}
return null;
};
return TokenizationRegistryImpl;
}());
exports.TokenizationRegistryImpl = TokenizationRegistryImpl;
});
/*!
Copyright (c) 2014 Taylor Hakes
Copyright (c) 2014 Forbes Lindesay
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define("vs/editor/common/standalone/promise-polyfill/polyfill", factory) :
(factory());
}(this, (function () {
'use strict';
/**
* @this {Promise}
*/
function finallyConstructor(callback) {
var constructor = this.constructor;
return this.then(
function (value) {
return constructor.resolve(callback()).then(function () {
return value;
});
},
function (reason) {
return constructor.resolve(callback()).then(function () {
return constructor.reject(reason);
});
}
);
}
// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;
function noop() { }
// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
return function () {
fn.apply(thisArg, arguments);
};
}
/**
* @constructor
* @param {Function} fn
*/
function Promise(fn) {
if (!(this instanceof Promise))
throw new TypeError('Promises must be constructed via new');
if (typeof fn !== 'function') throw new TypeError('not a function');
/** @type {!number} */
this._state = 0;
/** @type {!boolean} */
this._handled = false;
/** @type {Promise|undefined} */
this._value = undefined;
/** @type {!Array} */
this._deferreds = [];
doResolve(fn, this);
}
function handle(self, deferred) {
while (self._state === 3) {
self = self._value;
}
if (self._state === 0) {
self._deferreds.push(deferred);
return;
}
self._handled = true;
Promise._immediateFn(function () {
var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
if (cb === null) {
(self._state === 1 ? resolve : reject)(deferred.promise, self._value);
return;
}
var ret;
try {
ret = cb(self._value);
} catch (e) {
reject(deferred.promise, e);
return;
}
resolve(deferred.promise, ret);
});
}
function resolve(self, newValue) {
try {
// Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self)
throw new TypeError('A promise cannot be resolved with itself.');
if (
newValue &&
(typeof newValue === 'object' || typeof newValue === 'function')
) {
var then = newValue.then;
if (newValue instanceof Promise) {
self._state = 3;
self._value = newValue;
finale(self);
return;
} else if (typeof then === 'function') {
doResolve(bind(then, newValue), self);
return;
}
}
self._state = 1;
self._value = newValue;
finale(self);
} catch (e) {
reject(self, e);
}
}
function reject(self, newValue) {
self._state = 2;
self._value = newValue;
finale(self);
}
function finale(self) {
if (self._state === 2 && self._deferreds.length === 0) {
Promise._immediateFn(function () {
if (!self._handled) {
Promise._unhandledRejectionFn(self._value);
}
});
}
for (var i = 0, len = self._deferreds.length; i < len; i++) {
handle(self, self._deferreds[i]);
}
self._deferreds = null;
}
/**
* @constructor
*/
function Handler(onFulfilled, onRejected, promise) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.promise = promise;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, self) {
var done = false;
try {
fn(
function (value) {
if (done) return;
done = true;
resolve(self, value);
},
function (reason) {
if (done) return;
done = true;
reject(self, reason);
}
);
} catch (ex) {
if (done) return;
done = true;
reject(self, ex);
}
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
// @ts-ignore
var prom = new this.constructor(noop);
handle(this, new Handler(onFulfilled, onRejected, prom));
return prom;
};
Promise.prototype['finally'] = finallyConstructor;
Promise.all = function (arr) {
return new Promise(function (resolve, reject) {
if (!arr || typeof arr.length === 'undefined')
throw new TypeError('Promise.all accepts an array');
var args = Array.prototype.slice.call(arr);
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then;
if (typeof then === 'function') {
then.call(
val,
function (val) {
res(i, val);
},
reject
);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
Promise.resolve = function (value) {
if (value && typeof value === 'object' && value.constructor === Promise) {
return value;
}
return new Promise(function (resolve) {
resolve(value);
});
};
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
};
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
for (var i = 0, len = values.length; i < len; i++) {
values[i].then(resolve, reject);
}
});
};
// Use polyfill for setImmediate for performance gains
Promise._immediateFn =
(typeof setImmediate === 'function' &&
function (fn) {
setImmediate(fn);
}) ||
function (fn) {
setTimeoutFunc(fn, 0);
};
Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
if (typeof console !== 'undefined' && console) {
console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
}
};
/** @suppress {undefinedVars} */
var globalNS = (function () {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') {
return self;
}
if (typeof window !== 'undefined') {
return window;
}
if (typeof global !== 'undefined') {
return global;
}
throw new Error('unable to locate global object');
})();
if (!('Promise' in globalNS)) {
globalNS['Promise'] = Promise;
} else if (!globalNS.Promise.prototype['finally']) {
globalNS.Promise.prototype['finally'] = finallyConstructor;
}
})));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[147/*vs/editor/common/standalone/standaloneEnums*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// THIS IS A GENERATED FILE. DO NOT EDIT DIRECTLY.
var AccessibilitySupport;
(function (AccessibilitySupport) {
/**
* This should be the browser case where it is not known if a screen reader is attached or no.
*/
AccessibilitySupport[AccessibilitySupport["Unknown"] = 0] = "Unknown";
AccessibilitySupport[AccessibilitySupport["Disabled"] = 1] = "Disabled";
AccessibilitySupport[AccessibilitySupport["Enabled"] = 2] = "Enabled";
})(AccessibilitySupport = exports.AccessibilitySupport || (exports.AccessibilitySupport = {}));
var CompletionItemInsertTextRule;
(function (CompletionItemInsertTextRule) {
/**
* Adjust whitespace/indentation of multiline insert texts to
* match the current line indentation.
*/
CompletionItemInsertTextRule[CompletionItemInsertTextRule["KeepWhitespace"] = 1] = "KeepWhitespace";
/**
* `insertText` is a snippet.
*/
CompletionItemInsertTextRule[CompletionItemInsertTextRule["InsertAsSnippet"] = 4] = "InsertAsSnippet";
})(CompletionItemInsertTextRule = exports.CompletionItemInsertTextRule || (exports.CompletionItemInsertTextRule = {}));
var CompletionItemKind;
(function (CompletionItemKind) {
CompletionItemKind[CompletionItemKind["Method"] = 0] = "Method";
CompletionItemKind[CompletionItemKind["Function"] = 1] = "Function";
CompletionItemKind[CompletionItemKind["Constructor"] = 2] = "Constructor";
CompletionItemKind[CompletionItemKind["Field"] = 3] = "Field";
CompletionItemKind[CompletionItemKind["Variable"] = 4] = "Variable";
CompletionItemKind[CompletionItemKind["Class"] = 5] = "Class";
CompletionItemKind[CompletionItemKind["Struct"] = 6] = "Struct";
CompletionItemKind[CompletionItemKind["Interface"] = 7] = "Interface";
CompletionItemKind[CompletionItemKind["Module"] = 8] = "Module";
CompletionItemKind[CompletionItemKind["Property"] = 9] = "Property";
CompletionItemKind[CompletionItemKind["Event"] = 10] = "Event";
CompletionItemKind[CompletionItemKind["Operator"] = 11] = "Operator";
CompletionItemKind[CompletionItemKind["Unit"] = 12] = "Unit";
CompletionItemKind[CompletionItemKind["Value"] = 13] = "Value";
CompletionItemKind[CompletionItemKind["Constant"] = 14] = "Constant";
CompletionItemKind[CompletionItemKind["Enum"] = 15] = "Enum";
CompletionItemKind[CompletionItemKind["EnumMember"] = 16] = "EnumMember";
CompletionItemKind[CompletionItemKind["Keyword"] = 17] = "Keyword";
CompletionItemKind[CompletionItemKind["Text"] = 18] = "Text";
CompletionItemKind[CompletionItemKind["Color"] = 19] = "Color";
CompletionItemKind[CompletionItemKind["File"] = 20] = "File";
CompletionItemKind[CompletionItemKind["Reference"] = 21] = "Reference";
CompletionItemKind[CompletionItemKind["Customcolor"] = 22] = "Customcolor";
CompletionItemKind[CompletionItemKind["Folder"] = 23] = "Folder";
CompletionItemKind[CompletionItemKind["TypeParameter"] = 24] = "TypeParameter";
CompletionItemKind[CompletionItemKind["Snippet"] = 25] = "Snippet";
})(CompletionItemKind = exports.CompletionItemKind || (exports.CompletionItemKind = {}));
var CompletionItemTag;
(function (CompletionItemTag) {
CompletionItemTag[CompletionItemTag["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag = exports.CompletionItemTag || (exports.CompletionItemTag = {}));
/**
* How a suggest provider was triggered.
*/
var CompletionTriggerKind;
(function (CompletionTriggerKind) {
CompletionTriggerKind[CompletionTriggerKind["Invoke"] = 0] = "Invoke";
CompletionTriggerKind[CompletionTriggerKind["TriggerCharacter"] = 1] = "TriggerCharacter";
CompletionTriggerKind[CompletionTriggerKind["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
})(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
/**
* A positioning preference for rendering content widgets.
*/
var ContentWidgetPositionPreference;
(function (ContentWidgetPositionPreference) {
/**
* Place the content widget exactly at a position
*/
ContentWidgetPositionPreference[ContentWidgetPositionPreference["EXACT"] = 0] = "EXACT";
/**
* Place the content widget above a position
*/
ContentWidgetPositionPreference[ContentWidgetPositionPreference["ABOVE"] = 1] = "ABOVE";
/**
* Place the content widget below a position
*/
ContentWidgetPositionPreference[ContentWidgetPositionPreference["BELOW"] = 2] = "BELOW";
})(ContentWidgetPositionPreference = exports.ContentWidgetPositionPreference || (exports.ContentWidgetPositionPreference = {}));
/**
* Describes the reason the cursor has changed its position.
*/
var CursorChangeReason;
(function (CursorChangeReason) {
/**
* Unknown or not set.
*/
CursorChangeReason[CursorChangeReason["NotSet"] = 0] = "NotSet";
/**
* A `model.setValue()` was called.
*/
CursorChangeReason[CursorChangeReason["ContentFlush"] = 1] = "ContentFlush";
/**
* The `model` has been changed outside of this cursor and the cursor recovers its position from associated markers.
*/
CursorChangeReason[CursorChangeReason["RecoverFromMarkers"] = 2] = "RecoverFromMarkers";
/**
* There was an explicit user gesture.
*/
CursorChangeReason[CursorChangeReason["Explicit"] = 3] = "Explicit";
/**
* There was a Paste.
*/
CursorChangeReason[CursorChangeReason["Paste"] = 4] = "Paste";
/**
* There was an Undo.
*/
CursorChangeReason[CursorChangeReason["Undo"] = 5] = "Undo";
/**
* There was a Redo.
*/
CursorChangeReason[CursorChangeReason["Redo"] = 6] = "Redo";
})(CursorChangeReason = exports.CursorChangeReason || (exports.CursorChangeReason = {}));
/**
* The default end of line to use when instantiating models.
*/
var DefaultEndOfLine;
(function (DefaultEndOfLine) {
/**
* Use line feed (\n) as the end of line character.
*/
DefaultEndOfLine[DefaultEndOfLine["LF"] = 1] = "LF";
/**
* Use carriage return and line feed (\r\n) as the end of line character.
*/
DefaultEndOfLine[DefaultEndOfLine["CRLF"] = 2] = "CRLF";
})(DefaultEndOfLine = exports.DefaultEndOfLine || (exports.DefaultEndOfLine = {}));
/**
* A document highlight kind.
*/
var DocumentHighlightKind;
(function (DocumentHighlightKind) {
/**
* A textual occurrence.
*/
DocumentHighlightKind[DocumentHighlightKind["Text"] = 0] = "Text";
/**
* Read-access of a symbol, like reading a variable.
*/
DocumentHighlightKind[DocumentHighlightKind["Read"] = 1] = "Read";
/**
* Write-access of a symbol, like writing to a variable.
*/
DocumentHighlightKind[DocumentHighlightKind["Write"] = 2] = "Write";
})(DocumentHighlightKind = exports.DocumentHighlightKind || (exports.DocumentHighlightKind = {}));
/**
* Configuration options for auto indentation in the editor
*/
var EditorAutoIndentStrategy;
(function (EditorAutoIndentStrategy) {
EditorAutoIndentStrategy[EditorAutoIndentStrategy["None"] = 0] = "None";
EditorAutoIndentStrategy[EditorAutoIndentStrategy["Keep"] = 1] = "Keep";
EditorAutoIndentStrategy[EditorAutoIndentStrategy["Brackets"] = 2] = "Brackets";
EditorAutoIndentStrategy[EditorAutoIndentStrategy["Advanced"] = 3] = "Advanced";
EditorAutoIndentStrategy[EditorAutoIndentStrategy["Full"] = 4] = "Full";
})(EditorAutoIndentStrategy = exports.EditorAutoIndentStrategy || (exports.EditorAutoIndentStrategy = {}));
var EditorOption;
(function (EditorOption) {
EditorOption[EditorOption["acceptSuggestionOnCommitCharacter"] = 0] = "acceptSuggestionOnCommitCharacter";
EditorOption[EditorOption["acceptSuggestionOnEnter"] = 1] = "acceptSuggestionOnEnter";
EditorOption[EditorOption["accessibilitySupport"] = 2] = "accessibilitySupport";
EditorOption[EditorOption["accessibilityPageSize"] = 3] = "accessibilityPageSize";
EditorOption[EditorOption["ariaLabel"] = 4] = "ariaLabel";
EditorOption[EditorOption["autoClosingBrackets"] = 5] = "autoClosingBrackets";
EditorOption[EditorOption["autoClosingOvertype"] = 6] = "autoClosingOvertype";
EditorOption[EditorOption["autoClosingQuotes"] = 7] = "autoClosingQuotes";
EditorOption[EditorOption["autoIndent"] = 8] = "autoIndent";
EditorOption[EditorOption["automaticLayout"] = 9] = "automaticLayout";
EditorOption[EditorOption["autoSurround"] = 10] = "autoSurround";
EditorOption[EditorOption["codeLens"] = 11] = "codeLens";
EditorOption[EditorOption["colorDecorators"] = 12] = "colorDecorators";
EditorOption[EditorOption["comments"] = 13] = "comments";
EditorOption[EditorOption["contextmenu"] = 14] = "contextmenu";
EditorOption[EditorOption["copyWithSyntaxHighlighting"] = 15] = "copyWithSyntaxHighlighting";
EditorOption[EditorOption["cursorBlinking"] = 16] = "cursorBlinking";
EditorOption[EditorOption["cursorSmoothCaretAnimation"] = 17] = "cursorSmoothCaretAnimation";
EditorOption[EditorOption["cursorStyle"] = 18] = "cursorStyle";
EditorOption[EditorOption["cursorSurroundingLines"] = 19] = "cursorSurroundingLines";
EditorOption[EditorOption["cursorSurroundingLinesStyle"] = 20] = "cursorSurroundingLinesStyle";
EditorOption[EditorOption["cursorWidth"] = 21] = "cursorWidth";
EditorOption[EditorOption["disableLayerHinting"] = 22] = "disableLayerHinting";
EditorOption[EditorOption["disableMonospaceOptimizations"] = 23] = "disableMonospaceOptimizations";
EditorOption[EditorOption["dragAndDrop"] = 24] = "dragAndDrop";
EditorOption[EditorOption["emptySelectionClipboard"] = 25] = "emptySelectionClipboard";
EditorOption[EditorOption["extraEditorClassName"] = 26] = "extraEditorClassName";
EditorOption[EditorOption["fastScrollSensitivity"] = 27] = "fastScrollSensitivity";
EditorOption[EditorOption["find"] = 28] = "find";
EditorOption[EditorOption["fixedOverflowWidgets"] = 29] = "fixedOverflowWidgets";
EditorOption[EditorOption["folding"] = 30] = "folding";
EditorOption[EditorOption["foldingStrategy"] = 31] = "foldingStrategy";
EditorOption[EditorOption["foldingHighlight"] = 32] = "foldingHighlight";
EditorOption[EditorOption["fontFamily"] = 33] = "fontFamily";
EditorOption[EditorOption["fontInfo"] = 34] = "fontInfo";
EditorOption[EditorOption["fontLigatures"] = 35] = "fontLigatures";
EditorOption[EditorOption["fontSize"] = 36] = "fontSize";
EditorOption[EditorOption["fontWeight"] = 37] = "fontWeight";
EditorOption[EditorOption["formatOnPaste"] = 38] = "formatOnPaste";
EditorOption[EditorOption["formatOnType"] = 39] = "formatOnType";
EditorOption[EditorOption["glyphMargin"] = 40] = "glyphMargin";
EditorOption[EditorOption["gotoLocation"] = 41] = "gotoLocation";
EditorOption[EditorOption["hideCursorInOverviewRuler"] = 42] = "hideCursorInOverviewRuler";
EditorOption[EditorOption["highlightActiveIndentGuide"] = 43] = "highlightActiveIndentGuide";
EditorOption[EditorOption["hover"] = 44] = "hover";
EditorOption[EditorOption["inDiffEditor"] = 45] = "inDiffEditor";
EditorOption[EditorOption["letterSpacing"] = 46] = "letterSpacing";
EditorOption[EditorOption["lightbulb"] = 47] = "lightbulb";
EditorOption[EditorOption["lineDecorationsWidth"] = 48] = "lineDecorationsWidth";
EditorOption[EditorOption["lineHeight"] = 49] = "lineHeight";
EditorOption[EditorOption["lineNumbers"] = 50] = "lineNumbers";
EditorOption[EditorOption["lineNumbersMinChars"] = 51] = "lineNumbersMinChars";
EditorOption[EditorOption["links"] = 52] = "links";
EditorOption[EditorOption["matchBrackets"] = 53] = "matchBrackets";
EditorOption[EditorOption["minimap"] = 54] = "minimap";
EditorOption[EditorOption["mouseStyle"] = 55] = "mouseStyle";
EditorOption[EditorOption["mouseWheelScrollSensitivity"] = 56] = "mouseWheelScrollSensitivity";
EditorOption[EditorOption["mouseWheelZoom"] = 57] = "mouseWheelZoom";
EditorOption[EditorOption["multiCursorMergeOverlapping"] = 58] = "multiCursorMergeOverlapping";
EditorOption[EditorOption["multiCursorModifier"] = 59] = "multiCursorModifier";
EditorOption[EditorOption["multiCursorPaste"] = 60] = "multiCursorPaste";
EditorOption[EditorOption["occurrencesHighlight"] = 61] = "occurrencesHighlight";
EditorOption[EditorOption["overviewRulerBorder"] = 62] = "overviewRulerBorder";
EditorOption[EditorOption["overviewRulerLanes"] = 63] = "overviewRulerLanes";
EditorOption[EditorOption["parameterHints"] = 64] = "parameterHints";
EditorOption[EditorOption["peekWidgetDefaultFocus"] = 65] = "peekWidgetDefaultFocus";
EditorOption[EditorOption["quickSuggestions"] = 66] = "quickSuggestions";
EditorOption[EditorOption["quickSuggestionsDelay"] = 67] = "quickSuggestionsDelay";
EditorOption[EditorOption["readOnly"] = 68] = "readOnly";
EditorOption[EditorOption["renderControlCharacters"] = 69] = "renderControlCharacters";
EditorOption[EditorOption["renderIndentGuides"] = 70] = "renderIndentGuides";
EditorOption[EditorOption["renderFinalNewline"] = 71] = "renderFinalNewline";
EditorOption[EditorOption["renderLineHighlight"] = 72] = "renderLineHighlight";
EditorOption[EditorOption["renderValidationDecorations"] = 73] = "renderValidationDecorations";
EditorOption[EditorOption["renderWhitespace"] = 74] = "renderWhitespace";
EditorOption[EditorOption["revealHorizontalRightPadding"] = 75] = "revealHorizontalRightPadding";
EditorOption[EditorOption["roundedSelection"] = 76] = "roundedSelection";
EditorOption[EditorOption["rulers"] = 77] = "rulers";
EditorOption[EditorOption["scrollbar"] = 78] = "scrollbar";
EditorOption[EditorOption["scrollBeyondLastColumn"] = 79] = "scrollBeyondLastColumn";
EditorOption[EditorOption["scrollBeyondLastLine"] = 80] = "scrollBeyondLastLine";
EditorOption[EditorOption["selectionClipboard"] = 81] = "selectionClipboard";
EditorOption[EditorOption["selectionHighlight"] = 82] = "selectionHighlight";
EditorOption[EditorOption["selectOnLineNumbers"] = 83] = "selectOnLineNumbers";
EditorOption[EditorOption["showFoldingControls"] = 84] = "showFoldingControls";
EditorOption[EditorOption["showUnused"] = 85] = "showUnused";
EditorOption[EditorOption["snippetSuggestions"] = 86] = "snippetSuggestions";
EditorOption[EditorOption["smoothScrolling"] = 87] = "smoothScrolling";
EditorOption[EditorOption["stopRenderingLineAfter"] = 88] = "stopRenderingLineAfter";
EditorOption[EditorOption["suggest"] = 89] = "suggest";
EditorOption[EditorOption["suggestFontSize"] = 90] = "suggestFontSize";
EditorOption[EditorOption["suggestLineHeight"] = 91] = "suggestLineHeight";
EditorOption[EditorOption["suggestOnTriggerCharacters"] = 92] = "suggestOnTriggerCharacters";
EditorOption[EditorOption["suggestSelection"] = 93] = "suggestSelection";
EditorOption[EditorOption["tabCompletion"] = 94] = "tabCompletion";
EditorOption[EditorOption["useTabStops"] = 95] = "useTabStops";
EditorOption[EditorOption["wordSeparators"] = 96] = "wordSeparators";
EditorOption[EditorOption["wordWrap"] = 97] = "wordWrap";
EditorOption[EditorOption["wordWrapBreakAfterCharacters"] = 98] = "wordWrapBreakAfterCharacters";
EditorOption[EditorOption["wordWrapBreakBeforeCharacters"] = 99] = "wordWrapBreakBeforeCharacters";
EditorOption[EditorOption["wordWrapColumn"] = 100] = "wordWrapColumn";
EditorOption[EditorOption["wordWrapMinified"] = 101] = "wordWrapMinified";
EditorOption[EditorOption["wrappingIndent"] = 102] = "wrappingIndent";
EditorOption[EditorOption["wrappingStrategy"] = 103] = "wrappingStrategy";
EditorOption[EditorOption["editorClassName"] = 104] = "editorClassName";
EditorOption[EditorOption["pixelRatio"] = 105] = "pixelRatio";
EditorOption[EditorOption["tabFocusMode"] = 106] = "tabFocusMode";
EditorOption[EditorOption["layoutInfo"] = 107] = "layoutInfo";
EditorOption[EditorOption["wrappingInfo"] = 108] = "wrappingInfo";
})(EditorOption = exports.EditorOption || (exports.EditorOption = {}));
/**
* End of line character preference.
*/
var EndOfLinePreference;
(function (EndOfLinePreference) {
/**
* Use the end of line character identified in the text buffer.
*/
EndOfLinePreference[EndOfLinePreference["TextDefined"] = 0] = "TextDefined";
/**
* Use line feed (\n) as the end of line character.
*/
EndOfLinePreference[EndOfLinePreference["LF"] = 1] = "LF";
/**
* Use carriage return and line feed (\r\n) as the end of line character.
*/
EndOfLinePreference[EndOfLinePreference["CRLF"] = 2] = "CRLF";
})(EndOfLinePreference = exports.EndOfLinePreference || (exports.EndOfLinePreference = {}));
/**
* End of line character preference.
*/
var EndOfLineSequence;
(function (EndOfLineSequence) {
/**
* Use line feed (\n) as the end of line character.
*/
EndOfLineSequence[EndOfLineSequence["LF"] = 0] = "LF";
/**
* Use carriage return and line feed (\r\n) as the end of line character.
*/
EndOfLineSequence[EndOfLineSequence["CRLF"] = 1] = "CRLF";
})(EndOfLineSequence = exports.EndOfLineSequence || (exports.EndOfLineSequence = {}));
/**
* Describes what to do with the indentation when pressing Enter.
*/
var IndentAction;
(function (IndentAction) {
/**
* Insert new line and copy the previous line's indentation.
*/
IndentAction[IndentAction["None"] = 0] = "None";
/**
* Insert new line and indent once (relative to the previous line's indentation).
*/
IndentAction[IndentAction["Indent"] = 1] = "Indent";
/**
* Insert two new lines:
* - the first one indented which will hold the cursor
* - the second one at the same indentation level
*/
IndentAction[IndentAction["IndentOutdent"] = 2] = "IndentOutdent";
/**
* Insert new line and outdent once (relative to the previous line's indentation).
*/
IndentAction[IndentAction["Outdent"] = 3] = "Outdent";
})(IndentAction = exports.IndentAction || (exports.IndentAction = {}));
/**
* Virtual Key Codes, the value does not hold any inherent meaning.
* Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
* But these are "more general", as they should work across browsers & OS`s.
*/
var KeyCode;
(function (KeyCode) {
/**
* Placed first to cover the 0 value of the enum.
*/
KeyCode[KeyCode["Unknown"] = 0] = "Unknown";
KeyCode[KeyCode["Backspace"] = 1] = "Backspace";
KeyCode[KeyCode["Tab"] = 2] = "Tab";
KeyCode[KeyCode["Enter"] = 3] = "Enter";
KeyCode[KeyCode["Shift"] = 4] = "Shift";
KeyCode[KeyCode["Ctrl"] = 5] = "Ctrl";
KeyCode[KeyCode["Alt"] = 6] = "Alt";
KeyCode[KeyCode["PauseBreak"] = 7] = "PauseBreak";
KeyCode[KeyCode["CapsLock"] = 8] = "CapsLock";
KeyCode[KeyCode["Escape"] = 9] = "Escape";
KeyCode[KeyCode["Space"] = 10] = "Space";
KeyCode[KeyCode["PageUp"] = 11] = "PageUp";
KeyCode[KeyCode["PageDown"] = 12] = "PageDown";
KeyCode[KeyCode["End"] = 13] = "End";
KeyCode[KeyCode["Home"] = 14] = "Home";
KeyCode[KeyCode["LeftArrow"] = 15] = "LeftArrow";
KeyCode[KeyCode["UpArrow"] = 16] = "UpArrow";
KeyCode[KeyCode["RightArrow"] = 17] = "RightArrow";
KeyCode[KeyCode["DownArrow"] = 18] = "DownArrow";
KeyCode[KeyCode["Insert"] = 19] = "Insert";
KeyCode[KeyCode["Delete"] = 20] = "Delete";
KeyCode[KeyCode["KEY_0"] = 21] = "KEY_0";
KeyCode[KeyCode["KEY_1"] = 22] = "KEY_1";
KeyCode[KeyCode["KEY_2"] = 23] = "KEY_2";
KeyCode[KeyCode["KEY_3"] = 24] = "KEY_3";
KeyCode[KeyCode["KEY_4"] = 25] = "KEY_4";
KeyCode[KeyCode["KEY_5"] = 26] = "KEY_5";
KeyCode[KeyCode["KEY_6"] = 27] = "KEY_6";
KeyCode[KeyCode["KEY_7"] = 28] = "KEY_7";
KeyCode[KeyCode["KEY_8"] = 29] = "KEY_8";
KeyCode[KeyCode["KEY_9"] = 30] = "KEY_9";
KeyCode[KeyCode["KEY_A"] = 31] = "KEY_A";
KeyCode[KeyCode["KEY_B"] = 32] = "KEY_B";
KeyCode[KeyCode["KEY_C"] = 33] = "KEY_C";
KeyCode[KeyCode["KEY_D"] = 34] = "KEY_D";
KeyCode[KeyCode["KEY_E"] = 35] = "KEY_E";
KeyCode[KeyCode["KEY_F"] = 36] = "KEY_F";
KeyCode[KeyCode["KEY_G"] = 37] = "KEY_G";
KeyCode[KeyCode["KEY_H"] = 38] = "KEY_H";
KeyCode[KeyCode["KEY_I"] = 39] = "KEY_I";
KeyCode[KeyCode["KEY_J"] = 40] = "KEY_J";
KeyCode[KeyCode["KEY_K"] = 41] = "KEY_K";
KeyCode[KeyCode["KEY_L"] = 42] = "KEY_L";
KeyCode[KeyCode["KEY_M"] = 43] = "KEY_M";
KeyCode[KeyCode["KEY_N"] = 44] = "KEY_N";
KeyCode[KeyCode["KEY_O"] = 45] = "KEY_O";
KeyCode[KeyCode["KEY_P"] = 46] = "KEY_P";
KeyCode[KeyCode["KEY_Q"] = 47] = "KEY_Q";
KeyCode[KeyCode["KEY_R"] = 48] = "KEY_R";
KeyCode[KeyCode["KEY_S"] = 49] = "KEY_S";
KeyCode[KeyCode["KEY_T"] = 50] = "KEY_T";
KeyCode[KeyCode["KEY_U"] = 51] = "KEY_U";
KeyCode[KeyCode["KEY_V"] = 52] = "KEY_V";
KeyCode[KeyCode["KEY_W"] = 53] = "KEY_W";
KeyCode[KeyCode["KEY_X"] = 54] = "KEY_X";
KeyCode[KeyCode["KEY_Y"] = 55] = "KEY_Y";
KeyCode[KeyCode["KEY_Z"] = 56] = "KEY_Z";
KeyCode[KeyCode["Meta"] = 57] = "Meta";
KeyCode[KeyCode["ContextMenu"] = 58] = "ContextMenu";
KeyCode[KeyCode["F1"] = 59] = "F1";
KeyCode[KeyCode["F2"] = 60] = "F2";
KeyCode[KeyCode["F3"] = 61] = "F3";
KeyCode[KeyCode["F4"] = 62] = "F4";
KeyCode[KeyCode["F5"] = 63] = "F5";
KeyCode[KeyCode["F6"] = 64] = "F6";
KeyCode[KeyCode["F7"] = 65] = "F7";
KeyCode[KeyCode["F8"] = 66] = "F8";
KeyCode[KeyCode["F9"] = 67] = "F9";
KeyCode[KeyCode["F10"] = 68] = "F10";
KeyCode[KeyCode["F11"] = 69] = "F11";
KeyCode[KeyCode["F12"] = 70] = "F12";
KeyCode[KeyCode["F13"] = 71] = "F13";
KeyCode[KeyCode["F14"] = 72] = "F14";
KeyCode[KeyCode["F15"] = 73] = "F15";
KeyCode[KeyCode["F16"] = 74] = "F16";
KeyCode[KeyCode["F17"] = 75] = "F17";
KeyCode[KeyCode["F18"] = 76] = "F18";
KeyCode[KeyCode["F19"] = 77] = "F19";
KeyCode[KeyCode["NumLock"] = 78] = "NumLock";
KeyCode[KeyCode["ScrollLock"] = 79] = "ScrollLock";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ';:' key
*/
KeyCode[KeyCode["US_SEMICOLON"] = 80] = "US_SEMICOLON";
/**
* For any country/region, the '+' key
* For the US standard keyboard, the '=+' key
*/
KeyCode[KeyCode["US_EQUAL"] = 81] = "US_EQUAL";
/**
* For any country/region, the ',' key
* For the US standard keyboard, the ',<' key
*/
KeyCode[KeyCode["US_COMMA"] = 82] = "US_COMMA";
/**
* For any country/region, the '-' key
* For the US standard keyboard, the '-_' key
*/
KeyCode[KeyCode["US_MINUS"] = 83] = "US_MINUS";
/**
* For any country/region, the '.' key
* For the US standard keyboard, the '.>' key
*/
KeyCode[KeyCode["US_DOT"] = 84] = "US_DOT";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '/?' key
*/
KeyCode[KeyCode["US_SLASH"] = 85] = "US_SLASH";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '`~' key
*/
KeyCode[KeyCode["US_BACKTICK"] = 86] = "US_BACKTICK";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '[{' key
*/
KeyCode[KeyCode["US_OPEN_SQUARE_BRACKET"] = 87] = "US_OPEN_SQUARE_BRACKET";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '\|' key
*/
KeyCode[KeyCode["US_BACKSLASH"] = 88] = "US_BACKSLASH";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ']}' key
*/
KeyCode[KeyCode["US_CLOSE_SQUARE_BRACKET"] = 89] = "US_CLOSE_SQUARE_BRACKET";
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ''"' key
*/
KeyCode[KeyCode["US_QUOTE"] = 90] = "US_QUOTE";
/**
* Used for miscellaneous characters; it can vary by keyboard.
*/
KeyCode[KeyCode["OEM_8"] = 91] = "OEM_8";
/**
* Either the angle bracket key or the backslash key on the RT 102-key keyboard.
*/
KeyCode[KeyCode["OEM_102"] = 92] = "OEM_102";
KeyCode[KeyCode["NUMPAD_0"] = 93] = "NUMPAD_0";
KeyCode[KeyCode["NUMPAD_1"] = 94] = "NUMPAD_1";
KeyCode[KeyCode["NUMPAD_2"] = 95] = "NUMPAD_2";
KeyCode[KeyCode["NUMPAD_3"] = 96] = "NUMPAD_3";
KeyCode[KeyCode["NUMPAD_4"] = 97] = "NUMPAD_4";
KeyCode[KeyCode["NUMPAD_5"] = 98] = "NUMPAD_5";
KeyCode[KeyCode["NUMPAD_6"] = 99] = "NUMPAD_6";
KeyCode[KeyCode["NUMPAD_7"] = 100] = "NUMPAD_7";
KeyCode[KeyCode["NUMPAD_8"] = 101] = "NUMPAD_8";
KeyCode[KeyCode["NUMPAD_9"] = 102] = "NUMPAD_9";
KeyCode[KeyCode["NUMPAD_MULTIPLY"] = 103] = "NUMPAD_MULTIPLY";
KeyCode[KeyCode["NUMPAD_ADD"] = 104] = "NUMPAD_ADD";
KeyCode[KeyCode["NUMPAD_SEPARATOR"] = 105] = "NUMPAD_SEPARATOR";
KeyCode[KeyCode["NUMPAD_SUBTRACT"] = 106] = "NUMPAD_SUBTRACT";
KeyCode[KeyCode["NUMPAD_DECIMAL"] = 107] = "NUMPAD_DECIMAL";
KeyCode[KeyCode["NUMPAD_DIVIDE"] = 108] = "NUMPAD_DIVIDE";
/**
* Cover all key codes when IME is processing input.
*/
KeyCode[KeyCode["KEY_IN_COMPOSITION"] = 109] = "KEY_IN_COMPOSITION";
KeyCode[KeyCode["ABNT_C1"] = 110] = "ABNT_C1";
KeyCode[KeyCode["ABNT_C2"] = 111] = "ABNT_C2";
/**
* Placed last to cover the length of the enum.
* Please do not depend on this value!
*/
KeyCode[KeyCode["MAX_VALUE"] = 112] = "MAX_VALUE";
})(KeyCode = exports.KeyCode || (exports.KeyCode = {}));
var MarkerSeverity;
(function (MarkerSeverity) {
MarkerSeverity[MarkerSeverity["Hint"] = 1] = "Hint";
MarkerSeverity[MarkerSeverity["Info"] = 2] = "Info";
MarkerSeverity[MarkerSeverity["Warning"] = 4] = "Warning";
MarkerSeverity[MarkerSeverity["Error"] = 8] = "Error";
})(MarkerSeverity = exports.MarkerSeverity || (exports.MarkerSeverity = {}));
var MarkerTag;
(function (MarkerTag) {
MarkerTag[MarkerTag["Unnecessary"] = 1] = "Unnecessary";
MarkerTag[MarkerTag["Deprecated"] = 2] = "Deprecated";
})(MarkerTag = exports.MarkerTag || (exports.MarkerTag = {}));
/**
* Position in the minimap to render the decoration.
*/
var MinimapPosition;
(function (MinimapPosition) {
MinimapPosition[MinimapPosition["Inline"] = 1] = "Inline";
MinimapPosition[MinimapPosition["Gutter"] = 2] = "Gutter";
})(MinimapPosition = exports.MinimapPosition || (exports.MinimapPosition = {}));
/**
* Type of hit element with the mouse in the editor.
*/
var MouseTargetType;
(function (MouseTargetType) {
/**
* Mouse is on top of an unknown element.
*/
MouseTargetType[MouseTargetType["UNKNOWN"] = 0] = "UNKNOWN";
/**
* Mouse is on top of the textarea used for input.
*/
MouseTargetType[MouseTargetType["TEXTAREA"] = 1] = "TEXTAREA";
/**
* Mouse is on top of the glyph margin
*/
MouseTargetType[MouseTargetType["GUTTER_GLYPH_MARGIN"] = 2] = "GUTTER_GLYPH_MARGIN";
/**
* Mouse is on top of the line numbers
*/
MouseTargetType[MouseTargetType["GUTTER_LINE_NUMBERS"] = 3] = "GUTTER_LINE_NUMBERS";
/**
* Mouse is on top of the line decorations
*/
MouseTargetType[MouseTargetType["GUTTER_LINE_DECORATIONS"] = 4] = "GUTTER_LINE_DECORATIONS";
/**
* Mouse is on top of the whitespace left in the gutter by a view zone.
*/
MouseTargetType[MouseTargetType["GUTTER_VIEW_ZONE"] = 5] = "GUTTER_VIEW_ZONE";
/**
* Mouse is on top of text in the content.
*/
MouseTargetType[MouseTargetType["CONTENT_TEXT"] = 6] = "CONTENT_TEXT";
/**
* Mouse is on top of empty space in the content (e.g. after line text or below last line)
*/
MouseTargetType[MouseTargetType["CONTENT_EMPTY"] = 7] = "CONTENT_EMPTY";
/**
* Mouse is on top of a view zone in the content.
*/
MouseTargetType[MouseTargetType["CONTENT_VIEW_ZONE"] = 8] = "CONTENT_VIEW_ZONE";
/**
* Mouse is on top of a content widget.
*/
MouseTargetType[MouseTargetType["CONTENT_WIDGET"] = 9] = "CONTENT_WIDGET";
/**
* Mouse is on top of the decorations overview ruler.
*/
MouseTargetType[MouseTargetType["OVERVIEW_RULER"] = 10] = "OVERVIEW_RULER";
/**
* Mouse is on top of a scrollbar.
*/
MouseTargetType[MouseTargetType["SCROLLBAR"] = 11] = "SCROLLBAR";
/**
* Mouse is on top of an overlay widget.
*/
MouseTargetType[MouseTargetType["OVERLAY_WIDGET"] = 12] = "OVERLAY_WIDGET";
/**
* Mouse is outside of the editor.
*/
MouseTargetType[MouseTargetType["OUTSIDE_EDITOR"] = 13] = "OUTSIDE_EDITOR";
})(MouseTargetType = exports.MouseTargetType || (exports.MouseTargetType = {}));
/**
* A positioning preference for rendering overlay widgets.
*/
var OverlayWidgetPositionPreference;
(function (OverlayWidgetPositionPreference) {
/**
* Position the overlay widget in the top right corner
*/
OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["TOP_RIGHT_CORNER"] = 0] = "TOP_RIGHT_CORNER";
/**
* Position the overlay widget in the bottom right corner
*/
OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["BOTTOM_RIGHT_CORNER"] = 1] = "BOTTOM_RIGHT_CORNER";
/**
* Position the overlay widget in the top center
*/
OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["TOP_CENTER"] = 2] = "TOP_CENTER";
})(OverlayWidgetPositionPreference = exports.OverlayWidgetPositionPreference || (exports.OverlayWidgetPositionPreference = {}));
/**
* Vertical Lane in the overview ruler of the editor.
*/
var OverviewRulerLane;
(function (OverviewRulerLane) {
OverviewRulerLane[OverviewRulerLane["Left"] = 1] = "Left";
OverviewRulerLane[OverviewRulerLane["Center"] = 2] = "Center";
OverviewRulerLane[OverviewRulerLane["Right"] = 4] = "Right";
OverviewRulerLane[OverviewRulerLane["Full"] = 7] = "Full";
})(OverviewRulerLane = exports.OverviewRulerLane || (exports.OverviewRulerLane = {}));
var RenderLineNumbersType;
(function (RenderLineNumbersType) {
RenderLineNumbersType[RenderLineNumbersType["Off"] = 0] = "Off";
RenderLineNumbersType[RenderLineNumbersType["On"] = 1] = "On";
RenderLineNumbersType[RenderLineNumbersType["Relative"] = 2] = "Relative";
RenderLineNumbersType[RenderLineNumbersType["Interval"] = 3] = "Interval";
RenderLineNumbersType[RenderLineNumbersType["Custom"] = 4] = "Custom";
})(RenderLineNumbersType = exports.RenderLineNumbersType || (exports.RenderLineNumbersType = {}));
var RenderMinimap;
(function (RenderMinimap) {
RenderMinimap[RenderMinimap["None"] = 0] = "None";
RenderMinimap[RenderMinimap["Text"] = 1] = "Text";
RenderMinimap[RenderMinimap["Blocks"] = 2] = "Blocks";
})(RenderMinimap = exports.RenderMinimap || (exports.RenderMinimap = {}));
var ScrollType;
(function (ScrollType) {
ScrollType[ScrollType["Smooth"] = 0] = "Smooth";
ScrollType[ScrollType["Immediate"] = 1] = "Immediate";
})(ScrollType = exports.ScrollType || (exports.ScrollType = {}));
var ScrollbarVisibility;
(function (ScrollbarVisibility) {
ScrollbarVisibility[ScrollbarVisibility["Auto"] = 1] = "Auto";
ScrollbarVisibility[ScrollbarVisibility["Hidden"] = 2] = "Hidden";
ScrollbarVisibility[ScrollbarVisibility["Visible"] = 3] = "Visible";
})(ScrollbarVisibility = exports.ScrollbarVisibility || (exports.ScrollbarVisibility = {}));
/**
* The direction of a selection.
*/
var SelectionDirection;
(function (SelectionDirection) {
/**
* The selection starts above where it ends.
*/
SelectionDirection[SelectionDirection["LTR"] = 0] = "LTR";
/**
* The selection starts below where it ends.
*/
SelectionDirection[SelectionDirection["RTL"] = 1] = "RTL";
})(SelectionDirection = exports.SelectionDirection || (exports.SelectionDirection = {}));
var SignatureHelpTriggerKind;
(function (SignatureHelpTriggerKind) {
SignatureHelpTriggerKind[SignatureHelpTriggerKind["Invoke"] = 1] = "Invoke";
SignatureHelpTriggerKind[SignatureHelpTriggerKind["TriggerCharacter"] = 2] = "TriggerCharacter";
SignatureHelpTriggerKind[SignatureHelpTriggerKind["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
/**
* A symbol kind.
*/
var SymbolKind;
(function (SymbolKind) {
SymbolKind[SymbolKind["File"] = 0] = "File";
SymbolKind[SymbolKind["Module"] = 1] = "Module";
SymbolKind[SymbolKind["Namespace"] = 2] = "Namespace";
SymbolKind[SymbolKind["Package"] = 3] = "Package";
SymbolKind[SymbolKind["Class"] = 4] = "Class";
SymbolKind[SymbolKind["Method"] = 5] = "Method";
SymbolKind[SymbolKind["Property"] = 6] = "Property";
SymbolKind[SymbolKind["Field"] = 7] = "Field";
SymbolKind[SymbolKind["Constructor"] = 8] = "Constructor";
SymbolKind[SymbolKind["Enum"] = 9] = "Enum";
SymbolKind[SymbolKind["Interface"] = 10] = "Interface";
SymbolKind[SymbolKind["Function"] = 11] = "Function";
SymbolKind[SymbolKind["Variable"] = 12] = "Variable";
SymbolKind[SymbolKind["Constant"] = 13] = "Constant";
SymbolKind[SymbolKind["String"] = 14] = "String";
SymbolKind[SymbolKind["Number"] = 15] = "Number";
SymbolKind[SymbolKind["Boolean"] = 16] = "Boolean";
SymbolKind[SymbolKind["Array"] = 17] = "Array";
SymbolKind[SymbolKind["Object"] = 18] = "Object";
SymbolKind[SymbolKind["Key"] = 19] = "Key";
SymbolKind[SymbolKind["Null"] = 20] = "Null";
SymbolKind[SymbolKind["EnumMember"] = 21] = "EnumMember";
SymbolKind[SymbolKind["Struct"] = 22] = "Struct";
SymbolKind[SymbolKind["Event"] = 23] = "Event";
SymbolKind[SymbolKind["Operator"] = 24] = "Operator";
SymbolKind[SymbolKind["TypeParameter"] = 25] = "TypeParameter";
})(SymbolKind = exports.SymbolKind || (exports.SymbolKind = {}));
var SymbolTag;
(function (SymbolTag) {
SymbolTag[SymbolTag["Deprecated"] = 1] = "Deprecated";
})(SymbolTag = exports.SymbolTag || (exports.SymbolTag = {}));
/**
* The kind of animation in which the editor's cursor should be rendered.
*/
var TextEditorCursorBlinkingStyle;
(function (TextEditorCursorBlinkingStyle) {
/**
* Hidden
*/
TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Hidden"] = 0] = "Hidden";
/**
* Blinking
*/
TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Blink"] = 1] = "Blink";
/**
* Blinking with smooth fading
*/
TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Smooth"] = 2] = "Smooth";
/**
* Blinking with prolonged filled state and smooth fading
*/
TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Phase"] = 3] = "Phase";
/**
* Expand collapse animation on the y axis
*/
TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Expand"] = 4] = "Expand";
/**
* No-Blinking
*/
TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Solid"] = 5] = "Solid";
})(TextEditorCursorBlinkingStyle = exports.TextEditorCursorBlinkingStyle || (exports.TextEditorCursorBlinkingStyle = {}));
/**
* The style in which the editor's cursor should be rendered.
*/
var TextEditorCursorStyle;
(function (TextEditorCursorStyle) {
/**
* As a vertical line (sitting between two characters).
*/
TextEditorCursorStyle[TextEditorCursorStyle["Line"] = 1] = "Line";
/**
* As a block (sitting on top of a character).
*/
TextEditorCursorStyle[TextEditorCursorStyle["Block"] = 2] = "Block";
/**
* As a horizontal line (sitting under a character).
*/
TextEditorCursorStyle[TextEditorCursorStyle["Underline"] = 3] = "Underline";
/**
* As a thin vertical line (sitting between two characters).
*/
TextEditorCursorStyle[TextEditorCursorStyle["LineThin"] = 4] = "LineThin";
/**
* As an outlined block (sitting on top of a character).
*/
TextEditorCursorStyle[TextEditorCursorStyle["BlockOutline"] = 5] = "BlockOutline";
/**
* As a thin horizontal line (sitting under a character).
*/
TextEditorCursorStyle[TextEditorCursorStyle["UnderlineThin"] = 6] = "UnderlineThin";
})(TextEditorCursorStyle = exports.TextEditorCursorStyle || (exports.TextEditorCursorStyle = {}));
/**
* Describes the behavior of decorations when typing/editing near their edges.
* Note: Please do not edit the values, as they very carefully match `DecorationRangeBehavior`
*/
var TrackedRangeStickiness;
(function (TrackedRangeStickiness) {
TrackedRangeStickiness[TrackedRangeStickiness["AlwaysGrowsWhenTypingAtEdges"] = 0] = "AlwaysGrowsWhenTypingAtEdges";
TrackedRangeStickiness[TrackedRangeStickiness["NeverGrowsWhenTypingAtEdges"] = 1] = "NeverGrowsWhenTypingAtEdges";
TrackedRangeStickiness[TrackedRangeStickiness["GrowsOnlyWhenTypingBefore"] = 2] = "GrowsOnlyWhenTypingBefore";
TrackedRangeStickiness[TrackedRangeStickiness["GrowsOnlyWhenTypingAfter"] = 3] = "GrowsOnlyWhenTypingAfter";
})(TrackedRangeStickiness = exports.TrackedRangeStickiness || (exports.TrackedRangeStickiness = {}));
/**
* Describes how to indent wrapped lines.
*/
var WrappingIndent;
(function (WrappingIndent) {
/**
* No indentation => wrapped lines begin at column 1.
*/
WrappingIndent[WrappingIndent["None"] = 0] = "None";
/**
* Same => wrapped lines get the same indentation as the parent.
*/
WrappingIndent[WrappingIndent["Same"] = 1] = "Same";
/**
* Indent => wrapped lines get +1 indentation toward the parent.
*/
WrappingIndent[WrappingIndent["Indent"] = 2] = "Indent";
/**
* DeepIndent => wrapped lines get +2 indentation toward the parent.
*/
WrappingIndent[WrappingIndent["DeepIndent"] = 3] = "DeepIndent";
})(WrappingIndent = exports.WrappingIndent || (exports.WrappingIndent = {}));
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[192/*vs/editor/common/standalone/standaloneBase*/], __M([0/*require*/,1/*exports*/,26/*vs/base/common/cancellation*/,4/*vs/base/common/event*/,36/*vs/base/common/keyCodes*/,25/*vs/base/common/uri*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,107/*vs/editor/common/core/token*/,147/*vs/editor/common/standalone/standaloneEnums*/,614/*vs/editor/common/standalone/promise-polyfill/polyfill*/]), function (require, exports, cancellation_1, event_1, keyCodes_1, uri_1, position_1, range_1, selection_1, token_1, standaloneEnums) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var KeyMod = /** @class */ (function () {
function KeyMod() {
}
KeyMod.chord = function (firstPart, secondPart) {
return keyCodes_1.KeyChord(firstPart, secondPart);
};
KeyMod.CtrlCmd = 2048 /* CtrlCmd */;
KeyMod.Shift = 1024 /* Shift */;
KeyMod.Alt = 512 /* Alt */;
KeyMod.WinCtrl = 256 /* WinCtrl */;
return KeyMod;
}());
exports.KeyMod = KeyMod;
function createMonacoBaseAPI() {
return {
editor: undefined,
languages: undefined,
CancellationTokenSource: cancellation_1.CancellationTokenSource,
Emitter: event_1.Emitter,
KeyCode: standaloneEnums.KeyCode,
KeyMod: KeyMod,
Position: position_1.Position,
Range: range_1.Range,
Selection: selection_1.Selection,
SelectionDirection: standaloneEnums.SelectionDirection,
MarkerSeverity: standaloneEnums.MarkerSeverity,
MarkerTag: standaloneEnums.MarkerTag,
Uri: uri_1.URI,
Token: token_1.Token
};
}
exports.createMonacoBaseAPI = createMonacoBaseAPI;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[193/*vs/editor/common/view/overviewZoneManager*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ColorZone = /** @class */ (function () {
function ColorZone(from, to, colorId) {
this.from = from | 0;
this.to = to | 0;
this.colorId = colorId | 0;
}
ColorZone.compare = function (a, b) {
if (a.colorId === b.colorId) {
if (a.from === b.from) {
return a.to - b.to;
}
return a.from - b.from;
}
return a.colorId - b.colorId;
};
return ColorZone;
}());
exports.ColorZone = ColorZone;
/**
* A zone in the overview ruler
*/
var OverviewRulerZone = /** @class */ (function () {
function OverviewRulerZone(startLineNumber, endLineNumber, color) {
this.startLineNumber = startLineNumber;
this.endLineNumber = endLineNumber;
this.color = color;
this._colorZone = null;
}
OverviewRulerZone.compare = function (a, b) {
if (a.color === b.color) {
if (a.startLineNumber === b.startLineNumber) {
return a.endLineNumber - b.endLineNumber;
}
return a.startLineNumber - b.startLineNumber;
}
return a.color < b.color ? -1 : 1;
};
OverviewRulerZone.prototype.setColorZone = function (colorZone) {
this._colorZone = colorZone;
};
OverviewRulerZone.prototype.getColorZones = function () {
return this._colorZone;
};
return OverviewRulerZone;
}());
exports.OverviewRulerZone = OverviewRulerZone;
var OverviewZoneManager = /** @class */ (function () {
function OverviewZoneManager(getVerticalOffsetForLine) {
this._getVerticalOffsetForLine = getVerticalOffsetForLine;
this._zones = [];
this._colorZonesInvalid = false;
this._lineHeight = 0;
this._domWidth = 0;
this._domHeight = 0;
this._outerHeight = 0;
this._pixelRatio = 1;
this._lastAssignedId = 0;
this._color2Id = Object.create(null);
this._id2Color = [];
}
OverviewZoneManager.prototype.getId2Color = function () {
return this._id2Color;
};
OverviewZoneManager.prototype.setZones = function (newZones) {
this._zones = newZones;
this._zones.sort(OverviewRulerZone.compare);
};
OverviewZoneManager.prototype.setLineHeight = function (lineHeight) {
if (this._lineHeight === lineHeight) {
return false;
}
this._lineHeight = lineHeight;
this._colorZonesInvalid = true;
return true;
};
OverviewZoneManager.prototype.setPixelRatio = function (pixelRatio) {
this._pixelRatio = pixelRatio;
this._colorZonesInvalid = true;
};
OverviewZoneManager.prototype.getDOMWidth = function () {
return this._domWidth;
};
OverviewZoneManager.prototype.getCanvasWidth = function () {
return this._domWidth * this._pixelRatio;
};
OverviewZoneManager.prototype.setDOMWidth = function (width) {
if (this._domWidth === width) {
return false;
}
this._domWidth = width;
this._colorZonesInvalid = true;
return true;
};
OverviewZoneManager.prototype.getDOMHeight = function () {
return this._domHeight;
};
OverviewZoneManager.prototype.getCanvasHeight = function () {
return this._domHeight * this._pixelRatio;
};
OverviewZoneManager.prototype.setDOMHeight = function (height) {
if (this._domHeight === height) {
return false;
}
this._domHeight = height;
this._colorZonesInvalid = true;
return true;
};
OverviewZoneManager.prototype.getOuterHeight = function () {
return this._outerHeight;
};
OverviewZoneManager.prototype.setOuterHeight = function (outerHeight) {
if (this._outerHeight === outerHeight) {
return false;
}
this._outerHeight = outerHeight;
this._colorZonesInvalid = true;
return true;
};
OverviewZoneManager.prototype.resolveColorZones = function () {
var colorZonesInvalid = this._colorZonesInvalid;
var lineHeight = Math.floor(this._lineHeight); // @perf
var totalHeight = Math.floor(this.getCanvasHeight()); // @perf
var outerHeight = Math.floor(this._outerHeight); // @perf
var heightRatio = totalHeight / outerHeight;
var halfMinimumHeight = Math.floor(4 /* MINIMUM_HEIGHT */ * this._pixelRatio / 2);
var allColorZones = [];
for (var i = 0, len = this._zones.length; i < len; i++) {
var zone = this._zones[i];
if (!colorZonesInvalid) {
var colorZone_1 = zone.getColorZones();
if (colorZone_1) {
allColorZones.push(colorZone_1);
continue;
}
}
var y1 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.startLineNumber)));
var y2 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight));
var ycenter = Math.floor((y1 + y2) / 2);
var halfHeight = (y2 - ycenter);
if (halfHeight < halfMinimumHeight) {
halfHeight = halfMinimumHeight;
}
if (ycenter - halfHeight < 0) {
ycenter = halfHeight;
}
if (ycenter + halfHeight > totalHeight) {
ycenter = totalHeight - halfHeight;
}
var color = zone.color;
var colorId = this._color2Id[color];
if (!colorId) {
colorId = (++this._lastAssignedId);
this._color2Id[color] = colorId;
this._id2Color[colorId] = color;
}
var colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId);
zone.setColorZone(colorZone);
allColorZones.push(colorZone);
}
this._colorZonesInvalid = false;
allColorZones.sort(ColorZone.compare);
return allColorZones;
};
return OverviewZoneManager;
}());
exports.OverviewZoneManager = OverviewZoneManager;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[91/*vs/editor/common/view/renderingContext*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var RestrictedRenderingContext = /** @class */ (function () {
function RestrictedRenderingContext(viewLayout, viewportData) {
this._viewLayout = viewLayout;
this.viewportData = viewportData;
this.scrollWidth = this._viewLayout.getScrollWidth();
this.scrollHeight = this._viewLayout.getScrollHeight();
this.visibleRange = this.viewportData.visibleRange;
this.bigNumbersDelta = this.viewportData.bigNumbersDelta;
var vInfo = this._viewLayout.getCurrentViewport();
this.scrollTop = vInfo.top;
this.scrollLeft = vInfo.left;
this.viewportWidth = vInfo.width;
this.viewportHeight = vInfo.height;
}
RestrictedRenderingContext.prototype.getScrolledTopFromAbsoluteTop = function (absoluteTop) {
return absoluteTop - this.scrollTop;
};
RestrictedRenderingContext.prototype.getVerticalOffsetForLineNumber = function (lineNumber) {
return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber);
};
RestrictedRenderingContext.prototype.getDecorationsInViewport = function () {
return this.viewportData.getDecorationsInViewport();
};
return RestrictedRenderingContext;
}());
exports.RestrictedRenderingContext = RestrictedRenderingContext;
var RenderingContext = /** @class */ (function (_super) {
__extends(RenderingContext, _super);
function RenderingContext(viewLayout, viewportData, viewLines) {
var _this = _super.call(this, viewLayout, viewportData) || this;
_this._viewLines = viewLines;
return _this;
}
RenderingContext.prototype.linesVisibleRangesForRange = function (range, includeNewLines) {
return this._viewLines.linesVisibleRangesForRange(range, includeNewLines);
};
RenderingContext.prototype.visibleRangeForPosition = function (position) {
return this._viewLines.visibleRangeForPosition(position);
};
return RenderingContext;
}(RestrictedRenderingContext));
exports.RenderingContext = RenderingContext;
var LineVisibleRanges = /** @class */ (function () {
function LineVisibleRanges(outsideRenderedLine, lineNumber, ranges) {
this.outsideRenderedLine = outsideRenderedLine;
this.lineNumber = lineNumber;
this.ranges = ranges;
}
return LineVisibleRanges;
}());
exports.LineVisibleRanges = LineVisibleRanges;
var HorizontalRange = /** @class */ (function () {
function HorizontalRange(left, width) {
this.left = Math.round(left);
this.width = Math.round(width);
}
HorizontalRange.prototype.toString = function () {
return "[" + this.left + "," + this.width + "]";
};
return HorizontalRange;
}());
exports.HorizontalRange = HorizontalRange;
var HorizontalPosition = /** @class */ (function () {
function HorizontalPosition(outsideRenderedLine, left) {
this.outsideRenderedLine = outsideRenderedLine;
this.left = Math.round(left);
}
return HorizontalPosition;
}());
exports.HorizontalPosition = HorizontalPosition;
var VisibleRanges = /** @class */ (function () {
function VisibleRanges(outsideRenderedLine, ranges) {
this.outsideRenderedLine = outsideRenderedLine;
this.ranges = ranges;
}
return VisibleRanges;
}());
exports.VisibleRanges = VisibleRanges;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[359/*vs/editor/browser/viewParts/lines/rangeUtil*/], __M([0/*require*/,1/*exports*/,91/*vs/editor/common/view/renderingContext*/]), function (require, exports, renderingContext_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FloatHorizontalRange = /** @class */ (function () {
function FloatHorizontalRange(left, width) {
this.left = left;
this.width = width;
}
FloatHorizontalRange.prototype.toString = function () {
return "[" + this.left + "," + this.width + "]";
};
FloatHorizontalRange.compare = function (a, b) {
return a.left - b.left;
};
return FloatHorizontalRange;
}());
var RangeUtil = /** @class */ (function () {
function RangeUtil() {
}
RangeUtil._createRange = function () {
if (!this._handyReadyRange) {
this._handyReadyRange = document.createRange();
}
return this._handyReadyRange;
};
RangeUtil._detachRange = function (range, endNode) {
// Move range out of the span node, IE doesn't like having many ranges in
// the same spot and will act badly for lines containing dashes ('-')
range.selectNodeContents(endNode);
};
RangeUtil._readClientRects = function (startElement, startOffset, endElement, endOffset, endNode) {
var range = this._createRange();
try {
range.setStart(startElement, startOffset);
range.setEnd(endElement, endOffset);
return range.getClientRects();
}
catch (e) {
// This is life ...
return null;
}
finally {
this._detachRange(range, endNode);
}
};
RangeUtil._mergeAdjacentRanges = function (ranges) {
if (ranges.length === 1) {
// There is nothing to merge
return [new renderingContext_1.HorizontalRange(ranges[0].left, ranges[0].width)];
}
ranges.sort(FloatHorizontalRange.compare);
var result = [], resultLen = 0;
var prevLeft = ranges[0].left;
var prevWidth = ranges[0].width;
for (var i = 1, len = ranges.length; i < len; i++) {
var range = ranges[i];
var myLeft = range.left;
var myWidth = range.width;
if (prevLeft + prevWidth + 0.9 /* account for browser's rounding errors*/ >= myLeft) {
prevWidth = Math.max(prevWidth, myLeft + myWidth - prevLeft);
}
else {
result[resultLen++] = new renderingContext_1.HorizontalRange(prevLeft, prevWidth);
prevLeft = myLeft;
prevWidth = myWidth;
}
}
result[resultLen++] = new renderingContext_1.HorizontalRange(prevLeft, prevWidth);
return result;
};
RangeUtil._createHorizontalRangesFromClientRects = function (clientRects, clientRectDeltaLeft) {
if (!clientRects || clientRects.length === 0) {
return null;
}
// We go through FloatHorizontalRange because it has been observed in bi-di text
// that the clientRects are not coming in sorted from the browser
var result = [];
for (var i = 0, len = clientRects.length; i < len; i++) {
var clientRect = clientRects[i];
result[i] = new FloatHorizontalRange(Math.max(0, clientRect.left - clientRectDeltaLeft), clientRect.width);
}
return this._mergeAdjacentRanges(result);
};
RangeUtil.readHorizontalRanges = function (domNode, startChildIndex, startOffset, endChildIndex, endOffset, clientRectDeltaLeft, endNode) {
// Panic check
var min = 0;
var max = domNode.children.length - 1;
if (min > max) {
return null;
}
startChildIndex = Math.min(max, Math.max(min, startChildIndex));
endChildIndex = Math.min(max, Math.max(min, endChildIndex));
// If crossing over to a span only to select offset 0, then use the previous span's maximum offset
// Chrome is buggy and doesn't handle 0 offsets well sometimes.
if (startChildIndex !== endChildIndex) {
if (endChildIndex > 0 && endOffset === 0) {
endChildIndex--;
endOffset = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
}
}
var startElement = domNode.children[startChildIndex].firstChild;
var endElement = domNode.children[endChildIndex].firstChild;
if (!startElement || !endElement) {
// When having an empty (without any text content), try to move to the previous
if (!startElement && startOffset === 0 && startChildIndex > 0) {
startElement = domNode.children[startChildIndex - 1].firstChild;
startOffset = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
}
if (!endElement && endOffset === 0 && endChildIndex > 0) {
endElement = domNode.children[endChildIndex - 1].firstChild;
endOffset = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
}
}
if (!startElement || !endElement) {
return null;
}
startOffset = Math.min(startElement.textContent.length, Math.max(0, startOffset));
endOffset = Math.min(endElement.textContent.length, Math.max(0, endOffset));
var clientRects = this._readClientRects(startElement, startOffset, endElement, endOffset, endNode);
return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft);
};
return RangeUtil;
}());
exports.RangeUtil = RangeUtil;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[360/*vs/editor/common/view/viewContext*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ViewContext = /** @class */ (function () {
function ViewContext(configuration, theme, model, privateViewEventBus) {
this.configuration = configuration;
this.theme = theme;
this.model = model;
this.viewLayout = model.viewLayout;
this.privateViewEventBus = privateViewEventBus;
}
ViewContext.prototype.addEventHandler = function (eventHandler) {
this.privateViewEventBus.addEventHandler(eventHandler);
};
ViewContext.prototype.removeEventHandler = function (eventHandler) {
this.privateViewEventBus.removeEventHandler(eventHandler);
};
return ViewContext;
}());
exports.ViewContext = ViewContext;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[361/*vs/editor/common/view/viewEventDispatcher*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ViewEventDispatcher = /** @class */ (function () {
function ViewEventDispatcher(eventHandlerGateKeeper) {
this._eventHandlerGateKeeper = eventHandlerGateKeeper;
this._eventHandlers = [];
this._eventQueue = null;
this._isConsumingQueue = false;
}
ViewEventDispatcher.prototype.addEventHandler = function (eventHandler) {
for (var i = 0, len = this._eventHandlers.length; i < len; i++) {
if (this._eventHandlers[i] === eventHandler) {
console.warn('Detected duplicate listener in ViewEventDispatcher', eventHandler);
}
}
this._eventHandlers.push(eventHandler);
};
ViewEventDispatcher.prototype.removeEventHandler = function (eventHandler) {
for (var i = 0; i < this._eventHandlers.length; i++) {
if (this._eventHandlers[i] === eventHandler) {
this._eventHandlers.splice(i, 1);
break;
}
}
};
ViewEventDispatcher.prototype.emit = function (event) {
if (this._eventQueue) {
this._eventQueue.push(event);
}
else {
this._eventQueue = [event];
}
if (!this._isConsumingQueue) {
this.consumeQueue();
}
};
ViewEventDispatcher.prototype.emitMany = function (events) {
if (this._eventQueue) {
this._eventQueue = this._eventQueue.concat(events);
}
else {
this._eventQueue = events;
}
if (!this._isConsumingQueue) {
this.consumeQueue();
}
};
ViewEventDispatcher.prototype.consumeQueue = function () {
var _this = this;
this._eventHandlerGateKeeper(function () {
try {
_this._isConsumingQueue = true;
_this._doConsumeQueue();
}
finally {
_this._isConsumingQueue = false;
}
});
};
ViewEventDispatcher.prototype._doConsumeQueue = function () {
while (this._eventQueue) {
// Empty event queue, as events might come in while sending these off
var events = this._eventQueue;
this._eventQueue = null;
// Use a clone of the event handlers list, as they might remove themselves
var eventHandlers = this._eventHandlers.slice(0);
for (var i = 0, len = eventHandlers.length; i < len; i++) {
eventHandlers[i].handleEvents(events);
}
}
};
return ViewEventDispatcher;
}());
exports.ViewEventDispatcher = ViewEventDispatcher;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[81/*vs/editor/common/view/viewEvents*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/]), function (require, exports, errors, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ViewConfigurationChangedEvent = /** @class */ (function () {
function ViewConfigurationChangedEvent(source) {
this.type = 1 /* ViewConfigurationChanged */;
this._source = source;
}
ViewConfigurationChangedEvent.prototype.hasChanged = function (id) {
return this._source.hasChanged(id);
};
return ViewConfigurationChangedEvent;
}());
exports.ViewConfigurationChangedEvent = ViewConfigurationChangedEvent;
var ViewContentSizeChangedEvent = /** @class */ (function () {
function ViewContentSizeChangedEvent(source) {
this.type = 2 /* ViewContentSizeChanged */;
this.contentWidth = source.contentWidth;
this.contentHeight = source.contentHeight;
this.contentWidthChanged = source.contentWidthChanged;
this.contentHeightChanged = source.contentHeightChanged;
}
return ViewContentSizeChangedEvent;
}());
exports.ViewContentSizeChangedEvent = ViewContentSizeChangedEvent;
var ViewCursorStateChangedEvent = /** @class */ (function () {
function ViewCursorStateChangedEvent(selections, modelSelections) {
this.type = 3 /* ViewCursorStateChanged */;
this.selections = selections;
this.modelSelections = modelSelections;
}
return ViewCursorStateChangedEvent;
}());
exports.ViewCursorStateChangedEvent = ViewCursorStateChangedEvent;
var ViewDecorationsChangedEvent = /** @class */ (function () {
function ViewDecorationsChangedEvent() {
this.type = 4 /* ViewDecorationsChanged */;
// Nothing to do
}
return ViewDecorationsChangedEvent;
}());
exports.ViewDecorationsChangedEvent = ViewDecorationsChangedEvent;
var ViewFlushedEvent = /** @class */ (function () {
function ViewFlushedEvent() {
this.type = 5 /* ViewFlushed */;
// Nothing to do
}
return ViewFlushedEvent;
}());
exports.ViewFlushedEvent = ViewFlushedEvent;
var ViewFocusChangedEvent = /** @class */ (function () {
function ViewFocusChangedEvent(isFocused) {
this.type = 6 /* ViewFocusChanged */;
this.isFocused = isFocused;
}
return ViewFocusChangedEvent;
}());
exports.ViewFocusChangedEvent = ViewFocusChangedEvent;
var ViewLanguageConfigurationEvent = /** @class */ (function () {
function ViewLanguageConfigurationEvent() {
this.type = 7 /* ViewLanguageConfigurationChanged */;
}
return ViewLanguageConfigurationEvent;
}());
exports.ViewLanguageConfigurationEvent = ViewLanguageConfigurationEvent;
var ViewLineMappingChangedEvent = /** @class */ (function () {
function ViewLineMappingChangedEvent() {
this.type = 8 /* ViewLineMappingChanged */;
// Nothing to do
}
return ViewLineMappingChangedEvent;
}());
exports.ViewLineMappingChangedEvent = ViewLineMappingChangedEvent;
var ViewLinesChangedEvent = /** @class */ (function () {
function ViewLinesChangedEvent(fromLineNumber, toLineNumber) {
this.type = 9 /* ViewLinesChanged */;
this.fromLineNumber = fromLineNumber;
this.toLineNumber = toLineNumber;
}
return ViewLinesChangedEvent;
}());
exports.ViewLinesChangedEvent = ViewLinesChangedEvent;
var ViewLinesDeletedEvent = /** @class */ (function () {
function ViewLinesDeletedEvent(fromLineNumber, toLineNumber) {
this.type = 10 /* ViewLinesDeleted */;
this.fromLineNumber = fromLineNumber;
this.toLineNumber = toLineNumber;
}
return ViewLinesDeletedEvent;
}());
exports.ViewLinesDeletedEvent = ViewLinesDeletedEvent;
var ViewLinesInsertedEvent = /** @class */ (function () {
function ViewLinesInsertedEvent(fromLineNumber, toLineNumber) {
this.type = 11 /* ViewLinesInserted */;
this.fromLineNumber = fromLineNumber;
this.toLineNumber = toLineNumber;
}
return ViewLinesInsertedEvent;
}());
exports.ViewLinesInsertedEvent = ViewLinesInsertedEvent;
var ViewRevealRangeRequestEvent = /** @class */ (function () {
function ViewRevealRangeRequestEvent(source, range, verticalType, revealHorizontal, scrollType) {
this.type = 12 /* ViewRevealRangeRequest */;
this.source = source;
this.range = range;
this.verticalType = verticalType;
this.revealHorizontal = revealHorizontal;
this.scrollType = scrollType;
}
return ViewRevealRangeRequestEvent;
}());
exports.ViewRevealRangeRequestEvent = ViewRevealRangeRequestEvent;
var ViewScrollChangedEvent = /** @class */ (function () {
function ViewScrollChangedEvent(source) {
this.type = 13 /* ViewScrollChanged */;
this.scrollWidth = source.scrollWidth;
this.scrollLeft = source.scrollLeft;
this.scrollHeight = source.scrollHeight;
this.scrollTop = source.scrollTop;
this.scrollWidthChanged = source.scrollWidthChanged;
this.scrollLeftChanged = source.scrollLeftChanged;
this.scrollHeightChanged = source.scrollHeightChanged;
this.scrollTopChanged = source.scrollTopChanged;
}
return ViewScrollChangedEvent;
}());
exports.ViewScrollChangedEvent = ViewScrollChangedEvent;
var ViewThemeChangedEvent = /** @class */ (function () {
function ViewThemeChangedEvent() {
this.type = 14 /* ViewThemeChanged */;
}
return ViewThemeChangedEvent;
}());
exports.ViewThemeChangedEvent = ViewThemeChangedEvent;
var ViewTokensChangedEvent = /** @class */ (function () {
function ViewTokensChangedEvent(ranges) {
this.type = 15 /* ViewTokensChanged */;
this.ranges = ranges;
}
return ViewTokensChangedEvent;
}());
exports.ViewTokensChangedEvent = ViewTokensChangedEvent;
var ViewTokensColorsChangedEvent = /** @class */ (function () {
function ViewTokensColorsChangedEvent() {
this.type = 16 /* ViewTokensColorsChanged */;
// Nothing to do
}
return ViewTokensColorsChangedEvent;
}());
exports.ViewTokensColorsChangedEvent = ViewTokensColorsChangedEvent;
var ViewZonesChangedEvent = /** @class */ (function () {
function ViewZonesChangedEvent() {
this.type = 17 /* ViewZonesChanged */;
// Nothing to do
}
return ViewZonesChangedEvent;
}());
exports.ViewZonesChangedEvent = ViewZonesChangedEvent;
var ViewEventEmitter = /** @class */ (function (_super) {
__extends(ViewEventEmitter, _super);
function ViewEventEmitter() {
var _this = _super.call(this) || this;
_this._listeners = [];
_this._collector = null;
_this._collectorCnt = 0;
return _this;
}
ViewEventEmitter.prototype.dispose = function () {
this._listeners = [];
_super.prototype.dispose.call(this);
};
ViewEventEmitter.prototype._beginEmit = function () {
this._collectorCnt++;
if (this._collectorCnt === 1) {
this._collector = new ViewEventsCollector();
}
return this._collector;
};
ViewEventEmitter.prototype._endEmit = function () {
this._collectorCnt--;
if (this._collectorCnt === 0) {
var events = this._collector.finalize();
this._collector = null;
if (events.length > 0) {
this._emit(events);
}
}
};
ViewEventEmitter.prototype._emit = function (events) {
var listeners = this._listeners.slice(0);
for (var i = 0, len = listeners.length; i < len; i++) {
safeInvokeListener(listeners[i], events);
}
};
ViewEventEmitter.prototype.addEventListener = function (listener) {
var _this = this;
this._listeners.push(listener);
return lifecycle_1.toDisposable(function () {
var listeners = _this._listeners;
for (var i = 0, len = listeners.length; i < len; i++) {
if (listeners[i] === listener) {
listeners.splice(i, 1);
break;
}
}
});
};
return ViewEventEmitter;
}(lifecycle_1.Disposable));
exports.ViewEventEmitter = ViewEventEmitter;
var ViewEventsCollector = /** @class */ (function () {
function ViewEventsCollector() {
this._eventsLen = 0;
this._events = [];
this._eventsLen = 0;
}
ViewEventsCollector.prototype.emit = function (event) {
this._events[this._eventsLen++] = event;
};
ViewEventsCollector.prototype.finalize = function () {
var result = this._events;
this._events = [];
return result;
};
return ViewEventsCollector;
}());
exports.ViewEventsCollector = ViewEventsCollector;
function safeInvokeListener(listener, events) {
try {
listener(events);
}
catch (e) {
errors.onUnexpectedError(e);
}
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[148/*vs/editor/common/viewLayout/lineDecorations*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LineDecoration = /** @class */ (function () {
function LineDecoration(startColumn, endColumn, className, type) {
this.startColumn = startColumn;
this.endColumn = endColumn;
this.className = className;
this.type = type;
}
LineDecoration._equals = function (a, b) {
return (a.startColumn === b.startColumn
&& a.endColumn === b.endColumn
&& a.className === b.className
&& a.type === b.type);
};
LineDecoration.equalsArr = function (a, b) {
var aLen = a.length;
var bLen = b.length;
if (aLen !== bLen) {
return false;
}
for (var i = 0; i < aLen; i++) {
if (!LineDecoration._equals(a[i], b[i])) {
return false;
}
}
return true;
};
LineDecoration.filter = function (lineDecorations, lineNumber, minLineColumn, maxLineColumn) {
if (lineDecorations.length === 0) {
return [];
}
var result = [], resultLen = 0;
for (var i = 0, len = lineDecorations.length; i < len; i++) {
var d = lineDecorations[i];
var range = d.range;
if (range.endLineNumber < lineNumber || range.startLineNumber > lineNumber) {
// Ignore decorations that sit outside this line
continue;
}
if (range.isEmpty() && (d.type === 0 /* Regular */ || d.type === 3 /* RegularAffectingLetterSpacing */)) {
// Ignore empty range decorations
continue;
}
var startColumn = (range.startLineNumber === lineNumber ? range.startColumn : minLineColumn);
var endColumn = (range.endLineNumber === lineNumber ? range.endColumn : maxLineColumn);
result[resultLen++] = new LineDecoration(startColumn, endColumn, d.inlineClassName, d.type);
}
return result;
};
LineDecoration.compare = function (a, b) {
if (a.startColumn === b.startColumn) {
if (a.endColumn === b.endColumn) {
if (a.className < b.className) {
return -1;
}
if (a.className > b.className) {
return 1;
}
return 0;
}
return a.endColumn - b.endColumn;
}
return a.startColumn - b.startColumn;
};
return LineDecoration;
}());
exports.LineDecoration = LineDecoration;
var DecorationSegment = /** @class */ (function () {
function DecorationSegment(startOffset, endOffset, className) {
this.startOffset = startOffset;
this.endOffset = endOffset;
this.className = className;
}
return DecorationSegment;
}());
exports.DecorationSegment = DecorationSegment;
var Stack = /** @class */ (function () {
function Stack() {
this.stopOffsets = [];
this.classNames = [];
this.count = 0;
}
Stack.prototype.consumeLowerThan = function (maxStopOffset, nextStartOffset, result) {
while (this.count > 0 && this.stopOffsets[0] < maxStopOffset) {
var i = 0;
// Take all equal stopping offsets
while (i + 1 < this.count && this.stopOffsets[i] === this.stopOffsets[i + 1]) {
i++;
}
// Basically we are consuming the first i + 1 elements of the stack
result.push(new DecorationSegment(nextStartOffset, this.stopOffsets[i], this.classNames.join(' ')));
nextStartOffset = this.stopOffsets[i] + 1;
// Consume them
this.stopOffsets.splice(0, i + 1);
this.classNames.splice(0, i + 1);
this.count -= (i + 1);
}
if (this.count > 0 && nextStartOffset < maxStopOffset) {
result.push(new DecorationSegment(nextStartOffset, maxStopOffset - 1, this.classNames.join(' ')));
nextStartOffset = maxStopOffset;
}
return nextStartOffset;
};
Stack.prototype.insert = function (stopOffset, className) {
if (this.count === 0 || this.stopOffsets[this.count - 1] <= stopOffset) {
// Insert at the end
this.stopOffsets.push(stopOffset);
this.classNames.push(className);
}
else {
// Find the insertion position for `stopOffset`
for (var i = 0; i < this.count; i++) {
if (this.stopOffsets[i] >= stopOffset) {
this.stopOffsets.splice(i, 0, stopOffset);
this.classNames.splice(i, 0, className);
break;
}
}
}
this.count++;
return;
};
return Stack;
}());
var LineDecorationsNormalizer = /** @class */ (function () {
function LineDecorationsNormalizer() {
}
/**
* Normalize line decorations. Overlapping decorations will generate multiple segments
*/
LineDecorationsNormalizer.normalize = function (lineContent, lineDecorations) {
if (lineDecorations.length === 0) {
return [];
}
var result = [];
var stack = new Stack();
var nextStartOffset = 0;
for (var i = 0, len = lineDecorations.length; i < len; i++) {
var d = lineDecorations[i];
var startColumn = d.startColumn;
var endColumn = d.endColumn;
var className = d.className;
// If the position would end up in the middle of a high-low surrogate pair, we move it to before the pair
if (startColumn > 1) {
var charCodeBefore = lineContent.charCodeAt(startColumn - 2);
if (strings.isHighSurrogate(charCodeBefore)) {
startColumn--;
}
}
if (endColumn > 1) {
var charCodeBefore = lineContent.charCodeAt(endColumn - 2);
if (strings.isHighSurrogate(charCodeBefore)) {
endColumn--;
}
}
var currentStartOffset = startColumn - 1;
var currentEndOffset = endColumn - 2;
nextStartOffset = stack.consumeLowerThan(currentStartOffset, nextStartOffset, result);
if (stack.count === 0) {
nextStartOffset = currentStartOffset;
}
stack.insert(currentEndOffset, className);
}
stack.consumeLowerThan(1073741824 /* MAX_SAFE_SMALL_INTEGER */, nextStartOffset, result);
return result;
};
return LineDecorationsNormalizer;
}());
exports.LineDecorationsNormalizer = LineDecorationsNormalizer;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[362/*vs/editor/common/viewLayout/linesLayout*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PendingChanges = /** @class */ (function () {
function PendingChanges() {
this._hasPending = false;
this._inserts = [];
this._changes = [];
this._removes = [];
}
PendingChanges.prototype.insert = function (x) {
this._hasPending = true;
this._inserts.push(x);
};
PendingChanges.prototype.change = function (x) {
this._hasPending = true;
this._changes.push(x);
};
PendingChanges.prototype.remove = function (x) {
this._hasPending = true;
this._removes.push(x);
};
PendingChanges.prototype.mustCommit = function () {
return this._hasPending;
};
PendingChanges.prototype.commit = function (linesLayout) {
if (!this._hasPending) {
return;
}
var inserts = this._inserts;
var changes = this._changes;
var removes = this._removes;
this._hasPending = false;
this._inserts = [];
this._changes = [];
this._removes = [];
linesLayout._commitPendingChanges(inserts, changes, removes);
};
return PendingChanges;
}());
var EditorWhitespace = /** @class */ (function () {
function EditorWhitespace(id, afterLineNumber, ordinal, height, minWidth) {
this.id = id;
this.afterLineNumber = afterLineNumber;
this.ordinal = ordinal;
this.height = height;
this.minWidth = minWidth;
this.prefixSum = 0;
}
return EditorWhitespace;
}());
exports.EditorWhitespace = EditorWhitespace;
/**
* Layouting of objects that take vertical space (by having a height) and push down other objects.
*
* These objects are basically either text (lines) or spaces between those lines (whitespaces).
* This provides commodity operations for working with lines that contain whitespace that pushes lines lower (vertically).
*/
var LinesLayout = /** @class */ (function () {
function LinesLayout(lineCount, lineHeight) {
this._instanceId = strings.singleLetterHash(++LinesLayout.INSTANCE_COUNT);
this._pendingChanges = new PendingChanges();
this._lastWhitespaceId = 0;
this._arr = [];
this._prefixSumValidIndex = -1;
this._minWidth = -1; /* marker for not being computed */
this._lineCount = lineCount;
this._lineHeight = lineHeight;
}
/**
* Find the insertion index for a new value inside a sorted array of values.
* If the value is already present in the sorted array, the insertion index will be after the already existing value.
*/
LinesLayout.findInsertionIndex = function (arr, afterLineNumber, ordinal) {
var low = 0;
var high = arr.length;
while (low < high) {
var mid = ((low + high) >>> 1);
if (afterLineNumber === arr[mid].afterLineNumber) {
if (ordinal < arr[mid].ordinal) {
high = mid;
}
else {
low = mid + 1;
}
}
else if (afterLineNumber < arr[mid].afterLineNumber) {
high = mid;
}
else {
low = mid + 1;
}
}
return low;
};
/**
* Change the height of a line in pixels.
*/
LinesLayout.prototype.setLineHeight = function (lineHeight) {
this._checkPendingChanges();
this._lineHeight = lineHeight;
};
/**
* Set the number of lines.
*
* @param lineCount New number of lines.
*/
LinesLayout.prototype.onFlushed = function (lineCount) {
this._checkPendingChanges();
this._lineCount = lineCount;
};
LinesLayout.prototype.changeWhitespace = function (callback) {
var _this = this;
try {
var accessor = {
insertWhitespace: function (afterLineNumber, ordinal, heightInPx, minWidth) {
afterLineNumber = afterLineNumber | 0;
ordinal = ordinal | 0;
heightInPx = heightInPx | 0;
minWidth = minWidth | 0;
var id = _this._instanceId + (++_this._lastWhitespaceId);
_this._pendingChanges.insert(new EditorWhitespace(id, afterLineNumber, ordinal, heightInPx, minWidth));
return id;
},
changeOneWhitespace: function (id, newAfterLineNumber, newHeight) {
newAfterLineNumber = newAfterLineNumber | 0;
newHeight = newHeight | 0;
_this._pendingChanges.change({ id: id, newAfterLineNumber: newAfterLineNumber, newHeight: newHeight });
},
removeWhitespace: function (id) {
_this._pendingChanges.remove({ id: id });
}
};
return callback(accessor);
}
finally {
this._pendingChanges.commit(this);
}
};
LinesLayout.prototype._commitPendingChanges = function (inserts, changes, removes) {
if (inserts.length > 0 || removes.length > 0) {
this._minWidth = -1; /* marker for not being computed */
}
if (inserts.length + changes.length + removes.length <= 1) {
// when only one thing happened, handle it "delicately"
for (var _i = 0, inserts_1 = inserts; _i < inserts_1.length; _i++) {
var insert = inserts_1[_i];
this._insertWhitespace(insert);
}
for (var _a = 0, changes_1 = changes; _a < changes_1.length; _a++) {
var change = changes_1[_a];
this._changeOneWhitespace(change.id, change.newAfterLineNumber, change.newHeight);
}
for (var _b = 0, removes_1 = removes; _b < removes_1.length; _b++) {
var remove = removes_1[_b];
var index = this._findWhitespaceIndex(remove.id);
if (index === -1) {
continue;
}
this._removeWhitespace(index);
}
return;
}
// simply rebuild the entire datastructure
var toRemove = new Set();
for (var _c = 0, removes_2 = removes; _c < removes_2.length; _c++) {
var remove = removes_2[_c];
toRemove.add(remove.id);
}
var toChange = new Map();
for (var _d = 0, changes_2 = changes; _d < changes_2.length; _d++) {
var change = changes_2[_d];
toChange.set(change.id, change);
}
var applyRemoveAndChange = function (whitespaces) {
var result = [];
for (var _i = 0, whitespaces_1 = whitespaces; _i < whitespaces_1.length; _i++) {
var whitespace = whitespaces_1[_i];
if (toRemove.has(whitespace.id)) {
continue;
}
if (toChange.has(whitespace.id)) {
var change = toChange.get(whitespace.id);
whitespace.afterLineNumber = change.newAfterLineNumber;
whitespace.height = change.newHeight;
}
result.push(whitespace);
}
return result;
};
var result = applyRemoveAndChange(this._arr).concat(applyRemoveAndChange(inserts));
result.sort(function (a, b) {
if (a.afterLineNumber === b.afterLineNumber) {
return a.ordinal - b.ordinal;
}
return a.afterLineNumber - b.afterLineNumber;
});
this._arr = result;
this._prefixSumValidIndex = -1;
};
LinesLayout.prototype._checkPendingChanges = function () {
if (this._pendingChanges.mustCommit()) {
this._pendingChanges.commit(this);
}
};
LinesLayout.prototype._insertWhitespace = function (whitespace) {
var insertIndex = LinesLayout.findInsertionIndex(this._arr, whitespace.afterLineNumber, whitespace.ordinal);
this._arr.splice(insertIndex, 0, whitespace);
this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1);
};
LinesLayout.prototype._findWhitespaceIndex = function (id) {
var arr = this._arr;
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i].id === id) {
return i;
}
}
return -1;
};
LinesLayout.prototype._changeOneWhitespace = function (id, newAfterLineNumber, newHeight) {
var index = this._findWhitespaceIndex(id);
if (index === -1) {
return;
}
if (this._arr[index].height !== newHeight) {
this._arr[index].height = newHeight;
this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index - 1);
}
if (this._arr[index].afterLineNumber !== newAfterLineNumber) {
// `afterLineNumber` changed for this whitespace
// Record old whitespace
var whitespace = this._arr[index];
// Since changing `afterLineNumber` can trigger a reordering, we're gonna remove this whitespace
this._removeWhitespace(index);
whitespace.afterLineNumber = newAfterLineNumber;
// And add it again
this._insertWhitespace(whitespace);
}
};
LinesLayout.prototype._removeWhitespace = function (removeIndex) {
this._arr.splice(removeIndex, 1);
this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, removeIndex - 1);
};
/**
* Notify the layouter that lines have been deleted (a continuous zone of lines).
*
* @param fromLineNumber The line number at which the deletion started, inclusive
* @param toLineNumber The line number at which the deletion ended, inclusive
*/
LinesLayout.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) {
this._checkPendingChanges();
fromLineNumber = fromLineNumber | 0;
toLineNumber = toLineNumber | 0;
this._lineCount -= (toLineNumber - fromLineNumber + 1);
for (var i = 0, len = this._arr.length; i < len; i++) {
var afterLineNumber = this._arr[i].afterLineNumber;
if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) {
// The line this whitespace was after has been deleted
// => move whitespace to before first deleted line
this._arr[i].afterLineNumber = fromLineNumber - 1;
}
else if (afterLineNumber > toLineNumber) {
// The line this whitespace was after has been moved up
// => move whitespace up
this._arr[i].afterLineNumber -= (toLineNumber - fromLineNumber + 1);
}
}
};
/**
* Notify the layouter that lines have been inserted (a continuous zone of lines).
*
* @param fromLineNumber The line number at which the insertion started, inclusive
* @param toLineNumber The line number at which the insertion ended, inclusive.
*/
LinesLayout.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) {
this._checkPendingChanges();
fromLineNumber = fromLineNumber | 0;
toLineNumber = toLineNumber | 0;
this._lineCount += (toLineNumber - fromLineNumber + 1);
for (var i = 0, len = this._arr.length; i < len; i++) {
var afterLineNumber = this._arr[i].afterLineNumber;
if (fromLineNumber <= afterLineNumber) {
this._arr[i].afterLineNumber += (toLineNumber - fromLineNumber + 1);
}
}
};
/**
* Get the sum of all the whitespaces.
*/
LinesLayout.prototype.getWhitespacesTotalHeight = function () {
this._checkPendingChanges();
if (this._arr.length === 0) {
return 0;
}
return this.getWhitespacesAccumulatedHeight(this._arr.length - 1);
};
/**
* Return the sum of the heights of the whitespaces at [0..index].
* This includes the whitespace at `index`.
*
* @param index The index of the whitespace.
* @return The sum of the heights of all whitespaces before the one at `index`, including the one at `index`.
*/
LinesLayout.prototype.getWhitespacesAccumulatedHeight = function (index) {
this._checkPendingChanges();
index = index | 0;
var startIndex = Math.max(0, this._prefixSumValidIndex + 1);
if (startIndex === 0) {
this._arr[0].prefixSum = this._arr[0].height;
startIndex++;
}
for (var i = startIndex; i <= index; i++) {
this._arr[i].prefixSum = this._arr[i - 1].prefixSum + this._arr[i].height;
}
this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index);
return this._arr[index].prefixSum;
};
/**
* Get the sum of heights for all objects.
*
* @return The sum of heights for all objects.
*/
LinesLayout.prototype.getLinesTotalHeight = function () {
this._checkPendingChanges();
var linesHeight = this._lineHeight * this._lineCount;
var whitespacesHeight = this.getWhitespacesTotalHeight();
return linesHeight + whitespacesHeight;
};
/**
* Returns the accumulated height of whitespaces before the given line number.
*
* @param lineNumber The line number
*/
LinesLayout.prototype.getWhitespaceAccumulatedHeightBeforeLineNumber = function (lineNumber) {
this._checkPendingChanges();
lineNumber = lineNumber | 0;
var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
if (lastWhitespaceBeforeLineNumber === -1) {
return 0;
}
return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber);
};
LinesLayout.prototype._findLastWhitespaceBeforeLineNumber = function (lineNumber) {
lineNumber = lineNumber | 0;
// Find the whitespace before line number
var arr = this._arr;
var low = 0;
var high = arr.length - 1;
while (low <= high) {
var delta = (high - low) | 0;
var halfDelta = (delta / 2) | 0;
var mid = (low + halfDelta) | 0;
if (arr[mid].afterLineNumber < lineNumber) {
if (mid + 1 >= arr.length || arr[mid + 1].afterLineNumber >= lineNumber) {
return mid;
}
else {
low = (mid + 1) | 0;
}
}
else {
high = (mid - 1) | 0;
}
}
return -1;
};
LinesLayout.prototype._findFirstWhitespaceAfterLineNumber = function (lineNumber) {
lineNumber = lineNumber | 0;
var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
var firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1;
if (firstWhitespaceAfterLineNumber < this._arr.length) {
return firstWhitespaceAfterLineNumber;
}
return -1;
};
/**
* Find the index of the first whitespace which has `afterLineNumber` >= `lineNumber`.
* @return The index of the first whitespace with `afterLineNumber` >= `lineNumber` or -1 if no whitespace is found.
*/
LinesLayout.prototype.getFirstWhitespaceIndexAfterLineNumber = function (lineNumber) {
this._checkPendingChanges();
lineNumber = lineNumber | 0;
return this._findFirstWhitespaceAfterLineNumber(lineNumber);
};
/**
* Get the vertical offset (the sum of heights for all objects above) a certain line number.
*
* @param lineNumber The line number
* @return The sum of heights for all objects above `lineNumber`.
*/
LinesLayout.prototype.getVerticalOffsetForLineNumber = function (lineNumber) {
this._checkPendingChanges();
lineNumber = lineNumber | 0;
var previousLinesHeight;
if (lineNumber > 1) {
previousLinesHeight = this._lineHeight * (lineNumber - 1);
}
else {
previousLinesHeight = 0;
}
var previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber);
return previousLinesHeight + previousWhitespacesHeight;
};
/**
* The maximum min width for all whitespaces.
*/
LinesLayout.prototype.getWhitespaceMinWidth = function () {
this._checkPendingChanges();
if (this._minWidth === -1) {
var minWidth = 0;
for (var i = 0, len = this._arr.length; i < len; i++) {
minWidth = Math.max(minWidth, this._arr[i].minWidth);
}
this._minWidth = minWidth;
}
return this._minWidth;
};
/**
* Check if `verticalOffset` is below all lines.
*/
LinesLayout.prototype.isAfterLines = function (verticalOffset) {
this._checkPendingChanges();
var totalHeight = this.getLinesTotalHeight();
return verticalOffset > totalHeight;
};
/**
* Find the first line number that is at or after vertical offset `verticalOffset`.
* i.e. if getVerticalOffsetForLine(line) is x and getVerticalOffsetForLine(line + 1) is y, then
* getLineNumberAtOrAfterVerticalOffset(i) = line, x <= i < y.
*
* @param verticalOffset The vertical offset to search at.
* @return The line number at or after vertical offset `verticalOffset`.
*/
LinesLayout.prototype.getLineNumberAtOrAfterVerticalOffset = function (verticalOffset) {
this._checkPendingChanges();
verticalOffset = verticalOffset | 0;
if (verticalOffset < 0) {
return 1;
}
var linesCount = this._lineCount | 0;
var lineHeight = this._lineHeight;
var minLineNumber = 1;
var maxLineNumber = linesCount;
while (minLineNumber < maxLineNumber) {
var midLineNumber = ((minLineNumber + maxLineNumber) / 2) | 0;
var midLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(midLineNumber) | 0;
if (verticalOffset >= midLineNumberVerticalOffset + lineHeight) {
// vertical offset is after mid line number
minLineNumber = midLineNumber + 1;
}
else if (verticalOffset >= midLineNumberVerticalOffset) {
// Hit
return midLineNumber;
}
else {
// vertical offset is before mid line number, but mid line number could still be what we're searching for
maxLineNumber = midLineNumber;
}
}
if (minLineNumber > linesCount) {
return linesCount;
}
return minLineNumber;
};
/**
* Get all the lines and their relative vertical offsets that are positioned between `verticalOffset1` and `verticalOffset2`.
*
* @param verticalOffset1 The beginning of the viewport.
* @param verticalOffset2 The end of the viewport.
* @return A structure describing the lines positioned between `verticalOffset1` and `verticalOffset2`.
*/
LinesLayout.prototype.getLinesViewportData = function (verticalOffset1, verticalOffset2) {
this._checkPendingChanges();
verticalOffset1 = verticalOffset1 | 0;
verticalOffset2 = verticalOffset2 | 0;
var lineHeight = this._lineHeight;
// Find first line number
// We don't live in a perfect world, so the line number might start before or after verticalOffset1
var startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0;
var startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0;
var endLineNumber = this._lineCount | 0;
// Also keep track of what whitespace we've got
var whitespaceIndex = this.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0;
var whitespaceCount = this.getWhitespacesCount() | 0;
var currentWhitespaceHeight;
var currentWhitespaceAfterLineNumber;
if (whitespaceIndex === -1) {
whitespaceIndex = whitespaceCount;
currentWhitespaceAfterLineNumber = endLineNumber + 1;
currentWhitespaceHeight = 0;
}
else {
currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
}
var currentVerticalOffset = startLineNumberVerticalOffset;
var currentLineRelativeOffset = currentVerticalOffset;
// IE (all versions) cannot handle units above about 1,533,908 px, so every 500k pixels bring numbers down
var STEP_SIZE = 500000;
var bigNumbersDelta = 0;
if (startLineNumberVerticalOffset >= STEP_SIZE) {
// Compute a delta that guarantees that lines are positioned at `lineHeight` increments
bigNumbersDelta = Math.floor(startLineNumberVerticalOffset / STEP_SIZE) * STEP_SIZE;
bigNumbersDelta = Math.floor(bigNumbersDelta / lineHeight) * lineHeight;
currentLineRelativeOffset -= bigNumbersDelta;
}
var linesOffsets = [];
var verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2;
var centeredLineNumber = -1;
// Figure out how far the lines go
for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
if (centeredLineNumber === -1) {
var currentLineTop = currentVerticalOffset;
var currentLineBottom = currentVerticalOffset + lineHeight;
if ((currentLineTop <= verticalCenter && verticalCenter < currentLineBottom) || currentLineTop > verticalCenter) {
centeredLineNumber = lineNumber;
}
}
// Count current line height in the vertical offsets
currentVerticalOffset += lineHeight;
linesOffsets[lineNumber - startLineNumber] = currentLineRelativeOffset;
// Next line starts immediately after this one
currentLineRelativeOffset += lineHeight;
while (currentWhitespaceAfterLineNumber === lineNumber) {
// Push down next line with the height of the current whitespace
currentLineRelativeOffset += currentWhitespaceHeight;
// Count current whitespace in the vertical offsets
currentVerticalOffset += currentWhitespaceHeight;
whitespaceIndex++;
if (whitespaceIndex >= whitespaceCount) {
currentWhitespaceAfterLineNumber = endLineNumber + 1;
}
else {
currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
}
}
if (currentVerticalOffset >= verticalOffset2) {
// We have covered the entire viewport area, time to stop
endLineNumber = lineNumber;
break;
}
}
if (centeredLineNumber === -1) {
centeredLineNumber = endLineNumber;
}
var endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0;
var completelyVisibleStartLineNumber = startLineNumber;
var completelyVisibleEndLineNumber = endLineNumber;
if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
if (startLineNumberVerticalOffset < verticalOffset1) {
completelyVisibleStartLineNumber++;
}
}
if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
if (endLineNumberVerticalOffset + lineHeight > verticalOffset2) {
completelyVisibleEndLineNumber--;
}
}
return {
bigNumbersDelta: bigNumbersDelta,
startLineNumber: startLineNumber,
endLineNumber: endLineNumber,
relativeVerticalOffset: linesOffsets,
centeredLineNumber: centeredLineNumber,
completelyVisibleStartLineNumber: completelyVisibleStartLineNumber,
completelyVisibleEndLineNumber: completelyVisibleEndLineNumber
};
};
LinesLayout.prototype.getVerticalOffsetForWhitespaceIndex = function (whitespaceIndex) {
this._checkPendingChanges();
whitespaceIndex = whitespaceIndex | 0;
var afterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex);
var previousLinesHeight;
if (afterLineNumber >= 1) {
previousLinesHeight = this._lineHeight * afterLineNumber;
}
else {
previousLinesHeight = 0;
}
var previousWhitespacesHeight;
if (whitespaceIndex > 0) {
previousWhitespacesHeight = this.getWhitespacesAccumulatedHeight(whitespaceIndex - 1);
}
else {
previousWhitespacesHeight = 0;
}
return previousLinesHeight + previousWhitespacesHeight;
};
LinesLayout.prototype.getWhitespaceIndexAtOrAfterVerticallOffset = function (verticalOffset) {
this._checkPendingChanges();
verticalOffset = verticalOffset | 0;
var minWhitespaceIndex = 0;
var maxWhitespaceIndex = this.getWhitespacesCount() - 1;
if (maxWhitespaceIndex < 0) {
return -1;
}
// Special case: nothing to be found
var maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex);
var maxWhitespaceHeight = this.getHeightForWhitespaceIndex(maxWhitespaceIndex);
if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) {
return -1;
}
while (minWhitespaceIndex < maxWhitespaceIndex) {
var midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2);
var midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex);
var midWhitespaceHeight = this.getHeightForWhitespaceIndex(midWhitespaceIndex);
if (verticalOffset >= midWhitespaceVerticalOffset + midWhitespaceHeight) {
// vertical offset is after whitespace
minWhitespaceIndex = midWhitespaceIndex + 1;
}
else if (verticalOffset >= midWhitespaceVerticalOffset) {
// Hit
return midWhitespaceIndex;
}
else {
// vertical offset is before whitespace, but midWhitespaceIndex might still be what we're searching for
maxWhitespaceIndex = midWhitespaceIndex;
}
}
return minWhitespaceIndex;
};
/**
* Get exactly the whitespace that is layouted at `verticalOffset`.
*
* @param verticalOffset The vertical offset.
* @return Precisely the whitespace that is layouted at `verticaloffset` or null.
*/
LinesLayout.prototype.getWhitespaceAtVerticalOffset = function (verticalOffset) {
this._checkPendingChanges();
verticalOffset = verticalOffset | 0;
var candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset);
if (candidateIndex < 0) {
return null;
}
if (candidateIndex >= this.getWhitespacesCount()) {
return null;
}
var candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex);
if (candidateTop > verticalOffset) {
return null;
}
var candidateHeight = this.getHeightForWhitespaceIndex(candidateIndex);
var candidateId = this.getIdForWhitespaceIndex(candidateIndex);
var candidateAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(candidateIndex);
return {
id: candidateId,
afterLineNumber: candidateAfterLineNumber,
verticalOffset: candidateTop,
height: candidateHeight
};
};
/**
* Get a list of whitespaces that are positioned between `verticalOffset1` and `verticalOffset2`.
*
* @param verticalOffset1 The beginning of the viewport.
* @param verticalOffset2 The end of the viewport.
* @return An array with all the whitespaces in the viewport. If no whitespace is in viewport, the array is empty.
*/
LinesLayout.prototype.getWhitespaceViewportData = function (verticalOffset1, verticalOffset2) {
this._checkPendingChanges();
verticalOffset1 = verticalOffset1 | 0;
verticalOffset2 = verticalOffset2 | 0;
var startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1);
var endIndex = this.getWhitespacesCount() - 1;
if (startIndex < 0) {
return [];
}
var result = [];
for (var i = startIndex; i <= endIndex; i++) {
var top_1 = this.getVerticalOffsetForWhitespaceIndex(i);
var height = this.getHeightForWhitespaceIndex(i);
if (top_1 >= verticalOffset2) {
break;
}
result.push({
id: this.getIdForWhitespaceIndex(i),
afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i),
verticalOffset: top_1,
height: height
});
}
return result;
};
/**
* Get all whitespaces.
*/
LinesLayout.prototype.getWhitespaces = function () {
this._checkPendingChanges();
return this._arr.slice(0);
};
/**
* The number of whitespaces.
*/
LinesLayout.prototype.getWhitespacesCount = function () {
this._checkPendingChanges();
return this._arr.length;
};
/**
* Get the `id` for whitespace at index `index`.
*
* @param index The index of the whitespace.
* @return `id` of whitespace at `index`.
*/
LinesLayout.prototype.getIdForWhitespaceIndex = function (index) {
this._checkPendingChanges();
index = index | 0;
return this._arr[index].id;
};
/**
* Get the `afterLineNumber` for whitespace at index `index`.
*
* @param index The index of the whitespace.
* @return `afterLineNumber` of whitespace at `index`.
*/
LinesLayout.prototype.getAfterLineNumberForWhitespaceIndex = function (index) {
this._checkPendingChanges();
index = index | 0;
return this._arr[index].afterLineNumber;
};
/**
* Get the `height` for whitespace at index `index`.
*
* @param index The index of the whitespace.
* @return `height` of whitespace at `index`.
*/
LinesLayout.prototype.getHeightForWhitespaceIndex = function (index) {
this._checkPendingChanges();
index = index | 0;
return this._arr[index].height;
};
LinesLayout.INSTANCE_COUNT = 0;
return LinesLayout;
}());
exports.LinesLayout = LinesLayout;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[110/*vs/editor/common/viewLayout/viewLineRenderer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,106/*vs/editor/common/core/stringBuilder*/,148/*vs/editor/common/viewLayout/lineDecorations*/]), function (require, exports, strings, stringBuilder_1, lineDecorations_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LinePart = /** @class */ (function () {
function LinePart(endIndex, type) {
this.endIndex = endIndex;
this.type = type;
}
return LinePart;
}());
var LineRange = /** @class */ (function () {
function LineRange(startIndex, endIndex) {
this.startOffset = startIndex;
this.endOffset = endIndex;
}
LineRange.prototype.equals = function (otherLineRange) {
return this.startOffset === otherLineRange.startOffset
&& this.endOffset === otherLineRange.endOffset;
};
return LineRange;
}());
exports.LineRange = LineRange;
var RenderLineInput = /** @class */ (function () {
function RenderLineInput(useMonospaceOptimizations, canUseHalfwidthRightwardsArrow, lineContent, continuesWithWrappedLine, isBasicASCII, containsRTL, fauxIndentLength, lineTokens, lineDecorations, tabSize, startVisibleColumn, spaceWidth, middotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, selectionsOnLine) {
this.useMonospaceOptimizations = useMonospaceOptimizations;
this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
this.lineContent = lineContent;
this.continuesWithWrappedLine = continuesWithWrappedLine;
this.isBasicASCII = isBasicASCII;
this.containsRTL = containsRTL;
this.fauxIndentLength = fauxIndentLength;
this.lineTokens = lineTokens;
this.lineDecorations = lineDecorations;
this.tabSize = tabSize;
this.startVisibleColumn = startVisibleColumn;
this.spaceWidth = spaceWidth;
this.middotWidth = middotWidth;
this.stopRenderingLineAfter = stopRenderingLineAfter;
this.renderWhitespace = (renderWhitespace === 'all'
? 3 /* All */
: renderWhitespace === 'boundary'
? 1 /* Boundary */
: renderWhitespace === 'selection'
? 2 /* Selection */
: 0 /* None */);
this.renderControlCharacters = renderControlCharacters;
this.fontLigatures = fontLigatures;
this.selectionsOnLine = selectionsOnLine && selectionsOnLine.sort(function (a, b) { return a.startOffset < b.startOffset ? -1 : 1; });
}
RenderLineInput.prototype.sameSelection = function (otherSelections) {
if (this.selectionsOnLine === null) {
return otherSelections === null;
}
if (otherSelections === null) {
return false;
}
if (otherSelections.length !== this.selectionsOnLine.length) {
return false;
}
for (var i = 0; i < this.selectionsOnLine.length; i++) {
if (!this.selectionsOnLine[i].equals(otherSelections[i])) {
return false;
}
}
return true;
};
RenderLineInput.prototype.equals = function (other) {
return (this.useMonospaceOptimizations === other.useMonospaceOptimizations
&& this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow
&& this.lineContent === other.lineContent
&& this.continuesWithWrappedLine === other.continuesWithWrappedLine
&& this.isBasicASCII === other.isBasicASCII
&& this.containsRTL === other.containsRTL
&& this.fauxIndentLength === other.fauxIndentLength
&& this.tabSize === other.tabSize
&& this.startVisibleColumn === other.startVisibleColumn
&& this.spaceWidth === other.spaceWidth
&& this.stopRenderingLineAfter === other.stopRenderingLineAfter
&& this.renderWhitespace === other.renderWhitespace
&& this.renderControlCharacters === other.renderControlCharacters
&& this.fontLigatures === other.fontLigatures
&& lineDecorations_1.LineDecoration.equalsArr(this.lineDecorations, other.lineDecorations)
&& this.lineTokens.equals(other.lineTokens)
&& this.sameSelection(other.selectionsOnLine));
};
return RenderLineInput;
}());
exports.RenderLineInput = RenderLineInput;
/**
* Provides a both direction mapping between a line's character and its rendered position.
*/
var CharacterMapping = /** @class */ (function () {
function CharacterMapping(length, partCount) {
this.length = length;
this._data = new Uint32Array(this.length);
this._absoluteOffsets = new Uint32Array(this.length);
}
CharacterMapping.getPartIndex = function (partData) {
return (partData & 4294901760 /* PART_INDEX_MASK */) >>> 16 /* PART_INDEX_OFFSET */;
};
CharacterMapping.getCharIndex = function (partData) {
return (partData & 65535 /* CHAR_INDEX_MASK */) >>> 0 /* CHAR_INDEX_OFFSET */;
};
CharacterMapping.prototype.setPartData = function (charOffset, partIndex, charIndex, partAbsoluteOffset) {
var partData = ((partIndex << 16 /* PART_INDEX_OFFSET */)
| (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0;
this._data[charOffset] = partData;
this._absoluteOffsets[charOffset] = partAbsoluteOffset + charIndex;
};
CharacterMapping.prototype.getAbsoluteOffsets = function () {
return this._absoluteOffsets;
};
CharacterMapping.prototype.charOffsetToPartData = function (charOffset) {
if (this.length === 0) {
return 0;
}
if (charOffset < 0) {
return this._data[0];
}
if (charOffset >= this.length) {
return this._data[this.length - 1];
}
return this._data[charOffset];
};
CharacterMapping.prototype.partDataToCharOffset = function (partIndex, partLength, charIndex) {
if (this.length === 0) {
return 0;
}
var searchEntry = ((partIndex << 16 /* PART_INDEX_OFFSET */)
| (charIndex << 0 /* CHAR_INDEX_OFFSET */)) >>> 0;
var min = 0;
var max = this.length - 1;
while (min + 1 < max) {
var mid = ((min + max) >>> 1);
var midEntry = this._data[mid];
if (midEntry === searchEntry) {
return mid;
}
else if (midEntry > searchEntry) {
max = mid;
}
else {
min = mid;
}
}
if (min === max) {
return min;
}
var minEntry = this._data[min];
var maxEntry = this._data[max];
if (minEntry === searchEntry) {
return min;
}
if (maxEntry === searchEntry) {
return max;
}
var minPartIndex = CharacterMapping.getPartIndex(minEntry);
var minCharIndex = CharacterMapping.getCharIndex(minEntry);
var maxPartIndex = CharacterMapping.getPartIndex(maxEntry);
var maxCharIndex;
if (minPartIndex !== maxPartIndex) {
// sitting between parts
maxCharIndex = partLength;
}
else {
maxCharIndex = CharacterMapping.getCharIndex(maxEntry);
}
var minEntryDistance = charIndex - minCharIndex;
var maxEntryDistance = maxCharIndex - charIndex;
if (minEntryDistance <= maxEntryDistance) {
return min;
}
return max;
};
return CharacterMapping;
}());
exports.CharacterMapping = CharacterMapping;
var RenderLineOutput = /** @class */ (function () {
function RenderLineOutput(characterMapping, containsRTL, containsForeignElements) {
this.characterMapping = characterMapping;
this.containsRTL = containsRTL;
this.containsForeignElements = containsForeignElements;
}
return RenderLineOutput;
}());
exports.RenderLineOutput = RenderLineOutput;
function renderViewLine(input, sb) {
if (input.lineContent.length === 0) {
var containsForeignElements = 0 /* None */;
// This is basically for IE's hit test to work
var content = '\u00a0';
if (input.lineDecorations.length > 0) {
// This line is empty, but it contains inline decorations
var beforeClassNames = [];
var afterClassNames = [];
for (var i = 0, len = input.lineDecorations.length; i < len; i++) {
var lineDecoration = input.lineDecorations[i];
if (lineDecoration.type === 1 /* Before */) {
beforeClassNames.push(input.lineDecorations[i].className);
containsForeignElements |= 1 /* Before */;
}
if (lineDecoration.type === 2 /* After */) {
afterClassNames.push(input.lineDecorations[i].className);
containsForeignElements |= 2 /* After */;
}
}
if (containsForeignElements !== 0 /* None */) {
var beforeSpan = (beforeClassNames.length > 0 ? "" : "");
var afterSpan = (afterClassNames.length > 0 ? "" : "");
content = "" + beforeSpan + afterSpan + "";
}
}
sb.appendASCIIString(content);
return new RenderLineOutput(new CharacterMapping(0, 0), false, containsForeignElements);
}
return _renderLine(resolveRenderLineInput(input), sb);
}
exports.renderViewLine = renderViewLine;
var RenderLineOutput2 = /** @class */ (function () {
function RenderLineOutput2(characterMapping, html, containsRTL, containsForeignElements) {
this.characterMapping = characterMapping;
this.html = html;
this.containsRTL = containsRTL;
this.containsForeignElements = containsForeignElements;
}
return RenderLineOutput2;
}());
exports.RenderLineOutput2 = RenderLineOutput2;
function renderViewLine2(input) {
var sb = stringBuilder_1.createStringBuilder(10000);
var out = renderViewLine(input, sb);
return new RenderLineOutput2(out.characterMapping, sb.build(), out.containsRTL, out.containsForeignElements);
}
exports.renderViewLine2 = renderViewLine2;
var ResolvedRenderLineInput = /** @class */ (function () {
function ResolvedRenderLineInput(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, parts, containsForeignElements, fauxIndentLength, tabSize, startVisibleColumn, containsRTL, spaceWidth, middotWidth, renderWhitespace, renderControlCharacters) {
this.fontIsMonospace = fontIsMonospace;
this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
this.lineContent = lineContent;
this.len = len;
this.isOverflowing = isOverflowing;
this.parts = parts;
this.containsForeignElements = containsForeignElements;
this.fauxIndentLength = fauxIndentLength;
this.tabSize = tabSize;
this.startVisibleColumn = startVisibleColumn;
this.containsRTL = containsRTL;
this.spaceWidth = spaceWidth;
this.middotWidth = middotWidth;
this.renderWhitespace = renderWhitespace;
this.renderControlCharacters = renderControlCharacters;
//
}
return ResolvedRenderLineInput;
}());
function resolveRenderLineInput(input) {
var useMonospaceOptimizations = input.useMonospaceOptimizations;
var lineContent = input.lineContent;
var isOverflowing;
var len;
if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) {
isOverflowing = true;
len = input.stopRenderingLineAfter;
}
else {
isOverflowing = false;
len = lineContent.length;
}
var tokens = transformAndRemoveOverflowing(input.lineTokens, input.fauxIndentLength, len);
if (input.renderWhitespace === 3 /* All */ || input.renderWhitespace === 1 /* Boundary */ || (input.renderWhitespace === 2 /* Selection */ && !!input.selectionsOnLine)) {
tokens = _applyRenderWhitespace(lineContent, len, input.continuesWithWrappedLine, tokens, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, useMonospaceOptimizations, input.selectionsOnLine, input.renderWhitespace === 1 /* Boundary */);
}
var containsForeignElements = 0 /* None */;
if (input.lineDecorations.length > 0) {
for (var i = 0, len_1 = input.lineDecorations.length; i < len_1; i++) {
var lineDecoration = input.lineDecorations[i];
if (lineDecoration.type === 3 /* RegularAffectingLetterSpacing */) {
// Pretend there are foreign elements... although not 100% accurate.
containsForeignElements |= 1 /* Before */;
}
else if (lineDecoration.type === 1 /* Before */) {
containsForeignElements |= 1 /* Before */;
}
else if (lineDecoration.type === 2 /* After */) {
containsForeignElements |= 2 /* After */;
}
}
tokens = _applyInlineDecorations(lineContent, len, tokens, input.lineDecorations);
}
if (!input.containsRTL) {
// We can never split RTL text, as it ruins the rendering
tokens = splitLargeTokens(lineContent, tokens, !input.isBasicASCII || input.fontLigatures);
}
return new ResolvedRenderLineInput(useMonospaceOptimizations, input.canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, tokens, containsForeignElements, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, input.containsRTL, input.spaceWidth, input.middotWidth, input.renderWhitespace, input.renderControlCharacters);
}
/**
* In the rendering phase, characters are always looped until token.endIndex.
* Ensure that all tokens end before `len` and the last one ends precisely at `len`.
*/
function transformAndRemoveOverflowing(tokens, fauxIndentLength, len) {
var result = [], resultLen = 0;
// The faux indent part of the line should have no token type
if (fauxIndentLength > 0) {
result[resultLen++] = new LinePart(fauxIndentLength, '');
}
for (var tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
var endIndex = tokens.getEndOffset(tokenIndex);
if (endIndex <= fauxIndentLength) {
// The faux indent part of the line should have no token type
continue;
}
var type = tokens.getClassName(tokenIndex);
if (endIndex >= len) {
result[resultLen++] = new LinePart(len, type);
break;
}
result[resultLen++] = new LinePart(endIndex, type);
}
return result;
}
/**
* See https://github.com/Microsoft/vscode/issues/6885.
* It appears that having very large spans causes very slow reading of character positions.
* So here we try to avoid that.
*/
function splitLargeTokens(lineContent, tokens, onlyAtSpaces) {
var lastTokenEndIndex = 0;
var result = [], resultLen = 0;
if (onlyAtSpaces) {
// Split only at spaces => we need to walk each character
for (var i = 0, len = tokens.length; i < len; i++) {
var token = tokens[i];
var tokenEndIndex = token.endIndex;
if (lastTokenEndIndex + 50 /* LongToken */ < tokenEndIndex) {
var tokenType = token.type;
var lastSpaceOffset = -1;
var currTokenStart = lastTokenEndIndex;
for (var j = lastTokenEndIndex; j < tokenEndIndex; j++) {
if (lineContent.charCodeAt(j) === 32 /* Space */) {
lastSpaceOffset = j;
}
if (lastSpaceOffset !== -1 && j - currTokenStart >= 50 /* LongToken */) {
// Split at `lastSpaceOffset` + 1
result[resultLen++] = new LinePart(lastSpaceOffset + 1, tokenType);
currTokenStart = lastSpaceOffset + 1;
lastSpaceOffset = -1;
}
}
if (currTokenStart !== tokenEndIndex) {
result[resultLen++] = new LinePart(tokenEndIndex, tokenType);
}
}
else {
result[resultLen++] = token;
}
lastTokenEndIndex = tokenEndIndex;
}
}
else {
// Split anywhere => we don't need to walk each character
for (var i = 0, len = tokens.length; i < len; i++) {
var token = tokens[i];
var tokenEndIndex = token.endIndex;
var diff = (tokenEndIndex - lastTokenEndIndex);
if (diff > 50 /* LongToken */) {
var tokenType = token.type;
var piecesCount = Math.ceil(diff / 50 /* LongToken */);
for (var j = 1; j < piecesCount; j++) {
var pieceEndIndex = lastTokenEndIndex + (j * 50 /* LongToken */);
result[resultLen++] = new LinePart(pieceEndIndex, tokenType);
}
result[resultLen++] = new LinePart(tokenEndIndex, tokenType);
}
else {
result[resultLen++] = token;
}
lastTokenEndIndex = tokenEndIndex;
}
}
return result;
}
/**
* Whitespace is rendered by "replacing" tokens with a special-purpose `vs-whitespace` type that is later recognized in the rendering phase.
* Moreover, a token is created for every visual indent because on some fonts the glyphs used for rendering whitespace (→ or ·) do not have the same width as .
* The rendering phase will generate `style="width:..."` for these tokens.
*/
function _applyRenderWhitespace(lineContent, len, continuesWithWrappedLine, tokens, fauxIndentLength, tabSize, startVisibleColumn, useMonospaceOptimizations, selections, onlyBoundary) {
var result = [], resultLen = 0;
var tokenIndex = 0;
var tokenType = tokens[tokenIndex].type;
var tokenEndIndex = tokens[tokenIndex].endIndex;
var tokensLength = tokens.length;
var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
var lastNonWhitespaceIndex;
if (firstNonWhitespaceIndex === -1) {
// The entire line is whitespace
firstNonWhitespaceIndex = len;
lastNonWhitespaceIndex = len;
}
else {
lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent);
}
var wasInWhitespace = false;
var currentSelectionIndex = 0;
var currentSelection = selections && selections[currentSelectionIndex];
var tmpIndent = startVisibleColumn % tabSize;
for (var charIndex = fauxIndentLength; charIndex < len; charIndex++) {
var chCode = lineContent.charCodeAt(charIndex);
if (currentSelection && charIndex >= currentSelection.endOffset) {
currentSelectionIndex++;
currentSelection = selections && selections[currentSelectionIndex];
}
var isInWhitespace = void 0;
if (charIndex < firstNonWhitespaceIndex || charIndex > lastNonWhitespaceIndex) {
// in leading or trailing whitespace
isInWhitespace = true;
}
else if (chCode === 9 /* Tab */) {
// a tab character is rendered both in all and boundary cases
isInWhitespace = true;
}
else if (chCode === 32 /* Space */) {
// hit a space character
if (onlyBoundary) {
// rendering only boundary whitespace
if (wasInWhitespace) {
isInWhitespace = true;
}
else {
var nextChCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* Null */);
isInWhitespace = (nextChCode === 32 /* Space */ || nextChCode === 9 /* Tab */);
}
}
else {
isInWhitespace = true;
}
}
else {
isInWhitespace = false;
}
// If rendering whitespace on selection, check that the charIndex falls within a selection
if (isInWhitespace && selections) {
isInWhitespace = !!currentSelection && currentSelection.startOffset <= charIndex && currentSelection.endOffset > charIndex;
}
if (wasInWhitespace) {
// was in whitespace token
if (!isInWhitespace || (!useMonospaceOptimizations && tmpIndent >= tabSize)) {
// leaving whitespace token or entering a new indent
result[resultLen++] = new LinePart(charIndex, 'vs-whitespace');
tmpIndent = tmpIndent % tabSize;
}
}
else {
// was in regular token
if (charIndex === tokenEndIndex || (isInWhitespace && charIndex > fauxIndentLength)) {
result[resultLen++] = new LinePart(charIndex, tokenType);
tmpIndent = tmpIndent % tabSize;
}
}
if (chCode === 9 /* Tab */) {
tmpIndent = tabSize;
}
else if (strings.isFullWidthCharacter(chCode)) {
tmpIndent += 2;
}
else {
tmpIndent++;
}
wasInWhitespace = isInWhitespace;
if (charIndex === tokenEndIndex) {
tokenIndex++;
if (tokenIndex < tokensLength) {
tokenType = tokens[tokenIndex].type;
tokenEndIndex = tokens[tokenIndex].endIndex;
}
}
}
var generateWhitespace = false;
if (wasInWhitespace) {
// was in whitespace token
if (continuesWithWrappedLine && onlyBoundary) {
var lastCharCode = (len > 0 ? lineContent.charCodeAt(len - 1) : 0 /* Null */);
var prevCharCode = (len > 1 ? lineContent.charCodeAt(len - 2) : 0 /* Null */);
var isSingleTrailingSpace = (lastCharCode === 32 /* Space */ && (prevCharCode !== 32 /* Space */ && prevCharCode !== 9 /* Tab */));
if (!isSingleTrailingSpace) {
generateWhitespace = true;
}
}
else {
generateWhitespace = true;
}
}
result[resultLen++] = new LinePart(len, generateWhitespace ? 'vs-whitespace' : tokenType);
return result;
}
/**
* Inline decorations are "merged" on top of tokens.
* Special care must be taken when multiple inline decorations are at play and they overlap.
*/
function _applyInlineDecorations(lineContent, len, tokens, _lineDecorations) {
_lineDecorations.sort(lineDecorations_1.LineDecoration.compare);
var lineDecorations = lineDecorations_1.LineDecorationsNormalizer.normalize(lineContent, _lineDecorations);
var lineDecorationsLen = lineDecorations.length;
var lineDecorationIndex = 0;
var result = [], resultLen = 0, lastResultEndIndex = 0;
for (var tokenIndex = 0, len_2 = tokens.length; tokenIndex < len_2; tokenIndex++) {
var token = tokens[tokenIndex];
var tokenEndIndex = token.endIndex;
var tokenType = token.type;
while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) {
var lineDecoration = lineDecorations[lineDecorationIndex];
if (lineDecoration.startOffset > lastResultEndIndex) {
lastResultEndIndex = lineDecoration.startOffset;
result[resultLen++] = new LinePart(lastResultEndIndex, tokenType);
}
if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
// This line decoration ends before this token ends
lastResultEndIndex = lineDecoration.endOffset + 1;
result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className);
lineDecorationIndex++;
}
else {
// This line decoration continues on to the next token
lastResultEndIndex = tokenEndIndex;
result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className);
break;
}
}
if (tokenEndIndex > lastResultEndIndex) {
lastResultEndIndex = tokenEndIndex;
result[resultLen++] = new LinePart(lastResultEndIndex, tokenType);
}
}
var lastTokenEndIndex = tokens[tokens.length - 1].endIndex;
if (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
var classNames = [];
while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
classNames.push(lineDecorations[lineDecorationIndex].className);
lineDecorationIndex++;
}
result[resultLen++] = new LinePart(lastResultEndIndex, classNames.join(' '));
}
return result;
}
/**
* This function is on purpose not split up into multiple functions to allow runtime type inference (i.e. performance reasons).
* Notice how all the needed data is fully resolved and passed in (i.e. no other calls).
*/
function _renderLine(input, sb) {
var fontIsMonospace = input.fontIsMonospace;
var canUseHalfwidthRightwardsArrow = input.canUseHalfwidthRightwardsArrow;
var containsForeignElements = input.containsForeignElements;
var lineContent = input.lineContent;
var len = input.len;
var isOverflowing = input.isOverflowing;
var parts = input.parts;
var fauxIndentLength = input.fauxIndentLength;
var tabSize = input.tabSize;
var startVisibleColumn = input.startVisibleColumn;
var containsRTL = input.containsRTL;
var spaceWidth = input.spaceWidth;
var middotWidth = input.middotWidth;
var renderWhitespace = input.renderWhitespace;
var renderControlCharacters = input.renderControlCharacters;
// use U+2E31 - WORD SEPARATOR MIDDLE DOT or U+00B7 - MIDDLE DOT
var spaceRenderWhitespaceCharacter = (middotWidth > spaceWidth ? 0x2E31 : 0xB7);
var characterMapping = new CharacterMapping(len + 1, parts.length);
var charIndex = 0;
var visibleColumn = startVisibleColumn;
var charOffsetInPart = 0;
var prevPartContentCnt = 0;
var partAbsoluteOffset = 0;
sb.appendASCIIString('');
for (var partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
partAbsoluteOffset += prevPartContentCnt;
var part = parts[partIndex];
var partEndIndex = part.endIndex;
var partType = part.type;
var partRendersWhitespace = (renderWhitespace !== 0 /* None */ && (partType.indexOf('vs-whitespace') >= 0));
charOffsetInPart = 0;
sb.appendASCIIString(' 1) {
sb.write1(0x2192); // RIGHTWARDS ARROW
}
else {
sb.write1(0xFFEB); // HALFWIDTH RIGHTWARDS ARROW
}
for (var space = 2; space <= charWidth; space++) {
sb.write1(0xA0); //
}
}
else { // must be CharCode.Space
charWidth = 1;
sb.write1(spaceRenderWhitespaceCharacter); // · or word separator middle dot
}
charOffsetInPart += charWidth;
if (charIndex >= fauxIndentLength) {
visibleColumn += charWidth;
}
}
prevPartContentCnt = partContentCnt;
}
else {
var partContentCnt = 0;
if (containsRTL) {
sb.appendASCIIString(' dir="ltr"');
}
sb.appendASCII(62 /* GreaterThan */);
for (; charIndex < partEndIndex; charIndex++) {
characterMapping.setPartData(charIndex, partIndex, charOffsetInPart, partAbsoluteOffset);
var charCode = lineContent.charCodeAt(charIndex);
var producedCharacters = 1;
var charWidth = 1;
switch (charCode) {
case 9 /* Tab */:
producedCharacters = (tabSize - (visibleColumn % tabSize));
charWidth = producedCharacters;
for (var space = 1; space <= producedCharacters; space++) {
sb.write1(0xA0); //
}
break;
case 32 /* Space */:
sb.write1(0xA0); //
break;
case 60 /* LessThan */:
sb.appendASCIIString('<');
break;
case 62 /* GreaterThan */:
sb.appendASCIIString('>');
break;
case 38 /* Ampersand */:
sb.appendASCIIString('&');
break;
case 0 /* Null */:
sb.appendASCIIString('');
break;
case 65279 /* UTF8_BOM */:
case 8232 /* LINE_SEPARATOR_2028 */:
sb.write1(0xFFFD);
break;
default:
if (strings.isFullWidthCharacter(charCode)) {
charWidth++;
}
if (renderControlCharacters && charCode < 32) {
sb.write1(9216 + charCode);
}
else {
sb.write1(charCode);
}
}
charOffsetInPart += producedCharacters;
partContentCnt += producedCharacters;
if (charIndex >= fauxIndentLength) {
visibleColumn += charWidth;
}
}
prevPartContentCnt = partContentCnt;
}
sb.appendASCIIString('');
}
// When getting client rects for the last character, we will position the
// text range at the end of the span, insteaf of at the beginning of next span
characterMapping.setPartData(len, parts.length - 1, charOffsetInPart, partAbsoluteOffset);
if (isOverflowing) {
sb.appendASCIIString('…');
}
sb.appendASCIIString('');
return new RenderLineOutput(characterMapping, containsRTL, containsForeignElements);
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[363/*vs/editor/common/viewLayout/viewLinesViewportData*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Contains all data needed to render at a specific viewport.
*/
var ViewportData = /** @class */ (function () {
function ViewportData(selections, partialData, whitespaceViewportData, model) {
this.selections = selections;
this.startLineNumber = partialData.startLineNumber | 0;
this.endLineNumber = partialData.endLineNumber | 0;
this.relativeVerticalOffset = partialData.relativeVerticalOffset;
this.bigNumbersDelta = partialData.bigNumbersDelta | 0;
this.whitespaceViewportData = whitespaceViewportData;
this._model = model;
this.visibleRange = new range_1.Range(partialData.startLineNumber, this._model.getLineMinColumn(partialData.startLineNumber), partialData.endLineNumber, this._model.getLineMaxColumn(partialData.endLineNumber));
}
ViewportData.prototype.getViewLineRenderingData = function (lineNumber) {
return this._model.getViewLineRenderingData(this.visibleRange, lineNumber);
};
ViewportData.prototype.getDecorationsInViewport = function () {
return this._model.getDecorationsInViewport(this.visibleRange);
};
return ViewportData;
}());
exports.ViewportData = ViewportData;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[194/*vs/editor/common/viewModel/prefixSumComputer*/], __M([0/*require*/,1/*exports*/,179/*vs/base/common/uint*/]), function (require, exports, uint_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PrefixSumIndexOfResult = /** @class */ (function () {
function PrefixSumIndexOfResult(index, remainder) {
this.index = index;
this.remainder = remainder;
}
return PrefixSumIndexOfResult;
}());
exports.PrefixSumIndexOfResult = PrefixSumIndexOfResult;
var PrefixSumComputer = /** @class */ (function () {
function PrefixSumComputer(values) {
this.values = values;
this.prefixSum = new Uint32Array(values.length);
this.prefixSumValidIndex = new Int32Array(1);
this.prefixSumValidIndex[0] = -1;
}
PrefixSumComputer.prototype.insertValues = function (insertIndex, insertValues) {
insertIndex = uint_1.toUint32(insertIndex);
var oldValues = this.values;
var oldPrefixSum = this.prefixSum;
var insertValuesLen = insertValues.length;
if (insertValuesLen === 0) {
return false;
}
this.values = new Uint32Array(oldValues.length + insertValuesLen);
this.values.set(oldValues.subarray(0, insertIndex), 0);
this.values.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen);
this.values.set(insertValues, insertIndex);
if (insertIndex - 1 < this.prefixSumValidIndex[0]) {
this.prefixSumValidIndex[0] = insertIndex - 1;
}
this.prefixSum = new Uint32Array(this.values.length);
if (this.prefixSumValidIndex[0] >= 0) {
this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
}
return true;
};
PrefixSumComputer.prototype.changeValue = function (index, value) {
index = uint_1.toUint32(index);
value = uint_1.toUint32(value);
if (this.values[index] === value) {
return false;
}
this.values[index] = value;
if (index - 1 < this.prefixSumValidIndex[0]) {
this.prefixSumValidIndex[0] = index - 1;
}
return true;
};
PrefixSumComputer.prototype.removeValues = function (startIndex, cnt) {
startIndex = uint_1.toUint32(startIndex);
cnt = uint_1.toUint32(cnt);
var oldValues = this.values;
var oldPrefixSum = this.prefixSum;
if (startIndex >= oldValues.length) {
return false;
}
var maxCnt = oldValues.length - startIndex;
if (cnt >= maxCnt) {
cnt = maxCnt;
}
if (cnt === 0) {
return false;
}
this.values = new Uint32Array(oldValues.length - cnt);
this.values.set(oldValues.subarray(0, startIndex), 0);
this.values.set(oldValues.subarray(startIndex + cnt), startIndex);
this.prefixSum = new Uint32Array(this.values.length);
if (startIndex - 1 < this.prefixSumValidIndex[0]) {
this.prefixSumValidIndex[0] = startIndex - 1;
}
if (this.prefixSumValidIndex[0] >= 0) {
this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
}
return true;
};
PrefixSumComputer.prototype.getTotalValue = function () {
if (this.values.length === 0) {
return 0;
}
return this._getAccumulatedValue(this.values.length - 1);
};
PrefixSumComputer.prototype.getAccumulatedValue = function (index) {
if (index < 0) {
return 0;
}
index = uint_1.toUint32(index);
return this._getAccumulatedValue(index);
};
PrefixSumComputer.prototype._getAccumulatedValue = function (index) {
if (index <= this.prefixSumValidIndex[0]) {
return this.prefixSum[index];
}
var startIndex = this.prefixSumValidIndex[0] + 1;
if (startIndex === 0) {
this.prefixSum[0] = this.values[0];
startIndex++;
}
if (index >= this.values.length) {
index = this.values.length - 1;
}
for (var i = startIndex; i <= index; i++) {
this.prefixSum[i] = this.prefixSum[i - 1] + this.values[i];
}
this.prefixSumValidIndex[0] = Math.max(this.prefixSumValidIndex[0], index);
return this.prefixSum[index];
};
PrefixSumComputer.prototype.getIndexOf = function (accumulatedValue) {
accumulatedValue = Math.floor(accumulatedValue); //@perf
// Compute all sums (to get a fully valid prefixSum)
this.getTotalValue();
var low = 0;
var high = this.values.length - 1;
var mid = 0;
var midStop = 0;
var midStart = 0;
while (low <= high) {
mid = low + ((high - low) / 2) | 0;
midStop = this.prefixSum[mid];
midStart = midStop - this.values[mid];
if (accumulatedValue < midStart) {
high = mid - 1;
}
else if (accumulatedValue >= midStop) {
low = mid + 1;
}
else {
break;
}
}
return new PrefixSumIndexOfResult(mid, accumulatedValue - midStart);
};
return PrefixSumComputer;
}());
exports.PrefixSumComputer = PrefixSumComputer;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[364/*vs/editor/common/model/mirrorTextModel*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,194/*vs/editor/common/viewModel/prefixSumComputer*/]), function (require, exports, position_1, prefixSumComputer_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MirrorTextModel = /** @class */ (function () {
function MirrorTextModel(uri, lines, eol, versionId) {
this._uri = uri;
this._lines = lines;
this._eol = eol;
this._versionId = versionId;
this._lineStarts = null;
}
MirrorTextModel.prototype.dispose = function () {
this._lines.length = 0;
};
MirrorTextModel.prototype.getText = function () {
return this._lines.join(this._eol);
};
MirrorTextModel.prototype.onEvents = function (e) {
if (e.eol && e.eol !== this._eol) {
this._eol = e.eol;
this._lineStarts = null;
}
// Update my lines
var changes = e.changes;
for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) {
var change = changes_1[_i];
this._acceptDeleteRange(change.range);
this._acceptInsertText(new position_1.Position(change.range.startLineNumber, change.range.startColumn), change.text);
}
this._versionId = e.versionId;
};
MirrorTextModel.prototype._ensureLineStarts = function () {
if (!this._lineStarts) {
var eolLength = this._eol.length;
var linesLength = this._lines.length;
var lineStartValues = new Uint32Array(linesLength);
for (var i = 0; i < linesLength; i++) {
lineStartValues[i] = this._lines[i].length + eolLength;
}
this._lineStarts = new prefixSumComputer_1.PrefixSumComputer(lineStartValues);
}
};
/**
* All changes to a line's text go through this method
*/
MirrorTextModel.prototype._setLineText = function (lineIndex, newValue) {
this._lines[lineIndex] = newValue;
if (this._lineStarts) {
// update prefix sum
this._lineStarts.changeValue(lineIndex, this._lines[lineIndex].length + this._eol.length);
}
};
MirrorTextModel.prototype._acceptDeleteRange = function (range) {
if (range.startLineNumber === range.endLineNumber) {
if (range.startColumn === range.endColumn) {
// Nothing to delete
return;
}
// Delete text on the affected line
this._setLineText(range.startLineNumber - 1, this._lines[range.startLineNumber - 1].substring(0, range.startColumn - 1)
+ this._lines[range.startLineNumber - 1].substring(range.endColumn - 1));
return;
}
// Take remaining text on last line and append it to remaining text on first line
this._setLineText(range.startLineNumber - 1, this._lines[range.startLineNumber - 1].substring(0, range.startColumn - 1)
+ this._lines[range.endLineNumber - 1].substring(range.endColumn - 1));
// Delete middle lines
this._lines.splice(range.startLineNumber, range.endLineNumber - range.startLineNumber);
if (this._lineStarts) {
// update prefix sum
this._lineStarts.removeValues(range.startLineNumber, range.endLineNumber - range.startLineNumber);
}
};
MirrorTextModel.prototype._acceptInsertText = function (position, insertText) {
if (insertText.length === 0) {
// Nothing to insert
return;
}
var insertLines = insertText.split(/\r\n|\r|\n/);
if (insertLines.length === 1) {
// Inserting text on one line
this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1)
+ insertLines[0]
+ this._lines[position.lineNumber - 1].substring(position.column - 1));
return;
}
// Append overflowing text from first line to the end of text to insert
insertLines[insertLines.length - 1] += this._lines[position.lineNumber - 1].substring(position.column - 1);
// Delete overflowing text from first line and insert text on first line
this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1)
+ insertLines[0]);
// Insert new lines & store lengths
var newLengths = new Uint32Array(insertLines.length - 1);
for (var i = 1; i < insertLines.length; i++) {
this._lines.splice(position.lineNumber + i - 1, 0, insertLines[i]);
newLengths[i - 1] = insertLines[i].length + this._eol.length;
}
if (this._lineStarts) {
// update prefix sum
this._lineStarts.insertValues(position.lineNumber, newLengths);
}
};
return MirrorTextModel;
}());
exports.MirrorTextModel = MirrorTextModel;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[365/*vs/editor/common/services/editorSimpleWorker*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,126/*vs/base/common/diff/diff*/,54/*vs/base/common/iterator*/,16/*vs/base/common/platform*/,25/*vs/base/common/uri*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,341/*vs/editor/common/diff/diffComputer*/,364/*vs/editor/common/model/mirrorTextModel*/,109/*vs/editor/common/model/wordHelper*/,351/*vs/editor/common/modes/linkComputer*/,354/*vs/editor/common/modes/supports/inplaceReplaceSupport*/,192/*vs/editor/common/standalone/standaloneBase*/,21/*vs/base/common/types*/]), function (require, exports, arrays_1, diff_1, iterator_1, platform_1, uri_1, position_1, range_1, diffComputer_1, mirrorTextModel_1, wordHelper_1, linkComputer_1, inplaceReplaceSupport_1, standaloneBase_1, types) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @internal
*/
var MirrorModel = /** @class */ (function (_super) {
__extends(MirrorModel, _super);
function MirrorModel() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(MirrorModel.prototype, "uri", {
get: function () {
return this._uri;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MirrorModel.prototype, "version", {
get: function () {
return this._versionId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MirrorModel.prototype, "eol", {
get: function () {
return this._eol;
},
enumerable: true,
configurable: true
});
MirrorModel.prototype.getValue = function () {
return this.getText();
};
MirrorModel.prototype.getLinesContent = function () {
return this._lines.slice(0);
};
MirrorModel.prototype.getLineCount = function () {
return this._lines.length;
};
MirrorModel.prototype.getLineContent = function (lineNumber) {
return this._lines[lineNumber - 1];
};
MirrorModel.prototype.getWordAtPosition = function (position, wordDefinition) {
var wordAtText = wordHelper_1.getWordAtText(position.column, wordHelper_1.ensureValidWordDefinition(wordDefinition), this._lines[position.lineNumber - 1], 0);
if (wordAtText) {
return new range_1.Range(position.lineNumber, wordAtText.startColumn, position.lineNumber, wordAtText.endColumn);
}
return null;
};
MirrorModel.prototype.createWordIterator = function (wordDefinition) {
var _this = this;
var obj;
var lineNumber = 0;
var lineText;
var wordRangesIdx = 0;
var wordRanges = [];
var next = function () {
if (wordRangesIdx < wordRanges.length) {
var value = lineText.substring(wordRanges[wordRangesIdx].start, wordRanges[wordRangesIdx].end);
wordRangesIdx += 1;
if (!obj) {
obj = { done: false, value: value };
}
else {
obj.value = value;
}
return obj;
}
else if (lineNumber >= _this._lines.length) {
return iterator_1.FIN;
}
else {
lineText = _this._lines[lineNumber];
wordRanges = _this._wordenize(lineText, wordDefinition);
wordRangesIdx = 0;
lineNumber += 1;
return next();
}
};
return { next: next };
};
MirrorModel.prototype.getLineWords = function (lineNumber, wordDefinition) {
var content = this._lines[lineNumber - 1];
var ranges = this._wordenize(content, wordDefinition);
var words = [];
for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) {
var range = ranges_1[_i];
words.push({
word: content.substring(range.start, range.end),
startColumn: range.start + 1,
endColumn: range.end + 1
});
}
return words;
};
MirrorModel.prototype._wordenize = function (content, wordDefinition) {
var result = [];
var match;
wordDefinition.lastIndex = 0; // reset lastIndex just to be sure
while (match = wordDefinition.exec(content)) {
if (match[0].length === 0) {
// it did match the empty string
break;
}
result.push({ start: match.index, end: match.index + match[0].length });
}
return result;
};
MirrorModel.prototype.getValueInRange = function (range) {
range = this._validateRange(range);
if (range.startLineNumber === range.endLineNumber) {
return this._lines[range.startLineNumber - 1].substring(range.startColumn - 1, range.endColumn - 1);
}
var lineEnding = this._eol;
var startLineIndex = range.startLineNumber - 1;
var endLineIndex = range.endLineNumber - 1;
var resultLines = [];
resultLines.push(this._lines[startLineIndex].substring(range.startColumn - 1));
for (var i = startLineIndex + 1; i < endLineIndex; i++) {
resultLines.push(this._lines[i]);
}
resultLines.push(this._lines[endLineIndex].substring(0, range.endColumn - 1));
return resultLines.join(lineEnding);
};
MirrorModel.prototype.offsetAt = function (position) {
position = this._validatePosition(position);
this._ensureLineStarts();
return this._lineStarts.getAccumulatedValue(position.lineNumber - 2) + (position.column - 1);
};
MirrorModel.prototype.positionAt = function (offset) {
offset = Math.floor(offset);
offset = Math.max(0, offset);
this._ensureLineStarts();
var out = this._lineStarts.getIndexOf(offset);
var lineLength = this._lines[out.index].length;
// Ensure we return a valid position
return {
lineNumber: 1 + out.index,
column: 1 + Math.min(out.remainder, lineLength)
};
};
MirrorModel.prototype._validateRange = function (range) {
var start = this._validatePosition({ lineNumber: range.startLineNumber, column: range.startColumn });
var end = this._validatePosition({ lineNumber: range.endLineNumber, column: range.endColumn });
if (start.lineNumber !== range.startLineNumber
|| start.column !== range.startColumn
|| end.lineNumber !== range.endLineNumber
|| end.column !== range.endColumn) {
return {
startLineNumber: start.lineNumber,
startColumn: start.column,
endLineNumber: end.lineNumber,
endColumn: end.column
};
}
return range;
};
MirrorModel.prototype._validatePosition = function (position) {
if (!position_1.Position.isIPosition(position)) {
throw new Error('bad position');
}
var lineNumber = position.lineNumber, column = position.column;
var hasChanged = false;
if (lineNumber < 1) {
lineNumber = 1;
column = 1;
hasChanged = true;
}
else if (lineNumber > this._lines.length) {
lineNumber = this._lines.length;
column = this._lines[lineNumber - 1].length + 1;
hasChanged = true;
}
else {
var maxCharacter = this._lines[lineNumber - 1].length + 1;
if (column < 1) {
column = 1;
hasChanged = true;
}
else if (column > maxCharacter) {
column = maxCharacter;
hasChanged = true;
}
}
if (!hasChanged) {
return position;
}
else {
return { lineNumber: lineNumber, column: column };
}
};
return MirrorModel;
}(mirrorTextModel_1.MirrorTextModel));
/**
* @internal
*/
var EditorSimpleWorker = /** @class */ (function () {
function EditorSimpleWorker(host, foreignModuleFactory) {
this._host = host;
this._models = Object.create(null);
this._foreignModuleFactory = foreignModuleFactory;
this._foreignModule = null;
}
EditorSimpleWorker.prototype.dispose = function () {
this._models = Object.create(null);
};
EditorSimpleWorker.prototype._getModel = function (uri) {
return this._models[uri];
};
EditorSimpleWorker.prototype._getModels = function () {
var _this = this;
var all = [];
Object.keys(this._models).forEach(function (key) { return all.push(_this._models[key]); });
return all;
};
EditorSimpleWorker.prototype.acceptNewModel = function (data) {
this._models[data.url] = new MirrorModel(uri_1.URI.parse(data.url), data.lines, data.EOL, data.versionId);
};
EditorSimpleWorker.prototype.acceptModelChanged = function (strURL, e) {
if (!this._models[strURL]) {
return;
}
var model = this._models[strURL];
model.onEvents(e);
};
EditorSimpleWorker.prototype.acceptRemovedModel = function (strURL) {
if (!this._models[strURL]) {
return;
}
delete this._models[strURL];
};
// ---- BEGIN diff --------------------------------------------------------------------------
EditorSimpleWorker.prototype.computeDiff = function (originalUrl, modifiedUrl, ignoreTrimWhitespace, maxComputationTime) {
return __awaiter(this, void 0, void 0, function () {
var original, modified, originalLines, modifiedLines, diffComputer, diffResult, identical;
return __generator(this, function (_a) {
original = this._getModel(originalUrl);
modified = this._getModel(modifiedUrl);
if (!original || !modified) {
return [2 /*return*/, null];
}
originalLines = original.getLinesContent();
modifiedLines = modified.getLinesContent();
diffComputer = new diffComputer_1.DiffComputer(originalLines, modifiedLines, {
shouldComputeCharChanges: true,
shouldPostProcessCharChanges: true,
shouldIgnoreTrimWhitespace: ignoreTrimWhitespace,
shouldMakePrettyDiff: true,
maxComputationTime: maxComputationTime
});
diffResult = diffComputer.computeDiff();
identical = (diffResult.changes.length > 0 ? false : this._modelsAreIdentical(original, modified));
return [2 /*return*/, {
quitEarly: diffResult.quitEarly,
identical: identical,
changes: diffResult.changes
}];
});
});
};
EditorSimpleWorker.prototype._modelsAreIdentical = function (original, modified) {
var originalLineCount = original.getLineCount();
var modifiedLineCount = modified.getLineCount();
if (originalLineCount !== modifiedLineCount) {
return false;
}
for (var line = 1; line <= originalLineCount; line++) {
var originalLine = original.getLineContent(line);
var modifiedLine = modified.getLineContent(line);
if (originalLine !== modifiedLine) {
return false;
}
}
return true;
};
EditorSimpleWorker.prototype.computeMoreMinimalEdits = function (modelUrl, edits) {
return __awaiter(this, void 0, void 0, function () {
var model, result, lastEol, _i, edits_1, _a, range, text, eol, original, changes, editOffset, _b, changes_1, change, start, end, newEdit;
return __generator(this, function (_c) {
model = this._getModel(modelUrl);
if (!model) {
return [2 /*return*/, edits];
}
result = [];
lastEol = undefined;
edits = arrays_1.mergeSort(edits, function (a, b) {
if (a.range && b.range) {
return range_1.Range.compareRangesUsingStarts(a.range, b.range);
}
// eol only changes should go to the end
var aRng = a.range ? 0 : 1;
var bRng = b.range ? 0 : 1;
return aRng - bRng;
});
for (_i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
_a = edits_1[_i], range = _a.range, text = _a.text, eol = _a.eol;
if (typeof eol === 'number') {
lastEol = eol;
}
if (range_1.Range.isEmpty(range) && !text) {
// empty change
continue;
}
original = model.getValueInRange(range);
text = text.replace(/\r\n|\n|\r/g, model.eol);
if (original === text) {
// noop
continue;
}
// make sure diff won't take too long
if (Math.max(text.length, original.length) > EditorSimpleWorker._diffLimit) {
result.push({ range: range, text: text });
continue;
}
changes = diff_1.stringDiff(original, text, false);
editOffset = model.offsetAt(range_1.Range.lift(range).getStartPosition());
for (_b = 0, changes_1 = changes; _b < changes_1.length; _b++) {
change = changes_1[_b];
start = model.positionAt(editOffset + change.originalStart);
end = model.positionAt(editOffset + change.originalStart + change.originalLength);
newEdit = {
text: text.substr(change.modifiedStart, change.modifiedLength),
range: { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column }
};
if (model.getValueInRange(newEdit.range) !== newEdit.text) {
result.push(newEdit);
}
}
}
if (typeof lastEol === 'number') {
result.push({ eol: lastEol, text: '', range: { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 } });
}
return [2 /*return*/, result];
});
});
};
// ---- END minimal edits ---------------------------------------------------------------
EditorSimpleWorker.prototype.computeLinks = function (modelUrl) {
return __awaiter(this, void 0, void 0, function () {
var model;
return __generator(this, function (_a) {
model = this._getModel(modelUrl);
if (!model) {
return [2 /*return*/, null];
}
return [2 /*return*/, linkComputer_1.computeLinks(model)];
});
});
};
EditorSimpleWorker.prototype.textualSuggest = function (modelUrl, position, wordDef, wordDefFlags) {
return __awaiter(this, void 0, void 0, function () {
var model, words, seen, wordDefRegExp, wordAt, iter, e, word;
return __generator(this, function (_a) {
model = this._getModel(modelUrl);
if (!model) {
return [2 /*return*/, null];
}
words = [];
seen = new Set();
wordDefRegExp = new RegExp(wordDef, wordDefFlags);
wordAt = model.getWordAtPosition(position, wordDefRegExp);
if (wordAt) {
seen.add(model.getValueInRange(wordAt));
}
for (iter = model.createWordIterator(wordDefRegExp), e = iter.next(); !e.done && seen.size <= EditorSimpleWorker._suggestionsLimit; e = iter.next()) {
word = e.value;
if (seen.has(word)) {
continue;
}
seen.add(word);
if (!isNaN(Number(word))) {
continue;
}
words.push(word);
}
return [2 /*return*/, words];
});
});
};
// ---- END suggest --------------------------------------------------------------------------
//#region -- word ranges --
EditorSimpleWorker.prototype.computeWordRanges = function (modelUrl, range, wordDef, wordDefFlags) {
return __awaiter(this, void 0, void 0, function () {
var model, wordDefRegExp, result, line, words, _i, words_1, word, array;
return __generator(this, function (_a) {
model = this._getModel(modelUrl);
if (!model) {
return [2 /*return*/, Object.create(null)];
}
wordDefRegExp = new RegExp(wordDef, wordDefFlags);
result = Object.create(null);
for (line = range.startLineNumber; line < range.endLineNumber; line++) {
words = model.getLineWords(line, wordDefRegExp);
for (_i = 0, words_1 = words; _i < words_1.length; _i++) {
word = words_1[_i];
if (!isNaN(Number(word.word))) {
continue;
}
array = result[word.word];
if (!array) {
array = [];
result[word.word] = array;
}
array.push({
startLineNumber: line,
startColumn: word.startColumn,
endLineNumber: line,
endColumn: word.endColumn
});
}
}
return [2 /*return*/, result];
});
});
};
//#endregion
EditorSimpleWorker.prototype.navigateValueSet = function (modelUrl, range, up, wordDef, wordDefFlags) {
return __awaiter(this, void 0, void 0, function () {
var model, wordDefRegExp, selectionText, wordRange, word, result;
return __generator(this, function (_a) {
model = this._getModel(modelUrl);
if (!model) {
return [2 /*return*/, null];
}
wordDefRegExp = new RegExp(wordDef, wordDefFlags);
if (range.startColumn === range.endColumn) {
range = {
startLineNumber: range.startLineNumber,
startColumn: range.startColumn,
endLineNumber: range.endLineNumber,
endColumn: range.endColumn + 1
};
}
selectionText = model.getValueInRange(range);
wordRange = model.getWordAtPosition({ lineNumber: range.startLineNumber, column: range.startColumn }, wordDefRegExp);
if (!wordRange) {
return [2 /*return*/, null];
}
word = model.getValueInRange(wordRange);
result = inplaceReplaceSupport_1.BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up);
return [2 /*return*/, result];
});
});
};
// ---- BEGIN foreign module support --------------------------------------------------------------------------
EditorSimpleWorker.prototype.loadForeignModule = function (moduleId, createData, foreignHostMethods) {
var _this = this;
var proxyMethodRequest = function (method, args) {
return _this._host.fhr(method, args);
};
var foreignHost = types.createProxyObject(foreignHostMethods, proxyMethodRequest);
var ctx = {
host: foreignHost,
getMirrorModels: function () {
return _this._getModels();
}
};
if (this._foreignModuleFactory) {
this._foreignModule = this._foreignModuleFactory(ctx, createData);
// static foreing module
return Promise.resolve(types.getAllMethodNames(this._foreignModule));
}
// ESM-comment-begin
return new Promise(function (resolve, reject) {
require([moduleId], function (foreignModule) {
_this._foreignModule = foreignModule.create(ctx, createData);
resolve(types.getAllMethodNames(_this._foreignModule));
}, reject);
});
// ESM-comment-end
// ESM-uncomment-begin
// return Promise.reject(new Error(`Unexpected usage`));
// ESM-uncomment-end
};
// foreign method request
EditorSimpleWorker.prototype.fmr = function (method, args) {
if (!this._foreignModule || typeof this._foreignModule[method] !== 'function') {
return Promise.reject(new Error('Missing requestHandler or method: ' + method));
}
try {
return Promise.resolve(this._foreignModule[method].apply(this._foreignModule, args));
}
catch (e) {
return Promise.reject(e);
}
};
// ---- END diff --------------------------------------------------------------------------
// ---- BEGIN minimal edits ---------------------------------------------------------------
EditorSimpleWorker._diffLimit = 100000;
// ---- BEGIN suggest --------------------------------------------------------------------------
EditorSimpleWorker._suggestionsLimit = 10000;
return EditorSimpleWorker;
}());
exports.EditorSimpleWorker = EditorSimpleWorker;
/**
* Called on the worker side
* @internal
*/
function create(host) {
return new EditorSimpleWorker(host, null);
}
exports.create = create;
if (typeof importScripts === 'function') {
// Running in a web worker
platform_1.globals.monaco = standaloneBase_1.createMonacoBaseAPI();
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[92/*vs/editor/common/viewModel/viewEventHandler*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ViewEventHandler = /** @class */ (function (_super) {
__extends(ViewEventHandler, _super);
function ViewEventHandler() {
var _this = _super.call(this) || this;
_this._shouldRender = true;
return _this;
}
ViewEventHandler.prototype.shouldRender = function () {
return this._shouldRender;
};
ViewEventHandler.prototype.forceShouldRender = function () {
this._shouldRender = true;
};
ViewEventHandler.prototype.setShouldRender = function () {
this._shouldRender = true;
};
ViewEventHandler.prototype.onDidRender = function () {
this._shouldRender = false;
};
// --- begin event handlers
ViewEventHandler.prototype.onConfigurationChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onContentSizeChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onCursorStateChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onDecorationsChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onFlushed = function (e) {
return false;
};
ViewEventHandler.prototype.onFocusChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onLanguageConfigurationChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onLineMappingChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onLinesChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onLinesDeleted = function (e) {
return false;
};
ViewEventHandler.prototype.onLinesInserted = function (e) {
return false;
};
ViewEventHandler.prototype.onRevealRangeRequest = function (e) {
return false;
};
ViewEventHandler.prototype.onScrollChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onThemeChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onTokensChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onTokensColorsChanged = function (e) {
return false;
};
ViewEventHandler.prototype.onZonesChanged = function (e) {
return false;
};
// --- end event handlers
ViewEventHandler.prototype.handleEvents = function (events) {
var shouldRender = false;
for (var i = 0, len = events.length; i < len; i++) {
var e = events[i];
switch (e.type) {
case 1 /* ViewConfigurationChanged */:
if (this.onConfigurationChanged(e)) {
shouldRender = true;
}
break;
case 2 /* ViewContentSizeChanged */:
if (this.onContentSizeChanged(e)) {
shouldRender = true;
}
break;
case 3 /* ViewCursorStateChanged */:
if (this.onCursorStateChanged(e)) {
shouldRender = true;
}
break;
case 4 /* ViewDecorationsChanged */:
if (this.onDecorationsChanged(e)) {
shouldRender = true;
}
break;
case 5 /* ViewFlushed */:
if (this.onFlushed(e)) {
shouldRender = true;
}
break;
case 6 /* ViewFocusChanged */:
if (this.onFocusChanged(e)) {
shouldRender = true;
}
break;
case 7 /* ViewLanguageConfigurationChanged */:
if (this.onLanguageConfigurationChanged(e)) {
shouldRender = true;
}
break;
case 8 /* ViewLineMappingChanged */:
if (this.onLineMappingChanged(e)) {
shouldRender = true;
}
break;
case 9 /* ViewLinesChanged */:
if (this.onLinesChanged(e)) {
shouldRender = true;
}
break;
case 10 /* ViewLinesDeleted */:
if (this.onLinesDeleted(e)) {
shouldRender = true;
}
break;
case 11 /* ViewLinesInserted */:
if (this.onLinesInserted(e)) {
shouldRender = true;
}
break;
case 12 /* ViewRevealRangeRequest */:
if (this.onRevealRangeRequest(e)) {
shouldRender = true;
}
break;
case 13 /* ViewScrollChanged */:
if (this.onScrollChanged(e)) {
shouldRender = true;
}
break;
case 15 /* ViewTokensChanged */:
if (this.onTokensChanged(e)) {
shouldRender = true;
}
break;
case 14 /* ViewThemeChanged */:
if (this.onThemeChanged(e)) {
shouldRender = true;
}
break;
case 16 /* ViewTokensColorsChanged */:
if (this.onTokensColorsChanged(e)) {
shouldRender = true;
}
break;
case 17 /* ViewZonesChanged */:
if (this.onZonesChanged(e)) {
shouldRender = true;
}
break;
default:
console.info('View received unknown event: ');
console.info(e);
}
}
if (shouldRender) {
this._shouldRender = true;
}
};
return ViewEventHandler;
}(lifecycle_1.Disposable));
exports.ViewEventHandler = ViewEventHandler;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[82/*vs/editor/browser/view/dynamicViewOverlay*/], __M([0/*require*/,1/*exports*/,92/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, viewEventHandler_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DynamicViewOverlay = /** @class */ (function (_super) {
__extends(DynamicViewOverlay, _super);
function DynamicViewOverlay() {
return _super !== null && _super.apply(this, arguments) || this;
}
return DynamicViewOverlay;
}(viewEventHandler_1.ViewEventHandler));
exports.DynamicViewOverlay = DynamicViewOverlay;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[37/*vs/editor/browser/view/viewPart*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,92/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, fastDomNode_1, viewEventHandler_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ViewPart = /** @class */ (function (_super) {
__extends(ViewPart, _super);
function ViewPart(context) {
var _this = _super.call(this) || this;
_this._context = context;
_this._context.addEventHandler(_this);
return _this;
}
ViewPart.prototype.dispose = function () {
this._context.removeEventHandler(this);
_super.prototype.dispose.call(this);
};
return ViewPart;
}(viewEventHandler_1.ViewEventHandler));
exports.ViewPart = ViewPart;
var PartFingerprints = /** @class */ (function () {
function PartFingerprints() {
}
PartFingerprints.write = function (target, partId) {
if (target instanceof fastDomNode_1.FastDomNode) {
target.setAttribute('data-mprt', String(partId));
}
else {
target.setAttribute('data-mprt', String(partId));
}
};
PartFingerprints.read = function (target) {
var r = target.getAttribute('data-mprt');
if (r === null) {
return 0 /* None */;
}
return parseInt(r, 10);
};
PartFingerprints.collect = function (child, stopAt) {
var result = [], resultLen = 0;
while (child && child !== document.body) {
if (child === stopAt) {
break;
}
if (child.nodeType === child.ELEMENT_NODE) {
result[resultLen++] = this.read(child);
}
child = child.parentElement;
}
var r = new Uint8Array(resultLen);
for (var i = 0; i < resultLen; i++) {
r[i] = result[resultLen - i - 1];
}
return r;
};
return PartFingerprints;
}());
exports.PartFingerprints = PartFingerprints;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[366/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,28/*vs/base/browser/fastDomNode*/,37/*vs/editor/browser/view/viewPart*/]), function (require, exports, dom, fastDomNode_1, viewPart_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Coordinate = /** @class */ (function () {
function Coordinate(top, left) {
this.top = top;
this.left = left;
}
return Coordinate;
}());
var ViewContentWidgets = /** @class */ (function (_super) {
__extends(ViewContentWidgets, _super);
function ViewContentWidgets(context, viewDomNode) {
var _this = _super.call(this, context) || this;
_this._viewDomNode = viewDomNode;
_this._widgets = {};
_this.domNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
viewPart_1.PartFingerprints.write(_this.domNode, 1 /* ContentWidgets */);
_this.domNode.setClassName('contentWidgets');
_this.domNode.setPosition('absolute');
_this.domNode.setTop(0);
_this.overflowingContentWidgetsDomNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
viewPart_1.PartFingerprints.write(_this.overflowingContentWidgetsDomNode, 2 /* OverflowingContentWidgets */);
_this.overflowingContentWidgetsDomNode.setClassName('overflowingContentWidgets');
return _this;
}
ViewContentWidgets.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this._widgets = {};
};
// --- begin event handlers
ViewContentWidgets.prototype.onConfigurationChanged = function (e) {
var keys = Object.keys(this._widgets);
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var widgetId = keys_1[_i];
this._widgets[widgetId].onConfigurationChanged(e);
}
return true;
};
ViewContentWidgets.prototype.onDecorationsChanged = function (e) {
// true for inline decorations that can end up relayouting text
return true;
};
ViewContentWidgets.prototype.onFlushed = function (e) {
return true;
};
ViewContentWidgets.prototype.onLineMappingChanged = function (e) {
var keys = Object.keys(this._widgets);
for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {
var widgetId = keys_2[_i];
this._widgets[widgetId].onLineMappingChanged(e);
}
return true;
};
ViewContentWidgets.prototype.onLinesChanged = function (e) {
return true;
};
ViewContentWidgets.prototype.onLinesDeleted = function (e) {
return true;
};
ViewContentWidgets.prototype.onLinesInserted = function (e) {
return true;
};
ViewContentWidgets.prototype.onScrollChanged = function (e) {
return true;
};
ViewContentWidgets.prototype.onZonesChanged = function (e) {
return true;
};
// ---- end view event handlers
ViewContentWidgets.prototype.addWidget = function (_widget) {
var myWidget = new Widget(this._context, this._viewDomNode, _widget);
this._widgets[myWidget.id] = myWidget;
if (myWidget.allowEditorOverflow) {
this.overflowingContentWidgetsDomNode.appendChild(myWidget.domNode);
}
else {
this.domNode.appendChild(myWidget.domNode);
}
this.setShouldRender();
};
ViewContentWidgets.prototype.setWidgetPosition = function (widget, range, preference) {
var myWidget = this._widgets[widget.getId()];
myWidget.setPosition(range, preference);
this.setShouldRender();
};
ViewContentWidgets.prototype.removeWidget = function (widget) {
var widgetId = widget.getId();
if (this._widgets.hasOwnProperty(widgetId)) {
var myWidget = this._widgets[widgetId];
delete this._widgets[widgetId];
var domNode = myWidget.domNode.domNode;
domNode.parentNode.removeChild(domNode);
domNode.removeAttribute('monaco-visible-content-widget');
this.setShouldRender();
}
};
ViewContentWidgets.prototype.shouldSuppressMouseDownOnWidget = function (widgetId) {
if (this._widgets.hasOwnProperty(widgetId)) {
return this._widgets[widgetId].suppressMouseDown;
}
return false;
};
ViewContentWidgets.prototype.onBeforeRender = function (viewportData) {
var keys = Object.keys(this._widgets);
for (var _i = 0, keys_3 = keys; _i < keys_3.length; _i++) {
var widgetId = keys_3[_i];
this._widgets[widgetId].onBeforeRender(viewportData);
}
};
ViewContentWidgets.prototype.prepareRender = function (ctx) {
var keys = Object.keys(this._widgets);
for (var _i = 0, keys_4 = keys; _i < keys_4.length; _i++) {
var widgetId = keys_4[_i];
this._widgets[widgetId].prepareRender(ctx);
}
};
ViewContentWidgets.prototype.render = function (ctx) {
var keys = Object.keys(this._widgets);
for (var _i = 0, keys_5 = keys; _i < keys_5.length; _i++) {
var widgetId = keys_5[_i];
this._widgets[widgetId].render(ctx);
}
};
return ViewContentWidgets;
}(viewPart_1.ViewPart));
exports.ViewContentWidgets = ViewContentWidgets;
var Widget = /** @class */ (function () {
function Widget(context, viewDomNode, actual) {
this._context = context;
this._viewDomNode = viewDomNode;
this._actual = actual;
this.domNode = fastDomNode_1.createFastDomNode(this._actual.getDomNode());
this.id = this._actual.getId();
this.allowEditorOverflow = this._actual.allowEditorOverflow || false;
this.suppressMouseDown = this._actual.suppressMouseDown || false;
var options = this._context.configuration.options;
var layoutInfo = options.get(107 /* layoutInfo */);
this._fixedOverflowWidgets = options.get(29 /* fixedOverflowWidgets */);
this._contentWidth = layoutInfo.contentWidth;
this._contentLeft = layoutInfo.contentLeft;
this._lineHeight = options.get(49 /* lineHeight */);
this._range = null;
this._viewRange = null;
this._preference = [];
this._cachedDomNodeClientWidth = -1;
this._cachedDomNodeClientHeight = -1;
this._maxWidth = this._getMaxWidth();
this._isVisible = false;
this._renderData = null;
this.domNode.setPosition((this._fixedOverflowWidgets && this.allowEditorOverflow) ? 'fixed' : 'absolute');
this.domNode.setVisibility('hidden');
this.domNode.setAttribute('widgetId', this.id);
this.domNode.setMaxWidth(this._maxWidth);
}
Widget.prototype.onConfigurationChanged = function (e) {
var options = this._context.configuration.options;
this._lineHeight = options.get(49 /* lineHeight */);
if (e.hasChanged(107 /* layoutInfo */)) {
var layoutInfo = options.get(107 /* layoutInfo */);
this._contentLeft = layoutInfo.contentLeft;
this._contentWidth = layoutInfo.contentWidth;
this._maxWidth = this._getMaxWidth();
}
};
Widget.prototype.onLineMappingChanged = function (e) {
this._setPosition(this._range);
};
Widget.prototype._setPosition = function (range) {
this._range = range;
this._viewRange = null;
if (this._range) {
// Do not trust that widgets give a valid position
var validModelRange = this._context.model.validateModelRange(this._range);
if (this._context.model.coordinatesConverter.modelPositionIsVisible(validModelRange.getStartPosition()) || this._context.model.coordinatesConverter.modelPositionIsVisible(validModelRange.getEndPosition())) {
this._viewRange = this._context.model.coordinatesConverter.convertModelRangeToViewRange(validModelRange);
}
}
};
Widget.prototype._getMaxWidth = function () {
return (this.allowEditorOverflow
? window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
: this._contentWidth);
};
Widget.prototype.setPosition = function (range, preference) {
this._setPosition(range);
this._preference = preference;
this._cachedDomNodeClientWidth = -1;
this._cachedDomNodeClientHeight = -1;
};
Widget.prototype._layoutBoxInViewport = function (topLeft, bottomLeft, width, height, ctx) {
// Our visible box is split horizontally by the current line => 2 boxes
// a) the box above the line
var aboveLineTop = topLeft.top;
var heightAboveLine = aboveLineTop;
// b) the box under the line
var underLineTop = bottomLeft.top + this._lineHeight;
var heightUnderLine = ctx.viewportHeight - underLineTop;
var aboveTop = aboveLineTop - height;
var fitsAbove = (heightAboveLine >= height);
var belowTop = underLineTop;
var fitsBelow = (heightUnderLine >= height);
// And its left
var actualAboveLeft = topLeft.left;
var actualBelowLeft = bottomLeft.left;
if (actualAboveLeft + width > ctx.scrollLeft + ctx.viewportWidth) {
actualAboveLeft = ctx.scrollLeft + ctx.viewportWidth - width;
}
if (actualBelowLeft + width > ctx.scrollLeft + ctx.viewportWidth) {
actualBelowLeft = ctx.scrollLeft + ctx.viewportWidth - width;
}
if (actualAboveLeft < ctx.scrollLeft) {
actualAboveLeft = ctx.scrollLeft;
}
if (actualBelowLeft < ctx.scrollLeft) {
actualBelowLeft = ctx.scrollLeft;
}
return {
fitsAbove: fitsAbove,
aboveTop: aboveTop,
aboveLeft: actualAboveLeft,
fitsBelow: fitsBelow,
belowTop: belowTop,
belowLeft: actualBelowLeft,
};
};
Widget.prototype._layoutHorizontalSegmentInPage = function (windowSize, domNodePosition, left, width) {
// Initially, the limits are defined as the dom node limits
var MIN_LIMIT = Math.max(0, domNodePosition.left - width);
var MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width, windowSize.width);
var absoluteLeft = domNodePosition.left + left - dom.StandardWindow.scrollX;
if (absoluteLeft + width > MAX_LIMIT) {
var delta = absoluteLeft - (MAX_LIMIT - width);
absoluteLeft -= delta;
left -= delta;
}
if (absoluteLeft < MIN_LIMIT) {
var delta = absoluteLeft - MIN_LIMIT;
absoluteLeft -= delta;
left -= delta;
}
return [left, absoluteLeft];
};
Widget.prototype._layoutBoxInPage = function (topLeft, bottomLeft, width, height, ctx) {
var aboveTop = topLeft.top - height;
var belowTop = bottomLeft.top + this._lineHeight;
var domNodePosition = dom.getDomNodePagePosition(this._viewDomNode.domNode);
var absoluteAboveTop = domNodePosition.top + aboveTop - dom.StandardWindow.scrollY;
var absoluteBelowTop = domNodePosition.top + belowTop - dom.StandardWindow.scrollY;
var windowSize = dom.getClientArea(document.body);
var _a = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, topLeft.left - ctx.scrollLeft + this._contentLeft, width), aboveLeft = _a[0], absoluteAboveLeft = _a[1];
var _b = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, bottomLeft.left - ctx.scrollLeft + this._contentLeft, width), belowLeft = _b[0], absoluteBelowLeft = _b[1];
// Leave some clearance to the top/bottom
var TOP_PADDING = 22;
var BOTTOM_PADDING = 22;
var fitsAbove = (absoluteAboveTop >= TOP_PADDING);
var fitsBelow = (absoluteBelowTop + height <= windowSize.height - BOTTOM_PADDING);
if (this._fixedOverflowWidgets) {
return {
fitsAbove: fitsAbove,
aboveTop: Math.max(absoluteAboveTop, TOP_PADDING),
aboveLeft: absoluteAboveLeft,
fitsBelow: fitsBelow,
belowTop: absoluteBelowTop,
belowLeft: absoluteBelowLeft
};
}
return {
fitsAbove: fitsAbove,
aboveTop: Math.max(aboveTop, TOP_PADDING),
aboveLeft: aboveLeft,
fitsBelow: fitsBelow,
belowTop: belowTop,
belowLeft: belowLeft
};
};
Widget.prototype._prepareRenderWidgetAtExactPositionOverflowing = function (topLeft) {
return new Coordinate(topLeft.top, topLeft.left + this._contentLeft);
};
/**
* Compute `this._topLeft`
*/
Widget.prototype._getTopAndBottomLeft = function (ctx) {
if (!this._viewRange) {
return [null, null];
}
var visibleRangesForRange = ctx.linesVisibleRangesForRange(this._viewRange, false);
if (!visibleRangesForRange || visibleRangesForRange.length === 0) {
return [null, null];
}
var firstLine = visibleRangesForRange[0];
var lastLine = visibleRangesForRange[0];
for (var _i = 0, visibleRangesForRange_1 = visibleRangesForRange; _i < visibleRangesForRange_1.length; _i++) {
var visibleRangesForLine = visibleRangesForRange_1[_i];
if (visibleRangesForLine.lineNumber < firstLine.lineNumber) {
firstLine = visibleRangesForLine;
}
if (visibleRangesForLine.lineNumber > lastLine.lineNumber) {
lastLine = visibleRangesForLine;
}
}
var firstLineMinLeft = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; //firstLine.Constants.MAX_SAFE_SMALL_INTEGER;
for (var _a = 0, _b = firstLine.ranges; _a < _b.length; _a++) {
var visibleRange = _b[_a];
if (visibleRange.left < firstLineMinLeft) {
firstLineMinLeft = visibleRange.left;
}
}
var lastLineMinLeft = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; //lastLine.Constants.MAX_SAFE_SMALL_INTEGER;
for (var _c = 0, _d = lastLine.ranges; _c < _d.length; _c++) {
var visibleRange = _d[_c];
if (visibleRange.left < lastLineMinLeft) {
lastLineMinLeft = visibleRange.left;
}
}
var topForPosition = ctx.getVerticalOffsetForLineNumber(firstLine.lineNumber) - ctx.scrollTop;
var topLeft = new Coordinate(topForPosition, firstLineMinLeft);
var topForBottomLine = ctx.getVerticalOffsetForLineNumber(lastLine.lineNumber) - ctx.scrollTop;
var bottomLeft = new Coordinate(topForBottomLine, lastLineMinLeft);
return [topLeft, bottomLeft];
};
Widget.prototype._prepareRenderWidget = function (ctx) {
var _a = this._getTopAndBottomLeft(ctx), topLeft = _a[0], bottomLeft = _a[1];
if (!topLeft || !bottomLeft) {
return null;
}
if (this._cachedDomNodeClientWidth === -1 || this._cachedDomNodeClientHeight === -1) {
var domNode = this.domNode.domNode;
this._cachedDomNodeClientWidth = domNode.clientWidth;
this._cachedDomNodeClientHeight = domNode.clientHeight;
}
var placement;
if (this.allowEditorOverflow) {
placement = this._layoutBoxInPage(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx);
}
else {
placement = this._layoutBoxInViewport(topLeft, bottomLeft, this._cachedDomNodeClientWidth, this._cachedDomNodeClientHeight, ctx);
}
// Do two passes, first for perfect fit, second picks first option
if (this._preference) {
for (var pass = 1; pass <= 2; pass++) {
for (var _i = 0, _b = this._preference; _i < _b.length; _i++) {
var pref = _b[_i];
// placement
if (pref === 1 /* ABOVE */) {
if (!placement) {
// Widget outside of viewport
return null;
}
if (pass === 2 || placement.fitsAbove) {
return new Coordinate(placement.aboveTop, placement.aboveLeft);
}
}
else if (pref === 2 /* BELOW */) {
if (!placement) {
// Widget outside of viewport
return null;
}
if (pass === 2 || placement.fitsBelow) {
return new Coordinate(placement.belowTop, placement.belowLeft);
}
}
else {
if (this.allowEditorOverflow) {
return this._prepareRenderWidgetAtExactPositionOverflowing(topLeft);
}
else {
return topLeft;
}
}
}
}
}
return null;
};
/**
* On this first pass, we ensure that the content widget (if it is in the viewport) has the max width set correctly.
*/
Widget.prototype.onBeforeRender = function (viewportData) {
if (!this._viewRange || !this._preference) {
return;
}
if (this._viewRange.endLineNumber < viewportData.startLineNumber || this._viewRange.startLineNumber > viewportData.endLineNumber) {
// Outside of viewport
return;
}
this.domNode.setMaxWidth(this._maxWidth);
};
Widget.prototype.prepareRender = function (ctx) {
this._renderData = this._prepareRenderWidget(ctx);
};
Widget.prototype.render = function (ctx) {
if (!this._renderData) {
// This widget should be invisible
if (this._isVisible) {
this.domNode.removeAttribute('monaco-visible-content-widget');
this._isVisible = false;
this.domNode.setVisibility('hidden');
}
return;
}
// This widget should be visible
if (this.allowEditorOverflow) {
this.domNode.setTop(this._renderData.top);
this.domNode.setLeft(this._renderData.left);
}
else {
this.domNode.setTop(this._renderData.top + ctx.scrollTop - ctx.bigNumbersDelta);
this.domNode.setLeft(this._renderData.left);
}
if (!this._isVisible) {
this.domNode.setVisibility('inherit');
this.domNode.setAttribute('monaco-visible-content-widget', 'true');
this._isVisible = true;
}
};
return Widget;
}());
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[367/*vs/editor/browser/viewParts/decorations/decorations*/], __M([0/*require*/,1/*exports*/,82/*vs/editor/browser/view/dynamicViewOverlay*/,3/*vs/editor/common/core/range*/,91/*vs/editor/common/view/renderingContext*/,286/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/]), function (require, exports, dynamicViewOverlay_1, range_1, renderingContext_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DecorationsOverlay = /** @class */ (function (_super) {
__extends(DecorationsOverlay, _super);
function DecorationsOverlay(context) {
var _this = _super.call(this) || this;
_this._context = context;
var options = _this._context.configuration.options;
_this._lineHeight = options.get(49 /* lineHeight */);
_this._typicalHalfwidthCharacterWidth = options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth;
_this._renderResult = null;
_this._context.addEventHandler(_this);
return _this;
}
DecorationsOverlay.prototype.dispose = function () {
this._context.removeEventHandler(this);
this._renderResult = null;
_super.prototype.dispose.call(this);
};
// --- begin event handlers
DecorationsOverlay.prototype.onConfigurationChanged = function (e) {
var options = this._context.configuration.options;
this._lineHeight = options.get(49 /* lineHeight */);
this._typicalHalfwidthCharacterWidth = options.get(34 /* fontInfo */).typicalHalfwidthCharacterWidth;
return true;
};
DecorationsOverlay.prototype.onDecorationsChanged = function (e) {
return true;
};
DecorationsOverlay.prototype.onFlushed = function (e) {
return true;
};
DecorationsOverlay.prototype.onLinesChanged = function (e) {
return true;
};
DecorationsOverlay.prototype.onLinesDeleted = function (e) {
return true;
};
DecorationsOverlay.prototype.onLinesInserted = function (e) {
return true;
};
DecorationsOverlay.prototype.onScrollChanged = function (e) {
return e.scrollTopChanged || e.scrollWidthChanged;
};
DecorationsOverlay.prototype.onZonesChanged = function (e) {
return true;
};
// --- end event handlers
DecorationsOverlay.prototype.prepareRender = function (ctx) {
var _decorations = ctx.getDecorationsInViewport();
// Keep only decorations with `className`
var decorations = [], decorationsLen = 0;
for (var i = 0, len = _decorations.length; i < len; i++) {
var d = _decorations[i];
if (d.options.className) {
decorations[decorationsLen++] = d;
}
}
// Sort decorations for consistent render output
decorations = decorations.sort(function (a, b) {
if (a.options.zIndex < b.options.zIndex) {
return -1;
}
if (a.options.zIndex > b.options.zIndex) {
return 1;
}
var aClassName = a.options.className;
var bClassName = b.options.className;
if (aClassName < bClassName) {
return -1;
}
if (aClassName > bClassName) {
return 1;
}
return range_1.Range.compareRangesUsingStarts(a.range, b.range);
});
var visibleStartLineNumber = ctx.visibleRange.startLineNumber;
var visibleEndLineNumber = ctx.visibleRange.endLineNumber;
var output = [];
for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
var lineIndex = lineNumber - visibleStartLineNumber;
output[lineIndex] = '';
}
// Render first whole line decorations and then regular decorations
this._renderWholeLineDecorations(ctx, decorations, output);
this._renderNormalDecorations(ctx, decorations, output);
this._renderResult = output;
};
DecorationsOverlay.prototype._renderWholeLineDecorations = function (ctx, decorations, output) {
var lineHeight = String(this._lineHeight);
var visibleStartLineNumber = ctx.visibleRange.startLineNumber;
var visibleEndLineNumber = ctx.visibleRange.endLineNumber;
for (var i = 0, lenI = decorations.length; i < lenI; i++) {
var d = decorations[i];
if (!d.options.isWholeLine) {
continue;
}
var decorationOutput = ('');
var startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
var endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
for (var j = startLineNumber; j <= endLineNumber; j++) {
var lineIndex = j - visibleStartLineNumber;
output[lineIndex] += decorationOutput;
}
}
};
DecorationsOverlay.prototype._renderNormalDecorations = function (ctx, decorations, output) {
var lineHeight = String(this._lineHeight);
var visibleStartLineNumber = ctx.visibleRange.startLineNumber;
var prevClassName = null;
var prevShowIfCollapsed = false;
var prevRange = null;
for (var i = 0, lenI = decorations.length; i < lenI; i++) {
var d = decorations[i];
if (d.options.isWholeLine) {
continue;
}
var className = d.options.className;
var showIfCollapsed = Boolean(d.options.showIfCollapsed);
var range = d.range;
if (showIfCollapsed && range.endColumn === 1 && range.endLineNumber !== range.startLineNumber) {
range = new range_1.Range(range.startLineNumber, range.startColumn, range.endLineNumber - 1, this._context.model.getLineMaxColumn(range.endLineNumber - 1));
}
if (prevClassName === className && prevShowIfCollapsed === showIfCollapsed && range_1.Range.areIntersectingOrTouching(prevRange, range)) {
// merge into previous decoration
prevRange = range_1.Range.plusRange(prevRange, range);
continue;
}
// flush previous decoration
if (prevClassName !== null) {
this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
}
prevClassName = className;
prevShowIfCollapsed = showIfCollapsed;
prevRange = range;
}
if (prevClassName !== null) {
this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
}
};
DecorationsOverlay.prototype._renderNormalDecoration = function (ctx, range, className, showIfCollapsed, lineHeight, visibleStartLineNumber, output) {
var linesVisibleRanges = ctx.linesVisibleRangesForRange(range, /*TODO@Alex*/ className === 'findMatch');
if (!linesVisibleRanges) {
return;
}
for (var j = 0, lenJ = linesVisibleRanges.length; j < lenJ; j++) {
var lineVisibleRanges = linesVisibleRanges[j];
if (lineVisibleRanges.outsideRenderedLine) {
continue;
}
var lineIndex = lineVisibleRanges.lineNumber - visibleStartLineNumber;
if (showIfCollapsed && lineVisibleRanges.ranges.length === 1) {
var singleVisibleRange = lineVisibleRanges.ranges[0];
if (singleVisibleRange.width === 0) {
// collapsed range case => make the decoration visible by faking its width
lineVisibleRanges.ranges[0] = new renderingContext_1.HorizontalRange(singleVisibleRange.left, this._typicalHalfwidthCharacterWidth);
}
}
for (var k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) {
var visibleRange = lineVisibleRanges.ranges[k];
var decorationOutput = ('');
output[lineIndex] += decorationOutput;
}
}
};
DecorationsOverlay.prototype.render = function (startLineNumber, lineNumber) {
if (!this._renderResult) {
return '';
}
var lineIndex = lineNumber - startLineNumber;
if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
return '';
}
return this._renderResult[lineIndex];
};
return DecorationsOverlay;
}(dynamicViewOverlay_1.DynamicViewOverlay));
exports.DecorationsOverlay = DecorationsOverlay;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[149/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([0/*require*/,1/*exports*/,82/*vs/editor/browser/view/dynamicViewOverlay*/,287/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/]), function (require, exports, dynamicViewOverlay_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DecorationToRender = /** @class */ (function () {
function DecorationToRender(startLineNumber, endLineNumber, className) {
this.startLineNumber = +startLineNumber;
this.endLineNumber = +endLineNumber;
this.className = String(className);
}
return DecorationToRender;
}());
exports.DecorationToRender = DecorationToRender;
var DedupOverlay = /** @class */ (function (_super) {
__extends(DedupOverlay, _super);
function DedupOverlay() {
return _super !== null && _super.apply(this, arguments) || this;
}
DedupOverlay.prototype._render = function (visibleStartLineNumber, visibleEndLineNumber, decorations) {
var output = [];
for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
var lineIndex = lineNumber - visibleStartLineNumber;
output[lineIndex] = [];
}
if (decorations.length === 0) {
return output;
}
decorations.sort(function (a, b) {
if (a.className === b.className) {
if (a.startLineNumber === b.startLineNumber) {
return a.endLineNumber - b.endLineNumber;
}
return a.startLineNumber - b.startLineNumber;
}
return (a.className < b.className ? -1 : 1);
});
var prevClassName = null;
var prevEndLineIndex = 0;
for (var i = 0, len = decorations.length; i < len; i++) {
var d = decorations[i];
var className = d.className;
var startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber;
var endLineIndex = Math.min(d.endLineNumber, visibleEndLineNumber) - visibleStartLineNumber;
if (prevClassName === className) {
startLineIndex = Math.max(prevEndLineIndex + 1, startLineIndex);
prevEndLineIndex = Math.max(prevEndLineIndex, endLineIndex);
}
else {
prevClassName = className;
prevEndLineIndex = endLineIndex;
}
for (var i_1 = startLineIndex; i_1 <= prevEndLineIndex; i_1++) {
output[i_1].push(prevClassName);
}
}
return output;
};
return DedupOverlay;
}(dynamicViewOverlay_1.DynamicViewOverlay));
exports.DedupOverlay = DedupOverlay;
var GlyphMarginOverlay = /** @class */ (function (_super) {
__extends(GlyphMarginOverlay, _super);
function GlyphMarginOverlay(context) {
var _this = _super.call(this) || this;
_this._context = context;
var options = _this._context.configuration.options;
var layoutInfo = options.get(107 /* layoutInfo */);
_this._lineHeight = options.get(49 /* lineHeight */);
_this._glyphMargin = options.get(40 /* glyphMargin */);
_this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
_this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
_this._renderResult = null;
_this._context.addEventHandler(_this);
return _this;
}
GlyphMarginOverlay.prototype.dispose = function () {
this._context.removeEventHandler(this);
this._renderResult = null;
_super.prototype.dispose.call(this);
};
// --- begin event handlers
GlyphMarginOverlay.prototype.onConfigurationChanged = function (e) {
var options = this._context.configuration.options;
var layoutInfo = options.get(107 /* layoutInfo */);
this._lineHeight = options.get(49 /* lineHeight */);
this._glyphMargin = options.get(40 /* glyphMargin */);
this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
return true;
};
GlyphMarginOverlay.prototype.onDecorationsChanged = function (e) {
return true;
};
GlyphMarginOverlay.prototype.onFlushed = function (e) {
return true;
};
GlyphMarginOverlay.prototype.onLinesChanged = function (e) {
return true;
};
GlyphMarginOverlay.prototype.onLinesDeleted = function (e) {
return true;
};
GlyphMarginOverlay.prototype.onLinesInserted = function (e) {
return true;
};
GlyphMarginOverlay.prototype.onScrollChanged = function (e) {
return e.scrollTopChanged;
};
GlyphMarginOverlay.prototype.onZonesChanged = function (e) {
return true;
};
// --- end event handlers
GlyphMarginOverlay.prototype._getDecorations = function (ctx) {
var decorations = ctx.getDecorationsInViewport();
var r = [], rLen = 0;
for (var i = 0, len = decorations.length; i < len; i++) {
var d = decorations[i];
var glyphMarginClassName = d.options.glyphMarginClassName;
if (glyphMarginClassName) {
r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, glyphMarginClassName);
}
}
return r;
};
GlyphMarginOverlay.prototype.prepareRender = function (ctx) {
if (!this._glyphMargin) {
this._renderResult = null;
return;
}
var visibleStartLineNumber = ctx.visibleRange.startLineNumber;
var visibleEndLineNumber = ctx.visibleRange.endLineNumber;
var toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
var lineHeight = this._lineHeight.toString();
var left = this._glyphMarginLeft.toString();
var width = this._glyphMarginWidth.toString();
var common = '" style="left:' + left + 'px;width:' + width + 'px' + ';height:' + lineHeight + 'px;">';
var output = [];
for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
var lineIndex = lineNumber - visibleStartLineNumber;
var classNames = toRender[lineIndex];
if (classNames.length === 0) {
output[lineIndex] = '';
}
else {
output[lineIndex] = ('';
var output = [];
for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
var lineIndex = lineNumber - visibleStartLineNumber;
var classNames = toRender[lineIndex];
var lineOutput = '';
for (var i = 0, len = classNames.length; i < len; i++) {
lineOutput += '';
}
output[lineIndex] = lineOutput;
}
this._renderResult = output;
};
MarginViewLineDecorationsOverlay.prototype.render = function (startLineNumber, lineNumber) {
if (!this._renderResult) {
return '';
}
return this._renderResult[lineNumber - startLineNumber];
};
return MarginViewLineDecorationsOverlay;
}(glyphMargin_1.DedupOverlay));
exports.MarginViewLineDecorationsOverlay = MarginViewLineDecorationsOverlay;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[370/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,37/*vs/editor/browser/view/viewPart*/,294/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/]), function (require, exports, fastDomNode_1, viewPart_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ViewOverlayWidgets = /** @class */ (function (_super) {
__extends(ViewOverlayWidgets, _super);
function ViewOverlayWidgets(context) {
var _this = _super.call(this, context) || this;
var options = _this._context.configuration.options;
var layoutInfo = options.get(107 /* layoutInfo */);
_this._widgets = {};
_this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
_this._minimapWidth = layoutInfo.minimapWidth;
_this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
_this._editorHeight = layoutInfo.height;
_this._editorWidth = layoutInfo.width;
_this._domNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
viewPart_1.PartFingerprints.write(_this._domNode, 4 /* OverlayWidgets */);
_this._domNode.setClassName('overlayWidgets');
return _this;
}
ViewOverlayWidgets.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this._widgets = {};
};
ViewOverlayWidgets.prototype.getDomNode = function () {
return this._domNode;
};
// ---- begin view event handlers
ViewOverlayWidgets.prototype.onConfigurationChanged = function (e) {
var options = this._context.configuration.options;
var layoutInfo = options.get(107 /* layoutInfo */);
this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
this._minimapWidth = layoutInfo.minimapWidth;
this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
this._editorHeight = layoutInfo.height;
this._editorWidth = layoutInfo.width;
return true;
};
// ---- end view event handlers
ViewOverlayWidgets.prototype.addWidget = function (widget) {
var domNode = fastDomNode_1.createFastDomNode(widget.getDomNode());
this._widgets[widget.getId()] = {
widget: widget,
preference: null,
domNode: domNode
};
// This is sync because a widget wants to be in the dom
domNode.setPosition('absolute');
domNode.setAttribute('widgetId', widget.getId());
this._domNode.appendChild(domNode);
this.setShouldRender();
};
ViewOverlayWidgets.prototype.setWidgetPosition = function (widget, preference) {
var widgetData = this._widgets[widget.getId()];
if (widgetData.preference === preference) {
return false;
}
widgetData.preference = preference;
this.setShouldRender();
return true;
};
ViewOverlayWidgets.prototype.removeWidget = function (widget) {
var widgetId = widget.getId();
if (this._widgets.hasOwnProperty(widgetId)) {
var widgetData = this._widgets[widgetId];
var domNode = widgetData.domNode.domNode;
delete this._widgets[widgetId];
domNode.parentNode.removeChild(domNode);
this.setShouldRender();
}
};
ViewOverlayWidgets.prototype._renderWidget = function (widgetData) {
var domNode = widgetData.domNode;
if (widgetData.preference === null) {
domNode.unsetTop();
return;
}
if (widgetData.preference === 0 /* TOP_RIGHT_CORNER */) {
domNode.setTop(0);
domNode.setRight((2 * this._verticalScrollbarWidth) + this._minimapWidth);
}
else if (widgetData.preference === 1 /* BOTTOM_RIGHT_CORNER */) {
var widgetHeight = domNode.domNode.clientHeight;
domNode.setTop((this._editorHeight - widgetHeight - 2 * this._horizontalScrollbarHeight));
domNode.setRight((2 * this._verticalScrollbarWidth) + this._minimapWidth);
}
else if (widgetData.preference === 2 /* TOP_CENTER */) {
domNode.setTop(0);
domNode.domNode.style.right = '50%';
}
};
ViewOverlayWidgets.prototype.prepareRender = function (ctx) {
// Nothing to read
};
ViewOverlayWidgets.prototype.render = function (ctx) {
this._domNode.setWidth(this._editorWidth);
var keys = Object.keys(this._widgets);
for (var i = 0, len = keys.length; i < len; i++) {
var widgetId = keys[i];
this._renderWidget(this._widgets[widgetId]);
}
};
return ViewOverlayWidgets;
}(viewPart_1.ViewPart));
exports.ViewOverlayWidgets = ViewOverlayWidgets;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[371/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,193/*vs/editor/common/view/overviewZoneManager*/,92/*vs/editor/common/viewModel/viewEventHandler*/]), function (require, exports, fastDomNode_1, overviewZoneManager_1, viewEventHandler_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var OverviewRuler = /** @class */ (function (_super) {
__extends(OverviewRuler, _super);
function OverviewRuler(context, cssClassName) {
var _this = _super.call(this) || this;
_this._context = context;
var options = _this._context.configuration.options;
_this._domNode = fastDomNode_1.createFastDomNode(document.createElement('canvas'));
_this._domNode.setClassName(cssClassName);
_this._domNode.setPosition('absolute');
_this._domNode.setLayerHinting(true);
_this._domNode.setContain('strict');
_this._zoneManager = new overviewZoneManager_1.OverviewZoneManager(function (lineNumber) { return _this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber); });
_this._zoneManager.setDOMWidth(0);
_this._zoneManager.setDOMHeight(0);
_this._zoneManager.setOuterHeight(_this._context.viewLayout.getScrollHeight());
_this._zoneManager.setLineHeight(options.get(49 /* lineHeight */));
_this._zoneManager.setPixelRatio(options.get(105 /* pixelRatio */));
_this._context.addEventHandler(_this);
return _this;
}
OverviewRuler.prototype.dispose = function () {
this._context.removeEventHandler(this);
_super.prototype.dispose.call(this);
};
// ---- begin view event handlers
OverviewRuler.prototype.onConfigurationChanged = function (e) {
var options = this._context.configuration.options;
if (e.hasChanged(49 /* lineHeight */)) {
this._zoneManager.setLineHeight(options.get(49 /* lineHeight */));
this._render();
}
if (e.hasChanged(105 /* pixelRatio */)) {
this._zoneManager.setPixelRatio(options.get(105 /* pixelRatio */));
this._domNode.setWidth(this._zoneManager.getDOMWidth());
this._domNode.setHeight(this._zoneManager.getDOMHeight());
this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
this._render();
}
return true;
};
OverviewRuler.prototype.onFlushed = function (e) {
this._render();
return true;
};
OverviewRuler.prototype.onScrollChanged = function (e) {
if (e.scrollHeightChanged) {
this._zoneManager.setOuterHeight(e.scrollHeight);
this._render();
}
return true;
};
OverviewRuler.prototype.onZonesChanged = function (e) {
this._render();
return true;
};
// ---- end view event handlers
OverviewRuler.prototype.getDomNode = function () {
return this._domNode.domNode;
};
OverviewRuler.prototype.setLayout = function (position) {
this._domNode.setTop(position.top);
this._domNode.setRight(position.right);
var hasChanged = false;
hasChanged = this._zoneManager.setDOMWidth(position.width) || hasChanged;
hasChanged = this._zoneManager.setDOMHeight(position.height) || hasChanged;
if (hasChanged) {
this._domNode.setWidth(this._zoneManager.getDOMWidth());
this._domNode.setHeight(this._zoneManager.getDOMHeight());
this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
this._render();
}
};
OverviewRuler.prototype.setZones = function (zones) {
this._zoneManager.setZones(zones);
this._render();
};
OverviewRuler.prototype._render = function () {
if (this._zoneManager.getOuterHeight() === 0) {
return false;
}
var width = this._zoneManager.getCanvasWidth();
var height = this._zoneManager.getCanvasHeight();
var colorZones = this._zoneManager.resolveColorZones();
var id2Color = this._zoneManager.getId2Color();
var ctx = this._domNode.domNode.getContext('2d');
ctx.clearRect(0, 0, width, height);
if (colorZones.length > 0) {
this._renderOneLane(ctx, colorZones, id2Color, width);
}
return true;
};
OverviewRuler.prototype._renderOneLane = function (ctx, colorZones, id2Color, width) {
var currentColorId = 0;
var currentFrom = 0;
var currentTo = 0;
for (var _i = 0, colorZones_1 = colorZones; _i < colorZones_1.length; _i++) {
var zone = colorZones_1[_i];
var zoneColorId = zone.colorId;
var zoneFrom = zone.from;
var zoneTo = zone.to;
if (zoneColorId !== currentColorId) {
ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
currentColorId = zoneColorId;
ctx.fillStyle = id2Color[currentColorId];
currentFrom = zoneFrom;
currentTo = zoneTo;
}
else {
if (currentTo >= zoneFrom) {
currentTo = Math.max(currentTo, zoneTo);
}
else {
ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
currentFrom = zoneFrom;
currentTo = zoneTo;
}
}
}
ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
};
return OverviewRuler;
}(viewEventHandler_1.ViewEventHandler));
exports.OverviewRuler = OverviewRuler;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[372/*vs/editor/browser/viewParts/viewZones/viewZones*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,10/*vs/base/common/errors*/,37/*vs/editor/browser/view/viewPart*/,13/*vs/editor/common/core/position*/]), function (require, exports, fastDomNode_1, errors_1, viewPart_1, position_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var invalidFunc = function () { throw new Error("Invalid change accessor"); };
var ViewZones = /** @class */ (function (_super) {
__extends(ViewZones, _super);
function ViewZones(context) {
var _this = _super.call(this, context) || this;
var options = _this._context.configuration.options;
var layoutInfo = options.get(107 /* layoutInfo */);
_this._lineHeight = options.get(49 /* lineHeight */);
_this._contentWidth = layoutInfo.contentWidth;
_this._contentLeft = layoutInfo.contentLeft;
_this.domNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
_this.domNode.setClassName('view-zones');
_this.domNode.setPosition('absolute');
_this.domNode.setAttribute('role', 'presentation');
_this.domNode.setAttribute('aria-hidden', 'true');
_this.marginDomNode = fastDomNode_1.createFastDomNode(document.createElement('div'));
_this.marginDomNode.setClassName('margin-view-zones');
_this.marginDomNode.setPosition('absolute');
_this.marginDomNode.setAttribute('role', 'presentation');
_this.marginDomNode.setAttribute('aria-hidden', 'true');
_this._zones = {};
return _this;
}
ViewZones.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this._zones = {};
};
// ---- begin view event handlers
ViewZones.prototype._recomputeWhitespacesProps = function () {
var _this = this;
var whitespaces = this._context.viewLayout.getWhitespaces();
var oldWhitespaces = new Map();
for (var _i = 0, whitespaces_1 = whitespaces; _i < whitespaces_1.length; _i++) {
var whitespace = whitespaces_1[_i];
oldWhitespaces.set(whitespace.id, whitespace);
}
return this._context.viewLayout.changeWhitespace(function (whitespaceAccessor) {
var hadAChange = false;
var keys = Object.keys(_this._zones);
for (var i = 0, len = keys.length; i < len; i++) {
var id = keys[i];
var zone = _this._zones[id];
var props = _this._computeWhitespaceProps(zone.delegate);
var oldWhitespace = oldWhitespaces.get(id);
if (oldWhitespace && (oldWhitespace.afterLineNumber !== props.afterViewLineNumber || oldWhitespace.height !== props.heightInPx)) {
whitespaceAccessor.changeOneWhitespace(id, props.afterViewLineNumber, props.heightInPx);
_this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
hadAChange = true;
}
}
return hadAChange;
});
};
ViewZones.prototype.onConfigurationChanged = function (e) {
var options = this._context.configuration.options;
var layoutInfo = options.get(107 /* layoutInfo */);
this._lineHeight = options.get(49 /* lineHeight */);
this._contentWidth = layoutInfo.contentWidth;
this._contentLeft = layoutInfo.contentLeft;
if (e.hasChanged(49 /* lineHeight */)) {
this._recomputeWhitespacesProps();
}
return true;
};
ViewZones.prototype.onLineMappingChanged = function (e) {
var hadAChange = this._recomputeWhitespacesProps();
if (hadAChange) {
this._context.viewLayout.onHeightMaybeChanged();
}
return hadAChange;
};
ViewZones.prototype.onLinesDeleted = function (e) {
return true;
};
ViewZones.prototype.onScrollChanged = function (e) {
return e.scrollTopChanged || e.scrollWidthChanged;
};
ViewZones.prototype.onZonesChanged = function (e) {
return true;
};
ViewZones.prototype.onLinesInserted = function (e) {
return true;
};
// ---- end view event handlers
ViewZones.prototype._getZoneOrdinal = function (zone) {
if (typeof zone.afterColumn !== 'undefined') {
return zone.afterColumn;
}
return 10000;
};
ViewZones.prototype._computeWhitespaceProps = function (zone) {
if (zone.afterLineNumber === 0) {
return {
afterViewLineNumber: 0,
heightInPx: this._heightInPixels(zone),
minWidthInPx: this._minWidthInPixels(zone)
};
}
var zoneAfterModelPosition;
if (typeof zone.afterColumn !== 'undefined') {
zoneAfterModelPosition = this._context.model.validateModelPosition({
lineNumber: zone.afterLineNumber,
column: zone.afterColumn
});
}
else {
var validAfterLineNumber = this._context.model.validateModelPosition({
lineNumber: zone.afterLineNumber,
column: 1
}).lineNumber;
zoneAfterModelPosition = new position_1.Position(validAfterLineNumber, this._context.model.getModelLineMaxColumn(validAfterLineNumber));
}
var zoneBeforeModelPosition;
if (zoneAfterModelPosition.column === this._context.model.getModelLineMaxColumn(zoneAfterModelPosition.lineNumber)) {
zoneBeforeModelPosition = this._context.model.validateModelPosition({
lineNumber: zoneAfterModelPosition.lineNumber + 1,
column: 1
});
}
else {
zoneBeforeModelPosition = this._context.model.validateModelPosition({
lineNumber: zoneAfterModelPosition.lineNumber,
column: zoneAfterModelPosition.column + 1
});
}
var viewPosition = this._context.model.coordinatesConverter.convertModelPositionToViewPosition(zoneAfterModelPosition);
var isVisible = this._context.model.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition);
return {
afterViewLineNumber: viewPosition.lineNumber,
heightInPx: (isVisible ? this._heightInPixels(zone) : 0),
minWidthInPx: this._minWidthInPixels(zone)
};
};
ViewZones.prototype.changeViewZones = function (callback) {
var _this = this;
return this._context.viewLayout.changeWhitespace(function (whitespaceAccessor) {
var zonesHaveChanged = false;
var changeAccessor = {
addZone: function (zone) {
zonesHaveChanged = true;
return _this._addZone(whitespaceAccessor, zone);
},
removeZone: function (id) {
if (!id) {
return;
}
zonesHaveChanged = _this._removeZone(whitespaceAccessor, id) || zonesHaveChanged;
},
layoutZone: function (id) {
if (!id) {
return;
}
zonesHaveChanged = _this._layoutZone(whitespaceAccessor, id) || zonesHaveChanged;
}
};
safeInvoke1Arg(callback, changeAccessor);
// Invalidate changeAccessor
changeAccessor.addZone = invalidFunc;
changeAccessor.removeZone = invalidFunc;
changeAccessor.layoutZone = invalidFunc;
return zonesHaveChanged;
});
};
ViewZones.prototype._addZone = function (whitespaceAccessor, zone) {
var props = this._computeWhitespaceProps(zone);
var whitespaceId = whitespaceAccessor.insertWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx, props.minWidthInPx);
var myZone = {
whitespaceId: whitespaceId,
delegate: zone,
isVisible: false,
domNode: fastDomNode_1.createFastDomNode(zone.domNode),
marginDomNode: zone.marginDomNode ? fastDomNode_1.createFastDomNode(zone.marginDomNode) : null
};
this._safeCallOnComputedHeight(myZone.delegate, props.heightInPx);
myZone.domNode.setPosition('absolute');
myZone.domNode.domNode.style.width = '100%';
myZone.domNode.setDisplay('none');
myZone.domNode.setAttribute('monaco-view-zone', myZone.whitespaceId);
this.domNode.appendChild(myZone.domNode);
if (myZone.marginDomNode) {
myZone.marginDomNode.setPosition('absolute');
myZone.marginDomNode.domNode.style.width = '100%';
myZone.marginDomNode.setDisplay('none');
myZone.marginDomNode.setAttribute('monaco-view-zone', myZone.whitespaceId);
this.marginDomNode.appendChild(myZone.marginDomNode);
}
this._zones[myZone.whitespaceId] = myZone;
this.setShouldRender();
return myZone.whitespaceId;
};
ViewZones.prototype._removeZone = function (whitespaceAccessor, id) {
if (this._zones.hasOwnProperty(id)) {
var zone = this._zones[id];
delete this._zones[id];
whitespaceAccessor.removeWhitespace(zone.whitespaceId);
zone.domNode.removeAttribute('monaco-visible-view-zone');
zone.domNode.removeAttribute('monaco-view-zone');
zone.domNode.domNode.parentNode.removeChild(zone.domNode.domNode);
if (zone.marginDomNode) {
zone.marginDomNode.removeAttribute('monaco-visible-view-zone');
zone.marginDomNode.removeAttribute('monaco-view-zone');
zone.marginDomNode.domNode.parentNode.removeChild(zone.marginDomNode.domNode);
}
this.setShouldRender();
return true;
}
return false;
};
ViewZones.prototype._layoutZone = function (whitespaceAccessor, id) {
if (this._zones.hasOwnProperty(id)) {
var zone = this._zones[id];
var props = this._computeWhitespaceProps(zone.delegate);
// const newOrdinal = this._getZoneOrdinal(zone.delegate);
whitespaceAccessor.changeOneWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx);
// TODO@Alex: change `newOrdinal` too
this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
this.setShouldRender();
return true;
}
return false;
};
ViewZones.prototype.shouldSuppressMouseDownOnViewZone = function (id) {
if (this._zones.hasOwnProperty(id)) {
var zone = this._zones[id];
return Boolean(zone.delegate.suppressMouseDown);
}
return false;
};
ViewZones.prototype._heightInPixels = function (zone) {
if (typeof zone.heightInPx === 'number') {
return zone.heightInPx;
}
if (typeof zone.heightInLines === 'number') {
return this._lineHeight * zone.heightInLines;
}
return this._lineHeight;
};
ViewZones.prototype._minWidthInPixels = function (zone) {
if (typeof zone.minWidthInPx === 'number') {
return zone.minWidthInPx;
}
return 0;
};
ViewZones.prototype._safeCallOnComputedHeight = function (zone, height) {
if (typeof zone.onComputedHeight === 'function') {
try {
zone.onComputedHeight(height);
}
catch (e) {
errors_1.onUnexpectedError(e);
}
}
};
ViewZones.prototype._safeCallOnDomNodeTop = function (zone, top) {
if (typeof zone.onDomNodeTop === 'function') {
try {
zone.onDomNodeTop(top);
}
catch (e) {
errors_1.onUnexpectedError(e);
}
}
};
ViewZones.prototype.prepareRender = function (ctx) {
// Nothing to read
};
ViewZones.prototype.render = function (ctx) {
var visibleWhitespaces = ctx.viewportData.whitespaceViewportData;
var visibleZones = {};
var hasVisibleZone = false;
for (var i = 0, len = visibleWhitespaces.length; i < len; i++) {
visibleZones[visibleWhitespaces[i].id] = visibleWhitespaces[i];
hasVisibleZone = true;
}
var keys = Object.keys(this._zones);
for (var i = 0, len = keys.length; i < len; i++) {
var id = keys[i];
var zone = this._zones[id];
var newTop = 0;
var newHeight = 0;
var newDisplay = 'none';
if (visibleZones.hasOwnProperty(id)) {
newTop = visibleZones[id].verticalOffset - ctx.bigNumbersDelta;
newHeight = visibleZones[id].height;
newDisplay = 'block';
// zone is visible
if (!zone.isVisible) {
zone.domNode.setAttribute('monaco-visible-view-zone', 'true');
zone.isVisible = true;
}
this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(visibleZones[id].verticalOffset));
}
else {
if (zone.isVisible) {
zone.domNode.removeAttribute('monaco-visible-view-zone');
zone.isVisible = false;
}
this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(-1000000));
}
zone.domNode.setTop(newTop);
zone.domNode.setHeight(newHeight);
zone.domNode.setDisplay(newDisplay);
if (zone.marginDomNode) {
zone.marginDomNode.setTop(newTop);
zone.marginDomNode.setHeight(newHeight);
zone.marginDomNode.setDisplay(newDisplay);
}
}
if (hasVisibleZone) {
this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
this.marginDomNode.setWidth(this._contentLeft);
}
};
return ViewZones;
}(viewPart_1.ViewPart));
exports.ViewZones = ViewZones;
function safeInvoke1Arg(func, arg1) {
try {
return func(arg1);
}
catch (e) {
errors_1.onUnexpectedError(e);
}
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[69/*vs/editor/common/viewModel/viewModel*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Viewport = /** @class */ (function () {
function Viewport(top, left, width, height) {
this.top = top | 0;
this.left = left | 0;
this.width = width | 0;
this.height = height | 0;
}
return Viewport;
}());
exports.Viewport = Viewport;
var MinimapLinesRenderingData = /** @class */ (function () {
function MinimapLinesRenderingData(tabSize, data) {
this.tabSize = tabSize;
this.data = data;
}
return MinimapLinesRenderingData;
}());
exports.MinimapLinesRenderingData = MinimapLinesRenderingData;
var ViewLineData = /** @class */ (function () {
function ViewLineData(content, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens) {
this.content = content;
this.continuesWithWrappedLine = continuesWithWrappedLine;
this.minColumn = minColumn;
this.maxColumn = maxColumn;
this.startVisibleColumn = startVisibleColumn;
this.tokens = tokens;
}
return ViewLineData;
}());
exports.ViewLineData = ViewLineData;
var ViewLineRenderingData = /** @class */ (function () {
function ViewLineRenderingData(minColumn, maxColumn, content, continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, tokens, inlineDecorations, tabSize, startVisibleColumn) {
this.minColumn = minColumn;
this.maxColumn = maxColumn;
this.content = content;
this.continuesWithWrappedLine = continuesWithWrappedLine;
this.isBasicASCII = ViewLineRenderingData.isBasicASCII(content, mightContainNonBasicASCII);
this.containsRTL = ViewLineRenderingData.containsRTL(content, this.isBasicASCII, mightContainRTL);
this.tokens = tokens;
this.inlineDecorations = inlineDecorations;
this.tabSize = tabSize;
this.startVisibleColumn = startVisibleColumn;
}
ViewLineRenderingData.isBasicASCII = function (lineContent, mightContainNonBasicASCII) {
if (mightContainNonBasicASCII) {
return strings.isBasicASCII(lineContent);
}
return true;
};
ViewLineRenderingData.containsRTL = function (lineContent, isBasicASCII, mightContainRTL) {
if (!isBasicASCII && mightContainRTL) {
return strings.containsRTL(lineContent);
}
return false;
};
return ViewLineRenderingData;
}());
exports.ViewLineRenderingData = ViewLineRenderingData;
var InlineDecoration = /** @class */ (function () {
function InlineDecoration(range, inlineClassName, type) {
this.range = range;
this.inlineClassName = inlineClassName;
this.type = type;
}
return InlineDecoration;
}());
exports.InlineDecoration = InlineDecoration;
var ViewModelDecoration = /** @class */ (function () {
function ViewModelDecoration(range, options) {
this.range = range;
this.options = options;
}
return ViewModelDecoration;
}());
exports.ViewModelDecoration = ViewModelDecoration;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[373/*vs/editor/common/viewLayout/viewLayout*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,176/*vs/base/common/scrollable*/,362/*vs/editor/common/viewLayout/linesLayout*/,69/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, event_1, lifecycle_1, scrollable_1, linesLayout_1, viewModel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SMOOTH_SCROLLING_TIME = 125;
var EditorScrollDimensions = /** @class */ (function () {
function EditorScrollDimensions(width, contentWidth, height, contentHeight) {
width = width | 0;
contentWidth = contentWidth | 0;
height = height | 0;
contentHeight = contentHeight | 0;
if (width < 0) {
width = 0;
}
if (contentWidth < 0) {
contentWidth = 0;
}
if (height < 0) {
height = 0;
}
if (contentHeight < 0) {
contentHeight = 0;
}
this.width = width;
this.contentWidth = contentWidth;
this.scrollWidth = Math.max(width, contentWidth);
this.height = height;
this.contentHeight = contentHeight;
this.scrollHeight = Math.max(height, contentHeight);
}
EditorScrollDimensions.prototype.equals = function (other) {
return (this.width === other.width
&& this.contentWidth === other.contentWidth
&& this.height === other.height
&& this.contentHeight === other.contentHeight);
};
return EditorScrollDimensions;
}());
var EditorScrollable = /** @class */ (function (_super) {
__extends(EditorScrollable, _super);
function EditorScrollable(smoothScrollDuration, scheduleAtNextAnimationFrame) {
var _this = _super.call(this) || this;
_this._onDidContentSizeChange = _this._register(new event_1.Emitter());
_this.onDidContentSizeChange = _this._onDidContentSizeChange.event;
_this._dimensions = new EditorScrollDimensions(0, 0, 0, 0);
_this._scrollable = _this._register(new scrollable_1.Scrollable(smoothScrollDuration, scheduleAtNextAnimationFrame));
_this.onDidScroll = _this._scrollable.onScroll;
return _this;
}
EditorScrollable.prototype.getScrollable = function () {
return this._scrollable;
};
EditorScrollable.prototype.setSmoothScrollDuration = function (smoothScrollDuration) {
this._scrollable.setSmoothScrollDuration(smoothScrollDuration);
};
EditorScrollable.prototype.validateScrollPosition = function (scrollPosition) {
return this._scrollable.validateScrollPosition(scrollPosition);
};
EditorScrollable.prototype.getScrollDimensions = function () {
return this._dimensions;
};
EditorScrollable.prototype.setScrollDimensions = function (dimensions) {
if (this._dimensions.equals(dimensions)) {
return;
}
var oldDimensions = this._dimensions;
this._dimensions = dimensions;
this._scrollable.setScrollDimensions({
width: dimensions.width,
scrollWidth: dimensions.scrollWidth,
height: dimensions.height,
scrollHeight: dimensions.scrollHeight
});
var contentWidthChanged = (oldDimensions.contentWidth !== dimensions.contentWidth);
var contentHeightChanged = (oldDimensions.contentHeight !== dimensions.contentHeight);
if (contentWidthChanged || contentHeightChanged) {
this._onDidContentSizeChange.fire({
contentWidth: dimensions.contentWidth,
contentHeight: dimensions.contentHeight,
contentWidthChanged: contentWidthChanged,
contentHeightChanged: contentHeightChanged
});
}
};
EditorScrollable.prototype.getFutureScrollPosition = function () {
return this._scrollable.getFutureScrollPosition();
};
EditorScrollable.prototype.getCurrentScrollPosition = function () {
return this._scrollable.getCurrentScrollPosition();
};
EditorScrollable.prototype.setScrollPositionNow = function (update) {
this._scrollable.setScrollPositionNow(update);
};
EditorScrollable.prototype.setScrollPositionSmooth = function (update) {
this._scrollable.setScrollPositionSmooth(update);
};
return EditorScrollable;
}(lifecycle_1.Disposable));
var ViewLayout = /** @class */ (function (_super) {
__extends(ViewLayout, _super);
function ViewLayout(configuration, lineCount, scheduleAtNextAnimationFrame) {
var _this = _super.call(this) || this;
_this._configuration = configuration;
var options = _this._configuration.options;
var layoutInfo = options.get(107 /* layoutInfo */);
_this._linesLayout = new linesLayout_1.LinesLayout(lineCount, options.get(49 /* lineHeight */));
_this._scrollable = _this._register(new EditorScrollable(0, scheduleAtNextAnimationFrame));
_this._configureSmoothScrollDuration();
_this._scrollable.setScrollDimensions(new EditorScrollDimensions(layoutInfo.contentWidth, 0, layoutInfo.height, 0));
_this.onDidScroll = _this._scrollable.onDidScroll;
_this.onDidContentSizeChange = _this._scrollable.onDidContentSizeChange;
_this._updateHeight();
return _this;
}
ViewLayout.prototype.dispose = function () {
_super.prototype.dispose.call(this);
};
ViewLayout.prototype.getScrollable = function () {
return this._scrollable.getScrollable();
};
ViewLayout.prototype.onHeightMaybeChanged = function () {
this._updateHeight();
};
ViewLayout.prototype._configureSmoothScrollDuration = function () {
this._scrollable.setSmoothScrollDuration(this._configuration.options.get(87 /* smoothScrolling */) ? SMOOTH_SCROLLING_TIME : 0);
};
// ---- begin view event handlers
ViewLayout.prototype.onConfigurationChanged = function (e) {
var options = this._configuration.options;
if (e.hasChanged(49 /* lineHeight */)) {
this._linesLayout.setLineHeight(options.get(49 /* lineHeight */));
}
if (e.hasChanged(107 /* layoutInfo */)) {
var layoutInfo = options.get(107 /* layoutInfo */);
var width = layoutInfo.contentWidth;
var height = layoutInfo.height;
var scrollDimensions = this._scrollable.getScrollDimensions();
var scrollWidth = scrollDimensions.scrollWidth;
this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, scrollWidth)));
}
else {
this._updateHeight();
}
if (e.hasChanged(87 /* smoothScrolling */)) {
this._configureSmoothScrollDuration();
}
};
ViewLayout.prototype.onFlushed = function (lineCount) {
this._linesLayout.onFlushed(lineCount);
};
ViewLayout.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) {
this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber);
};
ViewLayout.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) {
this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber);
};
// ---- end view event handlers
ViewLayout.prototype._getHorizontalScrollbarHeight = function (width, scrollWidth) {
var options = this._configuration.options;
var scrollbar = options.get(78 /* scrollbar */);
if (scrollbar.horizontal === 2 /* Hidden */) {
// horizontal scrollbar not visible
return 0;
}
if (width >= scrollWidth) {
// horizontal scrollbar not visible
return 0;
}
return scrollbar.horizontalScrollbarSize;
};
ViewLayout.prototype._getContentHeight = function (width, height, scrollWidth) {
var options = this._configuration.options;
var result = this._linesLayout.getLinesTotalHeight();
if (options.get(80 /* scrollBeyondLastLine */)) {
result += height - options.get(49 /* lineHeight */);
}
else {
result += this._getHorizontalScrollbarHeight(width, scrollWidth);
}
return result;
};
ViewLayout.prototype._updateHeight = function () {
var scrollDimensions = this._scrollable.getScrollDimensions();
var width = scrollDimensions.width;
var height = scrollDimensions.height;
var scrollWidth = scrollDimensions.scrollWidth;
this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, scrollWidth)));
};
// ---- Layouting logic
ViewLayout.prototype.getCurrentViewport = function () {
var scrollDimensions = this._scrollable.getScrollDimensions();
var currentScrollPosition = this._scrollable.getCurrentScrollPosition();
return new viewModel_1.Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
};
ViewLayout.prototype.getFutureViewport = function () {
var scrollDimensions = this._scrollable.getScrollDimensions();
var currentScrollPosition = this._scrollable.getFutureScrollPosition();
return new viewModel_1.Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
};
ViewLayout.prototype._computeContentWidth = function (maxLineWidth) {
var options = this._configuration.options;
var wrappingInfo = options.get(108 /* wrappingInfo */);
var fontInfo = options.get(34 /* fontInfo */);
if (wrappingInfo.isViewportWrapping) {
var layoutInfo = options.get(107 /* layoutInfo */);
var minimap = options.get(54 /* minimap */);
if (maxLineWidth > layoutInfo.contentWidth + fontInfo.typicalHalfwidthCharacterWidth) {
// This is a case where viewport wrapping is on, but the line extends above the viewport
if (minimap.enabled && minimap.side === 'right') {
// We need to accomodate the scrollbar width
return maxLineWidth + layoutInfo.verticalScrollbarWidth;
}
}
return maxLineWidth;
}
else {
var extraHorizontalSpace = options.get(79 /* scrollBeyondLastColumn */) * fontInfo.typicalHalfwidthCharacterWidth;
var whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth();
return Math.max(maxLineWidth + extraHorizontalSpace, whitespaceMinWidth);
}
};
ViewLayout.prototype.onMaxLineWidthChanged = function (maxLineWidth) {
var scrollDimensions = this._scrollable.getScrollDimensions();
// const newScrollWidth = ;
this._scrollable.setScrollDimensions(new EditorScrollDimensions(scrollDimensions.width, this._computeContentWidth(maxLineWidth), scrollDimensions.height, scrollDimensions.contentHeight));
// The height might depend on the fact that there is a horizontal scrollbar or not
this._updateHeight();
};
// ---- view state
ViewLayout.prototype.saveState = function () {
var currentScrollPosition = this._scrollable.getFutureScrollPosition();
var scrollTop = currentScrollPosition.scrollTop;
var firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop);
var whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);
return {
scrollTop: scrollTop,
scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,
scrollLeft: currentScrollPosition.scrollLeft
};
};
// ---- IVerticalLayoutProvider
ViewLayout.prototype.changeWhitespace = function (callback) {
return this._linesLayout.changeWhitespace(callback);
};
ViewLayout.prototype.getVerticalOffsetForLineNumber = function (lineNumber) {
return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber);
};
ViewLayout.prototype.isAfterLines = function (verticalOffset) {
return this._linesLayout.isAfterLines(verticalOffset);
};
ViewLayout.prototype.getLineNumberAtVerticalOffset = function (verticalOffset) {
return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset);
};
ViewLayout.prototype.getWhitespaceAtVerticalOffset = function (verticalOffset) {
return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset);
};
ViewLayout.prototype.getLinesViewportData = function () {
var visibleBox = this.getCurrentViewport();
return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
};
ViewLayout.prototype.getLinesViewportDataAtScrollTop = function (scrollTop) {
// do some minimal validations on scrollTop
var scrollDimensions = this._scrollable.getScrollDimensions();
if (scrollTop + scrollDimensions.height > scrollDimensions.scrollHeight) {
scrollTop = scrollDimensions.scrollHeight - scrollDimensions.height;
}
if (scrollTop < 0) {
scrollTop = 0;
}
return this._linesLayout.getLinesViewportData(scrollTop, scrollTop + scrollDimensions.height);
};
ViewLayout.prototype.getWhitespaceViewportData = function () {
var visibleBox = this.getCurrentViewport();
return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
};
ViewLayout.prototype.getWhitespaces = function () {
return this._linesLayout.getWhitespaces();
};
// ---- IScrollingProvider
ViewLayout.prototype.getContentWidth = function () {
var scrollDimensions = this._scrollable.getScrollDimensions();
return scrollDimensions.contentWidth;
};
ViewLayout.prototype.getScrollWidth = function () {
var scrollDimensions = this._scrollable.getScrollDimensions();
return scrollDimensions.scrollWidth;
};
ViewLayout.prototype.getContentHeight = function () {
var scrollDimensions = this._scrollable.getScrollDimensions();
return scrollDimensions.contentHeight;
};
ViewLayout.prototype.getScrollHeight = function () {
var scrollDimensions = this._scrollable.getScrollDimensions();
return scrollDimensions.scrollHeight;
};
ViewLayout.prototype.getCurrentScrollLeft = function () {
var currentScrollPosition = this._scrollable.getCurrentScrollPosition();
return currentScrollPosition.scrollLeft;
};
ViewLayout.prototype.getCurrentScrollTop = function () {
var currentScrollPosition = this._scrollable.getCurrentScrollPosition();
return currentScrollPosition.scrollTop;
};
ViewLayout.prototype.validateScrollPosition = function (scrollPosition) {
return this._scrollable.validateScrollPosition(scrollPosition);
};
ViewLayout.prototype.setScrollPositionNow = function (position) {
this._scrollable.setScrollPositionNow(position);
};
ViewLayout.prototype.setScrollPositionSmooth = function (position) {
this._scrollable.setScrollPositionSmooth(position);
};
ViewLayout.prototype.deltaScrollNow = function (deltaScrollLeft, deltaScrollTop) {
var currentScrollPosition = this._scrollable.getCurrentScrollPosition();
this._scrollable.setScrollPositionNow({
scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft,
scrollTop: currentScrollPosition.scrollTop + deltaScrollTop
});
};
return ViewLayout;
}(lifecycle_1.Disposable));
exports.ViewLayout = ViewLayout;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[374/*vs/editor/contrib/caretOperations/moveCaretCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MoveCaretCommand = /** @class */ (function () {
function MoveCaretCommand(selection, isMovingLeft) {
this._selection = selection;
this._isMovingLeft = isMovingLeft;
this._cutStartIndex = -1;
this._cutEndIndex = -1;
this._moved = false;
this._selectionId = null;
}
MoveCaretCommand.prototype.getEditOperations = function (model, builder) {
var s = this._selection;
this._selectionId = builder.trackSelection(s);
if (s.startLineNumber !== s.endLineNumber) {
return;
}
if (this._isMovingLeft && s.startColumn === 0) {
return;
}
else if (!this._isMovingLeft && s.endColumn === model.getLineMaxColumn(s.startLineNumber)) {
return;
}
var lineNumber = s.selectionStartLineNumber;
var lineContent = model.getLineContent(lineNumber);
var left;
var middle;
var right;
if (this._isMovingLeft) {
left = lineContent.substring(0, s.startColumn - 2);
middle = lineContent.substring(s.startColumn - 1, s.endColumn - 1);
right = lineContent.substring(s.startColumn - 2, s.startColumn - 1) + lineContent.substring(s.endColumn - 1);
}
else {
left = lineContent.substring(0, s.startColumn - 1) + lineContent.substring(s.endColumn - 1, s.endColumn);
middle = lineContent.substring(s.startColumn - 1, s.endColumn - 1);
right = lineContent.substring(s.endColumn);
}
var newLineContent = left + middle + right;
builder.addEditOperation(new range_1.Range(lineNumber, 1, lineNumber, model.getLineMaxColumn(lineNumber)), null);
builder.addEditOperation(new range_1.Range(lineNumber, 1, lineNumber, 1), newLineContent);
this._cutStartIndex = s.startColumn + (this._isMovingLeft ? -1 : 1);
this._cutEndIndex = this._cutStartIndex + s.endColumn - s.startColumn;
this._moved = true;
};
MoveCaretCommand.prototype.computeCursorState = function (model, helper) {
var result = helper.getTrackedSelection(this._selectionId);
if (this._moved) {
result = result.setStartPosition(result.startLineNumber, this._cutStartIndex);
result = result.setEndPosition(result.startLineNumber, this._cutEndIndex);
}
return result;
};
return MoveCaretCommand;
}());
exports.MoveCaretCommand = MoveCaretCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[111/*vs/editor/contrib/codeAction/types*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/]), function (require, exports, strings_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CodeActionKind = /** @class */ (function () {
function CodeActionKind(value) {
this.value = value;
}
CodeActionKind.prototype.equals = function (other) {
return this.value === other.value;
};
CodeActionKind.prototype.contains = function (other) {
return this.equals(other) || this.value === '' || strings_1.startsWith(other.value, this.value + CodeActionKind.sep);
};
CodeActionKind.prototype.intersects = function (other) {
return this.contains(other) || other.contains(this);
};
CodeActionKind.prototype.append = function (part) {
return new CodeActionKind(this.value + CodeActionKind.sep + part);
};
CodeActionKind.sep = '.';
CodeActionKind.None = new CodeActionKind('@@none@@'); // Special code action that contains nothing
CodeActionKind.Empty = new CodeActionKind('');
CodeActionKind.QuickFix = new CodeActionKind('quickfix');
CodeActionKind.Refactor = new CodeActionKind('refactor');
CodeActionKind.Source = new CodeActionKind('source');
CodeActionKind.SourceOrganizeImports = CodeActionKind.Source.append('organizeImports');
CodeActionKind.SourceFixAll = CodeActionKind.Source.append('fixAll');
return CodeActionKind;
}());
exports.CodeActionKind = CodeActionKind;
function mayIncludeActionsOfKind(filter, providedKind) {
// A provided kind may be a subset or superset of our filtered kind.
if (filter.include && !filter.include.intersects(providedKind)) {
return false;
}
if (filter.excludes) {
if (filter.excludes.some(function (exclude) { return excludesAction(providedKind, exclude, filter.include); })) {
return false;
}
}
// Don't return source actions unless they are explicitly requested
if (!filter.includeSourceActions && CodeActionKind.Source.contains(providedKind)) {
return false;
}
return true;
}
exports.mayIncludeActionsOfKind = mayIncludeActionsOfKind;
function filtersAction(filter, action) {
var actionKind = action.kind ? new CodeActionKind(action.kind) : undefined;
// Filter out actions by kind
if (filter.include) {
if (!actionKind || !filter.include.contains(actionKind)) {
return false;
}
}
if (filter.excludes) {
if (actionKind && filter.excludes.some(function (exclude) { return excludesAction(actionKind, exclude, filter.include); })) {
return false;
}
}
// Don't return source actions unless they are explicitly requested
if (!filter.includeSourceActions) {
if (actionKind && CodeActionKind.Source.contains(actionKind)) {
return false;
}
}
if (filter.onlyIncludePreferredActions) {
if (!action.isPreferred) {
return false;
}
}
return true;
}
exports.filtersAction = filtersAction;
function excludesAction(providedKind, exclude, include) {
if (!exclude.contains(providedKind)) {
return false;
}
if (include && exclude.contains(include)) {
// The include is more specific, don't filter out
return false;
}
return true;
}
var CodeActionCommandArgs = /** @class */ (function () {
function CodeActionCommandArgs(kind, apply, preferred) {
this.kind = kind;
this.apply = apply;
this.preferred = preferred;
}
CodeActionCommandArgs.fromUser = function (arg, defaults) {
if (!arg || typeof arg !== 'object') {
return new CodeActionCommandArgs(defaults.kind, defaults.apply, false);
}
return new CodeActionCommandArgs(CodeActionCommandArgs.getKindFromUser(arg, defaults.kind), CodeActionCommandArgs.getApplyFromUser(arg, defaults.apply), CodeActionCommandArgs.getPreferredUser(arg));
};
CodeActionCommandArgs.getApplyFromUser = function (arg, defaultAutoApply) {
switch (typeof arg.apply === 'string' ? arg.apply.toLowerCase() : '') {
case 'first': return "first" /* First */;
case 'never': return "never" /* Never */;
case 'ifsingle': return "ifSingle" /* IfSingle */;
default: return defaultAutoApply;
}
};
CodeActionCommandArgs.getKindFromUser = function (arg, defaultKind) {
return typeof arg.kind === 'string'
? new CodeActionKind(arg.kind)
: defaultKind;
};
CodeActionCommandArgs.getPreferredUser = function (arg) {
return typeof arg.preferred === 'boolean'
? arg.preferred
: false;
};
return CodeActionCommandArgs;
}());
exports.CodeActionCommandArgs = CodeActionCommandArgs;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[375/*vs/editor/contrib/colorPicker/colorPickerModel*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/]), function (require, exports, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ColorPickerModel = /** @class */ (function () {
function ColorPickerModel(color, availableColorPresentations, presentationIndex) {
this.presentationIndex = presentationIndex;
this._onColorFlushed = new event_1.Emitter();
this.onColorFlushed = this._onColorFlushed.event;
this._onDidChangeColor = new event_1.Emitter();
this.onDidChangeColor = this._onDidChangeColor.event;
this._onDidChangePresentation = new event_1.Emitter();
this.onDidChangePresentation = this._onDidChangePresentation.event;
this.originalColor = color;
this._color = color;
this._colorPresentations = availableColorPresentations;
}
Object.defineProperty(ColorPickerModel.prototype, "color", {
get: function () {
return this._color;
},
set: function (color) {
if (this._color.equals(color)) {
return;
}
this._color = color;
this._onDidChangeColor.fire(color);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorPickerModel.prototype, "presentation", {
get: function () { return this.colorPresentations[this.presentationIndex]; },
enumerable: true,
configurable: true
});
Object.defineProperty(ColorPickerModel.prototype, "colorPresentations", {
get: function () {
return this._colorPresentations;
},
set: function (colorPresentations) {
this._colorPresentations = colorPresentations;
if (this.presentationIndex > colorPresentations.length - 1) {
this.presentationIndex = 0;
}
this._onDidChangePresentation.fire(this.presentation);
},
enumerable: true,
configurable: true
});
ColorPickerModel.prototype.selectNextColorPresentation = function () {
this.presentationIndex = (this.presentationIndex + 1) % this.colorPresentations.length;
this.flushColor();
this._onDidChangePresentation.fire(this.presentation);
};
ColorPickerModel.prototype.guessColorPresentation = function (color, originalText) {
for (var i = 0; i < this.colorPresentations.length; i++) {
if (originalText === this.colorPresentations[i].label) {
this.presentationIndex = i;
this._onDidChangePresentation.fire(this.presentation);
break;
}
}
};
ColorPickerModel.prototype.flushColor = function () {
this._onColorFlushed.fire(this._color);
};
return ColorPickerModel;
}());
exports.ColorPickerModel = ColorPickerModel;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[196/*vs/editor/contrib/comment/blockCommentCommand*/], __M([0/*require*/,1/*exports*/,58/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, editOperation_1, position_1, range_1, selection_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BlockCommentCommand = /** @class */ (function () {
function BlockCommentCommand(selection, insertSpace) {
this._selection = selection;
this._insertSpace = insertSpace;
this._usedEndToken = null;
}
BlockCommentCommand._haystackHasNeedleAtOffset = function (haystack, needle, offset) {
if (offset < 0) {
return false;
}
var needleLength = needle.length;
var haystackLength = haystack.length;
if (offset + needleLength > haystackLength) {
return false;
}
for (var i = 0; i < needleLength; i++) {
var codeA = haystack.charCodeAt(offset + i);
var codeB = needle.charCodeAt(i);
if (codeA === codeB) {
continue;
}
if (codeA >= 65 /* A */ && codeA <= 90 /* Z */ && codeA + 32 === codeB) {
// codeA is upper-case variant of codeB
continue;
}
if (codeB >= 65 /* A */ && codeB <= 90 /* Z */ && codeB + 32 === codeA) {
// codeB is upper-case variant of codeA
continue;
}
return false;
}
return true;
};
BlockCommentCommand.prototype._createOperationsForBlockComment = function (selection, startToken, endToken, insertSpace, model, builder) {
var startLineNumber = selection.startLineNumber;
var startColumn = selection.startColumn;
var endLineNumber = selection.endLineNumber;
var endColumn = selection.endColumn;
var startLineText = model.getLineContent(startLineNumber);
var endLineText = model.getLineContent(endLineNumber);
var startTokenIndex = startLineText.lastIndexOf(startToken, startColumn - 1 + startToken.length);
var endTokenIndex = endLineText.indexOf(endToken, endColumn - 1 - endToken.length);
if (startTokenIndex !== -1 && endTokenIndex !== -1) {
if (startLineNumber === endLineNumber) {
var lineBetweenTokens = startLineText.substring(startTokenIndex + startToken.length, endTokenIndex);
if (lineBetweenTokens.indexOf(endToken) >= 0) {
// force to add a block comment
startTokenIndex = -1;
endTokenIndex = -1;
}
}
else {
var startLineAfterStartToken = startLineText.substring(startTokenIndex + startToken.length);
var endLineBeforeEndToken = endLineText.substring(0, endTokenIndex);
if (startLineAfterStartToken.indexOf(endToken) >= 0 || endLineBeforeEndToken.indexOf(endToken) >= 0) {
// force to add a block comment
startTokenIndex = -1;
endTokenIndex = -1;
}
}
}
var ops;
if (startTokenIndex !== -1 && endTokenIndex !== -1) {
// Consider spaces as part of the comment tokens
if (insertSpace && startTokenIndex + startToken.length < startLineText.length && startLineText.charCodeAt(startTokenIndex + startToken.length) === 32 /* Space */) {
// Pretend the start token contains a trailing space
startToken = startToken + ' ';
}
if (insertSpace && endTokenIndex > 0 && endLineText.charCodeAt(endTokenIndex - 1) === 32 /* Space */) {
// Pretend the end token contains a leading space
endToken = ' ' + endToken;
endTokenIndex -= 1;
}
ops = BlockCommentCommand._createRemoveBlockCommentOperations(new range_1.Range(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
}
else {
ops = BlockCommentCommand._createAddBlockCommentOperations(selection, startToken, endToken, this._insertSpace);
this._usedEndToken = ops.length === 1 ? endToken : null;
}
for (var _i = 0, ops_1 = ops; _i < ops_1.length; _i++) {
var op = ops_1[_i];
builder.addTrackedEditOperation(op.range, op.text);
}
};
BlockCommentCommand._createRemoveBlockCommentOperations = function (r, startToken, endToken) {
var res = [];
if (!range_1.Range.isEmpty(r)) {
// Remove block comment start
res.push(editOperation_1.EditOperation.delete(new range_1.Range(r.startLineNumber, r.startColumn - startToken.length, r.startLineNumber, r.startColumn)));
// Remove block comment end
res.push(editOperation_1.EditOperation.delete(new range_1.Range(r.endLineNumber, r.endColumn, r.endLineNumber, r.endColumn + endToken.length)));
}
else {
// Remove both continuously
res.push(editOperation_1.EditOperation.delete(new range_1.Range(r.startLineNumber, r.startColumn - startToken.length, r.endLineNumber, r.endColumn + endToken.length)));
}
return res;
};
BlockCommentCommand._createAddBlockCommentOperations = function (r, startToken, endToken, insertSpace) {
var res = [];
if (!range_1.Range.isEmpty(r)) {
// Insert block comment start
res.push(editOperation_1.EditOperation.insert(new position_1.Position(r.startLineNumber, r.startColumn), startToken + (insertSpace ? ' ' : '')));
// Insert block comment end
res.push(editOperation_1.EditOperation.insert(new position_1.Position(r.endLineNumber, r.endColumn), (insertSpace ? ' ' : '') + endToken));
}
else {
// Insert both continuously
res.push(editOperation_1.EditOperation.replace(new range_1.Range(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn), startToken + ' ' + endToken));
}
return res;
};
BlockCommentCommand.prototype.getEditOperations = function (model, builder) {
var startLineNumber = this._selection.startLineNumber;
var startColumn = this._selection.startColumn;
model.tokenizeIfCheap(startLineNumber);
var languageId = model.getLanguageIdAtPosition(startLineNumber, startColumn);
var config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId);
if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
// Mode does not support block comments
return;
}
this._createOperationsForBlockComment(this._selection, config.blockCommentStartToken, config.blockCommentEndToken, this._insertSpace, model, builder);
};
BlockCommentCommand.prototype.computeCursorState = function (model, helper) {
var inverseEditOperations = helper.getInverseEditOperations();
if (inverseEditOperations.length === 2) {
var startTokenEditOperation = inverseEditOperations[0];
var endTokenEditOperation = inverseEditOperations[1];
return new selection_1.Selection(startTokenEditOperation.range.endLineNumber, startTokenEditOperation.range.endColumn, endTokenEditOperation.range.startLineNumber, endTokenEditOperation.range.startColumn);
}
else {
var srcRange = inverseEditOperations[0].range;
var deltaColumn = this._usedEndToken ? -this._usedEndToken.length - 1 : 0; // minus 1 space before endToken
return new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn + deltaColumn, srcRange.endLineNumber, srcRange.endColumn + deltaColumn);
}
};
return BlockCommentCommand;
}());
exports.BlockCommentCommand = BlockCommentCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[376/*vs/editor/contrib/comment/lineCommentCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,58/*vs/editor/common/core/editOperation*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,196/*vs/editor/contrib/comment/blockCommentCommand*/]), function (require, exports, strings, editOperation_1, position_1, range_1, selection_1, languageConfigurationRegistry_1, blockCommentCommand_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LineCommentCommand = /** @class */ (function () {
function LineCommentCommand(selection, tabSize, type, insertSpace) {
this._selection = selection;
this._tabSize = tabSize;
this._type = type;
this._insertSpace = insertSpace;
this._selectionId = null;
this._deltaColumn = 0;
this._moveEndPositionDown = false;
}
/**
* Do an initial pass over the lines and gather info about the line comment string.
* Returns null if any of the lines doesn't support a line comment string.
*/
LineCommentCommand._gatherPreflightCommentStrings = function (model, startLineNumber, endLineNumber) {
model.tokenizeIfCheap(startLineNumber);
var languageId = model.getLanguageIdAtPosition(startLineNumber, 1);
var config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId);
var commentStr = (config ? config.lineCommentToken : null);
if (!commentStr) {
// Mode does not support line comments
return null;
}
var lines = [];
for (var i = 0, lineCount = endLineNumber - startLineNumber + 1; i < lineCount; i++) {
lines[i] = {
ignore: false,
commentStr: commentStr,
commentStrOffset: 0,
commentStrLength: commentStr.length
};
}
return lines;
};
/**
* Analyze lines and decide which lines are relevant and what the toggle should do.
* Also, build up several offsets and lengths useful in the generation of editor operations.
*/
LineCommentCommand._analyzeLines = function (type, insertSpace, model, lines, startLineNumber) {
var onlyWhitespaceLines = true;
var shouldRemoveComments;
if (type === 0 /* Toggle */) {
shouldRemoveComments = true;
}
else if (type === 1 /* ForceAdd */) {
shouldRemoveComments = false;
}
else {
shouldRemoveComments = true;
}
for (var i = 0, lineCount = lines.length; i < lineCount; i++) {
var lineData = lines[i];
var lineNumber = startLineNumber + i;
var lineContent = model.getLineContent(lineNumber);
var lineContentStartOffset = strings.firstNonWhitespaceIndex(lineContent);
if (lineContentStartOffset === -1) {
// Empty or whitespace only line
if (type === 0 /* Toggle */) {
lineData.ignore = true;
}
else if (type === 1 /* ForceAdd */) {
lineData.ignore = true;
}
else {
lineData.ignore = true;
}
lineData.commentStrOffset = lineContent.length;
continue;
}
onlyWhitespaceLines = false;
lineData.ignore = false;
lineData.commentStrOffset = lineContentStartOffset;
if (shouldRemoveComments && !blockCommentCommand_1.BlockCommentCommand._haystackHasNeedleAtOffset(lineContent, lineData.commentStr, lineContentStartOffset)) {
if (type === 0 /* Toggle */) {
// Every line so far has been a line comment, but this one is not
shouldRemoveComments = false;
}
else if (type === 1 /* ForceAdd */) {
// Will not happen
}
else {
lineData.ignore = true;
}
}
if (shouldRemoveComments && insertSpace) {
// Remove a following space if present
var commentStrEndOffset = lineContentStartOffset + lineData.commentStrLength;
if (commentStrEndOffset < lineContent.length && lineContent.charCodeAt(commentStrEndOffset) === 32 /* Space */) {
lineData.commentStrLength += 1;
}
}
}
if (type === 0 /* Toggle */ && onlyWhitespaceLines) {
// For only whitespace lines, we insert comments
shouldRemoveComments = false;
// Also, no longer ignore them
for (var i = 0, lineCount = lines.length; i < lineCount; i++) {
lines[i].ignore = false;
}
}
return {
supported: true,
shouldRemoveComments: shouldRemoveComments,
lines: lines
};
};
/**
* Analyze all lines and decide exactly what to do => not supported | insert line comments | remove line comments
*/
LineCommentCommand._gatherPreflightData = function (type, insertSpace, model, startLineNumber, endLineNumber) {
var lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber);
if (lines === null) {
return {
supported: false
};
}
return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber);
};
/**
* Given a successful analysis, execute either insert line comments, either remove line comments
*/
LineCommentCommand.prototype._executeLineComments = function (model, builder, data, s) {
var ops;
if (data.shouldRemoveComments) {
ops = LineCommentCommand._createRemoveLineCommentsOperations(data.lines, s.startLineNumber);
}
else {
LineCommentCommand._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this._tabSize);
ops = this._createAddLineCommentsOperations(data.lines, s.startLineNumber);
}
var cursorPosition = new position_1.Position(s.positionLineNumber, s.positionColumn);
for (var i = 0, len = ops.length; i < len; i++) {
builder.addEditOperation(ops[i].range, ops[i].text);
if (ops[i].range.isEmpty() && ops[i].range.getStartPosition().equals(cursorPosition)) {
var lineContent = model.getLineContent(cursorPosition.lineNumber);
if (lineContent.length + 1 === cursorPosition.column) {
this._deltaColumn = (ops[i].text || '').length;
}
}
}
this._selectionId = builder.trackSelection(s);
};
LineCommentCommand.prototype._attemptRemoveBlockComment = function (model, s, startToken, endToken) {
var startLineNumber = s.startLineNumber;
var endLineNumber = s.endLineNumber;
var startTokenAllowedBeforeColumn = endToken.length + Math.max(model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.startColumn);
var startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startTokenAllowedBeforeColumn - 1);
var endTokenIndex = model.getLineContent(endLineNumber).indexOf(endToken, s.endColumn - 1 - startToken.length);
if (startTokenIndex !== -1 && endTokenIndex === -1) {
endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
endLineNumber = startLineNumber;
}
if (startTokenIndex === -1 && endTokenIndex !== -1) {
startTokenIndex = model.getLineContent(endLineNumber).lastIndexOf(startToken, endTokenIndex);
startLineNumber = endLineNumber;
}
if (s.isEmpty() && (startTokenIndex === -1 || endTokenIndex === -1)) {
startTokenIndex = model.getLineContent(startLineNumber).indexOf(startToken);
if (startTokenIndex !== -1) {
endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
}
}
// We have to adjust to possible inner white space.
// For Space after startToken, add Space to startToken - range math will work out.
if (startTokenIndex !== -1 && model.getLineContent(startLineNumber).charCodeAt(startTokenIndex + startToken.length) === 32 /* Space */) {
startToken += ' ';
}
// For Space before endToken, add Space before endToken and shift index one left.
if (endTokenIndex !== -1 && model.getLineContent(endLineNumber).charCodeAt(endTokenIndex - 1) === 32 /* Space */) {
endToken = ' ' + endToken;
endTokenIndex -= 1;
}
if (startTokenIndex !== -1 && endTokenIndex !== -1) {
return blockCommentCommand_1.BlockCommentCommand._createRemoveBlockCommentOperations(new range_1.Range(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
}
return null;
};
/**
* Given an unsuccessful analysis, delegate to the block comment command
*/
LineCommentCommand.prototype._executeBlockComment = function (model, builder, s) {
model.tokenizeIfCheap(s.startLineNumber);
var languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1);
var config = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getComments(languageId);
if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
// Mode does not support block comments
return;
}
var startToken = config.blockCommentStartToken;
var endToken = config.blockCommentEndToken;
var ops = this._attemptRemoveBlockComment(model, s, startToken, endToken);
if (!ops) {
if (s.isEmpty()) {
var lineContent = model.getLineContent(s.startLineNumber);
var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
if (firstNonWhitespaceIndex === -1) {
// Line is empty or contains only whitespace
firstNonWhitespaceIndex = lineContent.length;
}
ops = blockCommentCommand_1.BlockCommentCommand._createAddBlockCommentOperations(new range_1.Range(s.startLineNumber, firstNonWhitespaceIndex + 1, s.startLineNumber, lineContent.length + 1), startToken, endToken, this._insertSpace);
}
else {
ops = blockCommentCommand_1.BlockCommentCommand._createAddBlockCommentOperations(new range_1.Range(s.startLineNumber, model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), startToken, endToken, this._insertSpace);
}
if (ops.length === 1) {
// Leave cursor after token and Space
this._deltaColumn = startToken.length + 1;
}
}
this._selectionId = builder.trackSelection(s);
for (var _i = 0, ops_1 = ops; _i < ops_1.length; _i++) {
var op = ops_1[_i];
builder.addEditOperation(op.range, op.text);
}
};
LineCommentCommand.prototype.getEditOperations = function (model, builder) {
var s = this._selection;
this._moveEndPositionDown = false;
if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
this._moveEndPositionDown = true;
s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
}
var data = LineCommentCommand._gatherPreflightData(this._type, this._insertSpace, model, s.startLineNumber, s.endLineNumber);
if (data.supported) {
return this._executeLineComments(model, builder, data, s);
}
return this._executeBlockComment(model, builder, s);
};
LineCommentCommand.prototype.computeCursorState = function (model, helper) {
var result = helper.getTrackedSelection(this._selectionId);
if (this._moveEndPositionDown) {
result = result.setEndPosition(result.endLineNumber + 1, 1);
}
return new selection_1.Selection(result.selectionStartLineNumber, result.selectionStartColumn + this._deltaColumn, result.positionLineNumber, result.positionColumn + this._deltaColumn);
};
/**
* Generate edit operations in the remove line comment case
*/
LineCommentCommand._createRemoveLineCommentsOperations = function (lines, startLineNumber) {
var res = [];
for (var i = 0, len = lines.length; i < len; i++) {
var lineData = lines[i];
if (lineData.ignore) {
continue;
}
res.push(editOperation_1.EditOperation.delete(new range_1.Range(startLineNumber + i, lineData.commentStrOffset + 1, startLineNumber + i, lineData.commentStrOffset + lineData.commentStrLength + 1)));
}
return res;
};
/**
* Generate edit operations in the add line comment case
*/
LineCommentCommand.prototype._createAddLineCommentsOperations = function (lines, startLineNumber) {
var res = [];
var afterCommentStr = this._insertSpace ? ' ' : '';
for (var i = 0, len = lines.length; i < len; i++) {
var lineData = lines[i];
if (lineData.ignore) {
continue;
}
res.push(editOperation_1.EditOperation.insert(new position_1.Position(startLineNumber + i, lineData.commentStrOffset + 1), lineData.commentStr + afterCommentStr));
}
return res;
};
LineCommentCommand.nextVisibleColumn = function (currentVisibleColumn, tabSize, isTab, columnSize) {
if (isTab) {
return currentVisibleColumn + (tabSize - (currentVisibleColumn % tabSize));
}
return currentVisibleColumn + columnSize;
};
/**
* Adjust insertion points to have them vertically aligned in the add line comment case
*/
LineCommentCommand._normalizeInsertionPoint = function (model, lines, startLineNumber, tabSize) {
var minVisibleColumn = 1073741824 /* MAX_SAFE_SMALL_INTEGER */;
var j;
var lenJ;
for (var i = 0, len = lines.length; i < len; i++) {
if (lines[i].ignore) {
continue;
}
var lineContent = model.getLineContent(startLineNumber + i);
var currentVisibleColumn = 0;
for (var j_1 = 0, lenJ_1 = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j_1 < lenJ_1; j_1++) {
currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j_1) === 9 /* Tab */, 1);
}
if (currentVisibleColumn < minVisibleColumn) {
minVisibleColumn = currentVisibleColumn;
}
}
minVisibleColumn = Math.floor(minVisibleColumn / tabSize) * tabSize;
for (var i = 0, len = lines.length; i < len; i++) {
if (lines[i].ignore) {
continue;
}
var lineContent = model.getLineContent(startLineNumber + i);
var currentVisibleColumn = 0;
for (j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) {
currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j) === 9 /* Tab */, 1);
}
if (currentVisibleColumn > minVisibleColumn) {
lines[i].commentStrOffset = j - 1;
}
else {
lines[i].commentStrOffset = j;
}
}
};
return LineCommentCommand;
}());
exports.LineCommentCommand = LineCommentCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[377/*vs/editor/contrib/dnd/dragAndDropCommand*/], __M([0/*require*/,1/*exports*/,22/*vs/editor/common/core/selection*/,3/*vs/editor/common/core/range*/]), function (require, exports, selection_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DragAndDropCommand = /** @class */ (function () {
function DragAndDropCommand(selection, targetPosition, copy) {
this.selection = selection;
this.targetPosition = targetPosition;
this.copy = copy;
this.targetSelection = null;
}
DragAndDropCommand.prototype.getEditOperations = function (model, builder) {
var text = model.getValueInRange(this.selection);
if (!this.copy) {
builder.addEditOperation(this.selection, null);
}
builder.addEditOperation(new range_1.Range(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column), text);
if (this.selection.containsPosition(this.targetPosition) && !(this.copy && (this.selection.getEndPosition().equals(this.targetPosition) || this.selection.getStartPosition().equals(this.targetPosition)) // we allow users to paste content beside the selection
)) {
this.targetSelection = this.selection;
return;
}
if (this.copy) {
this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber, this.targetPosition.column, this.selection.endLineNumber - this.selection.startLineNumber + this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
this.targetPosition.column + this.selection.endColumn - this.selection.startColumn :
this.selection.endColumn);
return;
}
if (this.targetPosition.lineNumber > this.selection.endLineNumber) {
// Drag the selection downwards
this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
this.targetPosition.column + this.selection.endColumn - this.selection.startColumn :
this.selection.endColumn);
return;
}
if (this.targetPosition.lineNumber < this.selection.endLineNumber) {
// Drag the selection upwards
this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber + this.selection.endLineNumber - this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
this.targetPosition.column + this.selection.endColumn - this.selection.startColumn :
this.selection.endColumn);
return;
}
// The target position is at the same line as the selection's end position.
if (this.selection.endColumn <= this.targetPosition.column) {
// The target position is after the selection's end position
this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
this.targetPosition.column - this.selection.endColumn + this.selection.startColumn :
this.targetPosition.column - this.selection.endColumn + this.selection.startColumn, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
this.targetPosition.column :
this.selection.endColumn);
}
else {
// The target position is before the selection's end position. Since the selection doesn't contain the target position, the selection is one-line and target position is before this selection.
this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column + this.selection.endColumn - this.selection.startColumn);
}
};
DragAndDropCommand.prototype.computeCursorState = function (model, helper) {
return this.targetSelection;
};
return DragAndDropCommand;
}());
exports.DragAndDropCommand = DragAndDropCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[378/*vs/editor/contrib/find/findState*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/]), function (require, exports, event_1, lifecycle_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function effectiveOptionValue(override, value) {
if (override === 1 /* True */) {
return true;
}
if (override === 2 /* False */) {
return false;
}
return value;
}
var FindReplaceState = /** @class */ (function (_super) {
__extends(FindReplaceState, _super);
function FindReplaceState() {
var _this = _super.call(this) || this;
_this._onFindReplaceStateChange = _this._register(new event_1.Emitter());
_this.onFindReplaceStateChange = _this._onFindReplaceStateChange.event;
_this._searchString = '';
_this._replaceString = '';
_this._isRevealed = false;
_this._isReplaceRevealed = false;
_this._isRegex = false;
_this._isRegexOverride = 0 /* NotSet */;
_this._wholeWord = false;
_this._wholeWordOverride = 0 /* NotSet */;
_this._matchCase = false;
_this._matchCaseOverride = 0 /* NotSet */;
_this._preserveCase = false;
_this._preserveCaseOverride = 0 /* NotSet */;
_this._searchScope = null;
_this._matchesPosition = 0;
_this._matchesCount = 0;
_this._currentMatch = null;
return _this;
}
Object.defineProperty(FindReplaceState.prototype, "searchString", {
get: function () { return this._searchString; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "replaceString", {
get: function () { return this._replaceString; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "isRevealed", {
get: function () { return this._isRevealed; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "isReplaceRevealed", {
get: function () { return this._isReplaceRevealed; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "isRegex", {
get: function () { return effectiveOptionValue(this._isRegexOverride, this._isRegex); },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "wholeWord", {
get: function () { return effectiveOptionValue(this._wholeWordOverride, this._wholeWord); },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "matchCase", {
get: function () { return effectiveOptionValue(this._matchCaseOverride, this._matchCase); },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "preserveCase", {
get: function () { return effectiveOptionValue(this._preserveCaseOverride, this._preserveCase); },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "actualIsRegex", {
get: function () { return this._isRegex; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "actualWholeWord", {
get: function () { return this._wholeWord; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "actualMatchCase", {
get: function () { return this._matchCase; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "actualPreserveCase", {
get: function () { return this._preserveCase; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "searchScope", {
get: function () { return this._searchScope; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "matchesPosition", {
get: function () { return this._matchesPosition; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "matchesCount", {
get: function () { return this._matchesCount; },
enumerable: true,
configurable: true
});
Object.defineProperty(FindReplaceState.prototype, "currentMatch", {
get: function () { return this._currentMatch; },
enumerable: true,
configurable: true
});
FindReplaceState.prototype.changeMatchInfo = function (matchesPosition, matchesCount, currentMatch) {
var changeEvent = {
moveCursor: false,
updateHistory: false,
searchString: false,
replaceString: false,
isRevealed: false,
isReplaceRevealed: false,
isRegex: false,
wholeWord: false,
matchCase: false,
preserveCase: false,
searchScope: false,
matchesPosition: false,
matchesCount: false,
currentMatch: false
};
var somethingChanged = false;
if (matchesCount === 0) {
matchesPosition = 0;
}
if (matchesPosition > matchesCount) {
matchesPosition = matchesCount;
}
if (this._matchesPosition !== matchesPosition) {
this._matchesPosition = matchesPosition;
changeEvent.matchesPosition = true;
somethingChanged = true;
}
if (this._matchesCount !== matchesCount) {
this._matchesCount = matchesCount;
changeEvent.matchesCount = true;
somethingChanged = true;
}
if (typeof currentMatch !== 'undefined') {
if (!range_1.Range.equalsRange(this._currentMatch, currentMatch)) {
this._currentMatch = currentMatch;
changeEvent.currentMatch = true;
somethingChanged = true;
}
}
if (somethingChanged) {
this._onFindReplaceStateChange.fire(changeEvent);
}
};
FindReplaceState.prototype.change = function (newState, moveCursor, updateHistory) {
if (updateHistory === void 0) { updateHistory = true; }
var changeEvent = {
moveCursor: moveCursor,
updateHistory: updateHistory,
searchString: false,
replaceString: false,
isRevealed: false,
isReplaceRevealed: false,
isRegex: false,
wholeWord: false,
matchCase: false,
preserveCase: false,
searchScope: false,
matchesPosition: false,
matchesCount: false,
currentMatch: false
};
var somethingChanged = false;
var oldEffectiveIsRegex = this.isRegex;
var oldEffectiveWholeWords = this.wholeWord;
var oldEffectiveMatchCase = this.matchCase;
var oldEffectivePreserveCase = this.preserveCase;
if (typeof newState.searchString !== 'undefined') {
if (this._searchString !== newState.searchString) {
this._searchString = newState.searchString;
changeEvent.searchString = true;
somethingChanged = true;
}
}
if (typeof newState.replaceString !== 'undefined') {
if (this._replaceString !== newState.replaceString) {
this._replaceString = newState.replaceString;
changeEvent.replaceString = true;
somethingChanged = true;
}
}
if (typeof newState.isRevealed !== 'undefined') {
if (this._isRevealed !== newState.isRevealed) {
this._isRevealed = newState.isRevealed;
changeEvent.isRevealed = true;
somethingChanged = true;
}
}
if (typeof newState.isReplaceRevealed !== 'undefined') {
if (this._isReplaceRevealed !== newState.isReplaceRevealed) {
this._isReplaceRevealed = newState.isReplaceRevealed;
changeEvent.isReplaceRevealed = true;
somethingChanged = true;
}
}
if (typeof newState.isRegex !== 'undefined') {
this._isRegex = newState.isRegex;
}
if (typeof newState.wholeWord !== 'undefined') {
this._wholeWord = newState.wholeWord;
}
if (typeof newState.matchCase !== 'undefined') {
this._matchCase = newState.matchCase;
}
if (typeof newState.preserveCase !== 'undefined') {
this._preserveCase = newState.preserveCase;
}
if (typeof newState.searchScope !== 'undefined') {
if (!range_1.Range.equalsRange(this._searchScope, newState.searchScope)) {
this._searchScope = newState.searchScope;
changeEvent.searchScope = true;
somethingChanged = true;
}
}
// Overrides get set when they explicitly come in and get reset anytime something else changes
this._isRegexOverride = (typeof newState.isRegexOverride !== 'undefined' ? newState.isRegexOverride : 0 /* NotSet */);
this._wholeWordOverride = (typeof newState.wholeWordOverride !== 'undefined' ? newState.wholeWordOverride : 0 /* NotSet */);
this._matchCaseOverride = (typeof newState.matchCaseOverride !== 'undefined' ? newState.matchCaseOverride : 0 /* NotSet */);
this._preserveCaseOverride = (typeof newState.preserveCaseOverride !== 'undefined' ? newState.preserveCaseOverride : 0 /* NotSet */);
if (oldEffectiveIsRegex !== this.isRegex) {
somethingChanged = true;
changeEvent.isRegex = true;
}
if (oldEffectiveWholeWords !== this.wholeWord) {
somethingChanged = true;
changeEvent.wholeWord = true;
}
if (oldEffectiveMatchCase !== this.matchCase) {
somethingChanged = true;
changeEvent.matchCase = true;
}
if (oldEffectivePreserveCase !== this.preserveCase) {
somethingChanged = true;
changeEvent.preserveCase = true;
}
if (somethingChanged) {
this._onFindReplaceStateChange.fire(changeEvent);
}
};
return FindReplaceState;
}(lifecycle_1.Disposable));
exports.FindReplaceState = FindReplaceState;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[379/*vs/editor/contrib/find/replaceAllCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ReplaceAllCommand = /** @class */ (function () {
function ReplaceAllCommand(editorSelection, ranges, replaceStrings) {
this._editorSelection = editorSelection;
this._ranges = ranges;
this._replaceStrings = replaceStrings;
this._trackedEditorSelectionId = null;
}
ReplaceAllCommand.prototype.getEditOperations = function (model, builder) {
if (this._ranges.length > 0) {
// Collect all edit operations
var ops = [];
for (var i = 0; i < this._ranges.length; i++) {
ops.push({
range: this._ranges[i],
text: this._replaceStrings[i]
});
}
// Sort them in ascending order by range starts
ops.sort(function (o1, o2) {
return range_1.Range.compareRangesUsingStarts(o1.range, o2.range);
});
// Merge operations that touch each other
var resultOps = [];
var previousOp = ops[0];
for (var i = 1; i < ops.length; i++) {
if (previousOp.range.endLineNumber === ops[i].range.startLineNumber && previousOp.range.endColumn === ops[i].range.startColumn) {
// These operations are one after another and can be merged
previousOp.range = previousOp.range.plusRange(ops[i].range);
previousOp.text = previousOp.text + ops[i].text;
}
else {
resultOps.push(previousOp);
previousOp = ops[i];
}
}
resultOps.push(previousOp);
for (var _i = 0, resultOps_1 = resultOps; _i < resultOps_1.length; _i++) {
var op = resultOps_1[_i];
builder.addEditOperation(op.range, op.text);
}
}
this._trackedEditorSelectionId = builder.trackSelection(this._editorSelection);
};
ReplaceAllCommand.prototype.computeCursorState = function (model, helper) {
return helper.getTrackedSelection(this._trackedEditorSelectionId);
};
return ReplaceAllCommand;
}());
exports.ReplaceAllCommand = ReplaceAllCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[380/*vs/editor/contrib/find/replacePattern*/], __M([0/*require*/,1/*exports*/,247/*vs/base/common/search*/]), function (require, exports, search_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Assigned when the replace pattern is entirely static.
*/
var StaticValueReplacePattern = /** @class */ (function () {
function StaticValueReplacePattern(staticValue) {
this.staticValue = staticValue;
this.kind = 0 /* StaticValue */;
}
return StaticValueReplacePattern;
}());
/**
* Assigned when the replace pattern has replacemend patterns.
*/
var DynamicPiecesReplacePattern = /** @class */ (function () {
function DynamicPiecesReplacePattern(pieces) {
this.pieces = pieces;
this.kind = 1 /* DynamicPieces */;
}
return DynamicPiecesReplacePattern;
}());
var ReplacePattern = /** @class */ (function () {
function ReplacePattern(pieces) {
if (!pieces || pieces.length === 0) {
this._state = new StaticValueReplacePattern('');
}
else if (pieces.length === 1 && pieces[0].staticValue !== null) {
this._state = new StaticValueReplacePattern(pieces[0].staticValue);
}
else {
this._state = new DynamicPiecesReplacePattern(pieces);
}
}
ReplacePattern.fromStaticValue = function (value) {
return new ReplacePattern([ReplacePiece.staticValue(value)]);
};
Object.defineProperty(ReplacePattern.prototype, "hasReplacementPatterns", {
get: function () {
return (this._state.kind === 1 /* DynamicPieces */);
},
enumerable: true,
configurable: true
});
ReplacePattern.prototype.buildReplaceString = function (matches, preserveCase) {
if (this._state.kind === 0 /* StaticValue */) {
if (preserveCase) {
return search_1.buildReplaceStringWithCasePreserved(matches, this._state.staticValue);
}
else {
return this._state.staticValue;
}
}
var result = '';
for (var i = 0, len = this._state.pieces.length; i < len; i++) {
var piece = this._state.pieces[i];
if (piece.staticValue !== null) {
// static value ReplacePiece
result += piece.staticValue;
continue;
}
// match index ReplacePiece
result += ReplacePattern._substitute(piece.matchIndex, matches);
}
return result;
};
ReplacePattern._substitute = function (matchIndex, matches) {
if (matches === null) {
return '';
}
if (matchIndex === 0) {
return matches[0];
}
var remainder = '';
while (matchIndex > 0) {
if (matchIndex < matches.length) {
// A match can be undefined
var match = (matches[matchIndex] || '');
return match + remainder;
}
remainder = String(matchIndex % 10) + remainder;
matchIndex = Math.floor(matchIndex / 10);
}
return '$' + remainder;
};
return ReplacePattern;
}());
exports.ReplacePattern = ReplacePattern;
/**
* A replace piece can either be a static string or an index to a specific match.
*/
var ReplacePiece = /** @class */ (function () {
function ReplacePiece(staticValue, matchIndex) {
this.staticValue = staticValue;
this.matchIndex = matchIndex;
}
ReplacePiece.staticValue = function (value) {
return new ReplacePiece(value, -1);
};
ReplacePiece.matchIndex = function (index) {
return new ReplacePiece(null, index);
};
return ReplacePiece;
}());
exports.ReplacePiece = ReplacePiece;
var ReplacePieceBuilder = /** @class */ (function () {
function ReplacePieceBuilder(source) {
this._source = source;
this._lastCharIndex = 0;
this._result = [];
this._resultLen = 0;
this._currentStaticPiece = '';
}
ReplacePieceBuilder.prototype.emitUnchanged = function (toCharIndex) {
this._emitStatic(this._source.substring(this._lastCharIndex, toCharIndex));
this._lastCharIndex = toCharIndex;
};
ReplacePieceBuilder.prototype.emitStatic = function (value, toCharIndex) {
this._emitStatic(value);
this._lastCharIndex = toCharIndex;
};
ReplacePieceBuilder.prototype._emitStatic = function (value) {
if (value.length === 0) {
return;
}
this._currentStaticPiece += value;
};
ReplacePieceBuilder.prototype.emitMatchIndex = function (index, toCharIndex) {
if (this._currentStaticPiece.length !== 0) {
this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
this._currentStaticPiece = '';
}
this._result[this._resultLen++] = ReplacePiece.matchIndex(index);
this._lastCharIndex = toCharIndex;
};
ReplacePieceBuilder.prototype.finalize = function () {
this.emitUnchanged(this._source.length);
if (this._currentStaticPiece.length !== 0) {
this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
this._currentStaticPiece = '';
}
return new ReplacePattern(this._result);
};
return ReplacePieceBuilder;
}());
/**
* \n => inserts a LF
* \t => inserts a TAB
* \\ => inserts a "\".
* $$ => inserts a "$".
* $& and $0 => inserts the matched substring.
* $n => Where n is a non-negative integer lesser than 100, inserts the nth parenthesized submatch string
* everything else stays untouched
*
* Also see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter
*/
function parseReplaceString(replaceString) {
if (!replaceString || replaceString.length === 0) {
return new ReplacePattern(null);
}
var result = new ReplacePieceBuilder(replaceString);
for (var i = 0, len = replaceString.length; i < len; i++) {
var chCode = replaceString.charCodeAt(i);
if (chCode === 92 /* Backslash */) {
// move to next char
i++;
if (i >= len) {
// string ends with a \
break;
}
var nextChCode = replaceString.charCodeAt(i);
// let replaceWithCharacter: string | null = null;
switch (nextChCode) {
case 92 /* Backslash */:
// \\ => inserts a "\"
result.emitUnchanged(i - 1);
result.emitStatic('\\', i + 1);
break;
case 110 /* n */:
// \n => inserts a LF
result.emitUnchanged(i - 1);
result.emitStatic('\n', i + 1);
break;
case 116 /* t */:
// \t => inserts a TAB
result.emitUnchanged(i - 1);
result.emitStatic('\t', i + 1);
break;
}
continue;
}
if (chCode === 36 /* DollarSign */) {
// move to next char
i++;
if (i >= len) {
// string ends with a $
break;
}
var nextChCode = replaceString.charCodeAt(i);
if (nextChCode === 36 /* DollarSign */) {
// $$ => inserts a "$"
result.emitUnchanged(i - 1);
result.emitStatic('$', i + 1);
continue;
}
if (nextChCode === 48 /* Digit0 */ || nextChCode === 38 /* Ampersand */) {
// $& and $0 => inserts the matched substring.
result.emitUnchanged(i - 1);
result.emitMatchIndex(0, i + 1);
continue;
}
if (49 /* Digit1 */ <= nextChCode && nextChCode <= 57 /* Digit9 */) {
// $n
var matchIndex = nextChCode - 48 /* Digit0 */;
// peek next char to probe for $nn
if (i + 1 < len) {
var nextNextChCode = replaceString.charCodeAt(i + 1);
if (48 /* Digit0 */ <= nextNextChCode && nextNextChCode <= 57 /* Digit9 */) {
// $nn
// move to next char
i++;
matchIndex = matchIndex * 10 + (nextNextChCode - 48 /* Digit0 */);
result.emitUnchanged(i - 2);
result.emitMatchIndex(matchIndex, i + 1);
continue;
}
}
result.emitUnchanged(i - 1);
result.emitMatchIndex(matchIndex, i + 1);
continue;
}
}
}
return result.finalize();
}
exports.parseReplaceString = parseReplaceString;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[150/*vs/editor/contrib/folding/foldingRanges*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MAX_FOLDING_REGIONS = 0xFFFF;
exports.MAX_LINE_NUMBER = 0xFFFFFF;
var MASK_INDENT = 0xFF000000;
var FoldingRegions = /** @class */ (function () {
function FoldingRegions(startIndexes, endIndexes, types) {
if (startIndexes.length !== endIndexes.length || startIndexes.length > exports.MAX_FOLDING_REGIONS) {
throw new Error('invalid startIndexes or endIndexes size');
}
this._startIndexes = startIndexes;
this._endIndexes = endIndexes;
this._collapseStates = new Uint32Array(Math.ceil(startIndexes.length / 32));
this._types = types;
this._parentsComputed = false;
}
FoldingRegions.prototype.ensureParentIndices = function () {
var _this = this;
if (!this._parentsComputed) {
this._parentsComputed = true;
var parentIndexes_1 = [];
var isInsideLast = function (startLineNumber, endLineNumber) {
var index = parentIndexes_1[parentIndexes_1.length - 1];
return _this.getStartLineNumber(index) <= startLineNumber && _this.getEndLineNumber(index) >= endLineNumber;
};
for (var i = 0, len = this._startIndexes.length; i < len; i++) {
var startLineNumber = this._startIndexes[i];
var endLineNumber = this._endIndexes[i];
if (startLineNumber > exports.MAX_LINE_NUMBER || endLineNumber > exports.MAX_LINE_NUMBER) {
throw new Error('startLineNumber or endLineNumber must not exceed ' + exports.MAX_LINE_NUMBER);
}
while (parentIndexes_1.length > 0 && !isInsideLast(startLineNumber, endLineNumber)) {
parentIndexes_1.pop();
}
var parentIndex = parentIndexes_1.length > 0 ? parentIndexes_1[parentIndexes_1.length - 1] : -1;
parentIndexes_1.push(i);
this._startIndexes[i] = startLineNumber + ((parentIndex & 0xFF) << 24);
this._endIndexes[i] = endLineNumber + ((parentIndex & 0xFF00) << 16);
}
}
};
Object.defineProperty(FoldingRegions.prototype, "length", {
get: function () {
return this._startIndexes.length;
},
enumerable: true,
configurable: true
});
FoldingRegions.prototype.getStartLineNumber = function (index) {
return this._startIndexes[index] & exports.MAX_LINE_NUMBER;
};
FoldingRegions.prototype.getEndLineNumber = function (index) {
return this._endIndexes[index] & exports.MAX_LINE_NUMBER;
};
FoldingRegions.prototype.getType = function (index) {
return this._types ? this._types[index] : undefined;
};
FoldingRegions.prototype.hasTypes = function () {
return !!this._types;
};
FoldingRegions.prototype.isCollapsed = function (index) {
var arrayIndex = (index / 32) | 0;
var bit = index % 32;
return (this._collapseStates[arrayIndex] & (1 << bit)) !== 0;
};
FoldingRegions.prototype.setCollapsed = function (index, newState) {
var arrayIndex = (index / 32) | 0;
var bit = index % 32;
var value = this._collapseStates[arrayIndex];
if (newState) {
this._collapseStates[arrayIndex] = value | (1 << bit);
}
else {
this._collapseStates[arrayIndex] = value & ~(1 << bit);
}
};
FoldingRegions.prototype.toRegion = function (index) {
return new FoldingRegion(this, index);
};
FoldingRegions.prototype.getParentIndex = function (index) {
this.ensureParentIndices();
var parent = ((this._startIndexes[index] & MASK_INDENT) >>> 24) + ((this._endIndexes[index] & MASK_INDENT) >>> 16);
if (parent === exports.MAX_FOLDING_REGIONS) {
return -1;
}
return parent;
};
FoldingRegions.prototype.contains = function (index, line) {
return this.getStartLineNumber(index) <= line && this.getEndLineNumber(index) >= line;
};
FoldingRegions.prototype.findIndex = function (line) {
var low = 0, high = this._startIndexes.length;
if (high === 0) {
return -1; // no children
}
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (line < this.getStartLineNumber(mid)) {
high = mid;
}
else {
low = mid + 1;
}
}
return low - 1;
};
FoldingRegions.prototype.findRange = function (line) {
var index = this.findIndex(line);
if (index >= 0) {
var endLineNumber = this.getEndLineNumber(index);
if (endLineNumber >= line) {
return index;
}
index = this.getParentIndex(index);
while (index !== -1) {
if (this.contains(index, line)) {
return index;
}
index = this.getParentIndex(index);
}
}
return -1;
};
FoldingRegions.prototype.toString = function () {
var res = [];
for (var i = 0; i < this.length; i++) {
res[i] = "[" + (this.isCollapsed(i) ? '+' : '-') + "] " + this.getStartLineNumber(i) + "/" + this.getEndLineNumber(i);
}
return res.join(', ');
};
return FoldingRegions;
}());
exports.FoldingRegions = FoldingRegions;
var FoldingRegion = /** @class */ (function () {
function FoldingRegion(ranges, index) {
this.ranges = ranges;
this.index = index;
}
Object.defineProperty(FoldingRegion.prototype, "startLineNumber", {
get: function () {
return this.ranges.getStartLineNumber(this.index);
},
enumerable: true,
configurable: true
});
Object.defineProperty(FoldingRegion.prototype, "endLineNumber", {
get: function () {
return this.ranges.getEndLineNumber(this.index);
},
enumerable: true,
configurable: true
});
Object.defineProperty(FoldingRegion.prototype, "regionIndex", {
get: function () {
return this.index;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FoldingRegion.prototype, "parentIndex", {
get: function () {
return this.ranges.getParentIndex(this.index);
},
enumerable: true,
configurable: true
});
Object.defineProperty(FoldingRegion.prototype, "isCollapsed", {
get: function () {
return this.ranges.isCollapsed(this.index);
},
enumerable: true,
configurable: true
});
FoldingRegion.prototype.containedBy = function (range) {
return range.startLineNumber <= this.startLineNumber && range.endLineNumber >= this.endLineNumber;
};
FoldingRegion.prototype.containsLine = function (lineNumber) {
return this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber;
};
return FoldingRegion;
}());
exports.FoldingRegion = FoldingRegion;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[381/*vs/editor/contrib/folding/foldingModel*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,150/*vs/editor/contrib/folding/foldingRanges*/]), function (require, exports, event_1, foldingRanges_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FoldingModel = /** @class */ (function () {
function FoldingModel(textModel, decorationProvider) {
this._updateEventEmitter = new event_1.Emitter();
this.onDidChange = this._updateEventEmitter.event;
this._textModel = textModel;
this._decorationProvider = decorationProvider;
this._regions = new foldingRanges_1.FoldingRegions(new Uint32Array(0), new Uint32Array(0));
this._editorDecorationIds = [];
this._isInitialized = false;
}
Object.defineProperty(FoldingModel.prototype, "regions", {
get: function () { return this._regions; },
enumerable: true,
configurable: true
});
Object.defineProperty(FoldingModel.prototype, "textModel", {
get: function () { return this._textModel; },
enumerable: true,
configurable: true
});
Object.defineProperty(FoldingModel.prototype, "isInitialized", {
get: function () { return this._isInitialized; },
enumerable: true,
configurable: true
});
FoldingModel.prototype.toggleCollapseState = function (regions) {
var _this = this;
if (!regions.length) {
return;
}
var processed = {};
this._decorationProvider.changeDecorations(function (accessor) {
for (var _i = 0, regions_1 = regions; _i < regions_1.length; _i++) {
var region = regions_1[_i];
var index = region.regionIndex;
var editorDecorationId = _this._editorDecorationIds[index];
if (editorDecorationId && !processed[editorDecorationId]) {
processed[editorDecorationId] = true;
var newCollapseState = !_this._regions.isCollapsed(index);
_this._regions.setCollapsed(index, newCollapseState);
accessor.changeDecorationOptions(editorDecorationId, _this._decorationProvider.getDecorationOption(newCollapseState));
}
}
});
this._updateEventEmitter.fire({ model: this, collapseStateChanged: regions });
};
FoldingModel.prototype.update = function (newRegions, blockedLineNumers) {
var _this = this;
if (blockedLineNumers === void 0) { blockedLineNumers = []; }
var newEditorDecorations = [];
var isBlocked = function (startLineNumber, endLineNumber) {
for (var _i = 0, blockedLineNumers_1 = blockedLineNumers; _i < blockedLineNumers_1.length; _i++) {
var blockedLineNumber = blockedLineNumers_1[_i];
if (startLineNumber < blockedLineNumber && blockedLineNumber <= endLineNumber) { // first line is visible
return true;
}
}
return false;
};
var initRange = function (index, isCollapsed) {
var startLineNumber = newRegions.getStartLineNumber(index);
if (isCollapsed && isBlocked(startLineNumber, newRegions.getEndLineNumber(index))) {
isCollapsed = false;
}
newRegions.setCollapsed(index, isCollapsed);
var maxColumn = _this._textModel.getLineMaxColumn(startLineNumber);
var decorationRange = {
startLineNumber: startLineNumber,
startColumn: maxColumn,
endLineNumber: startLineNumber,
endColumn: maxColumn
};
newEditorDecorations.push({ range: decorationRange, options: _this._decorationProvider.getDecorationOption(isCollapsed) });
};
var i = 0;
var nextCollapsed = function () {
while (i < _this._regions.length) {
var isCollapsed = _this._regions.isCollapsed(i);
i++;
if (isCollapsed) {
return i - 1;
}
}
return -1;
};
var k = 0;
var collapsedIndex = nextCollapsed();
while (collapsedIndex !== -1 && k < newRegions.length) {
// get the latest range
var decRange = this._textModel.getDecorationRange(this._editorDecorationIds[collapsedIndex]);
if (decRange) {
var collapsedStartLineNumber = decRange.startLineNumber;
if (this._textModel.getLineMaxColumn(collapsedStartLineNumber) === decRange.startColumn) { // test that the decoration is still at the end otherwise it got deleted
while (k < newRegions.length) {
var startLineNumber = newRegions.getStartLineNumber(k);
if (collapsedStartLineNumber >= startLineNumber) {
initRange(k, collapsedStartLineNumber === startLineNumber);
k++;
}
else {
break;
}
}
}
}
collapsedIndex = nextCollapsed();
}
while (k < newRegions.length) {
initRange(k, false);
k++;
}
this._editorDecorationIds = this._decorationProvider.deltaDecorations(this._editorDecorationIds, newEditorDecorations);
this._regions = newRegions;
this._isInitialized = true;
this._updateEventEmitter.fire({ model: this });
};
/**
* Collapse state memento, for persistence only
*/
FoldingModel.prototype.getMemento = function () {
var collapsedRanges = [];
for (var i = 0; i < this._regions.length; i++) {
if (this._regions.isCollapsed(i)) {
var range = this._textModel.getDecorationRange(this._editorDecorationIds[i]);
if (range) {
var startLineNumber = range.startLineNumber;
var endLineNumber = range.endLineNumber + this._regions.getEndLineNumber(i) - this._regions.getStartLineNumber(i);
collapsedRanges.push({ startLineNumber: startLineNumber, endLineNumber: endLineNumber });
}
}
}
if (collapsedRanges.length > 0) {
return collapsedRanges;
}
return undefined;
};
/**
* Apply persisted state, for persistence only
*/
FoldingModel.prototype.applyMemento = function (state) {
if (!Array.isArray(state)) {
return;
}
var toToogle = [];
for (var _i = 0, state_1 = state; _i < state_1.length; _i++) {
var range = state_1[_i];
var region = this.getRegionAtLine(range.startLineNumber);
if (region && !region.isCollapsed) {
toToogle.push(region);
}
}
this.toggleCollapseState(toToogle);
};
FoldingModel.prototype.dispose = function () {
this._decorationProvider.deltaDecorations(this._editorDecorationIds, []);
};
FoldingModel.prototype.getAllRegionsAtLine = function (lineNumber, filter) {
var result = [];
if (this._regions) {
var index = this._regions.findRange(lineNumber);
var level = 1;
while (index >= 0) {
var current = this._regions.toRegion(index);
if (!filter || filter(current, level)) {
result.push(current);
}
level++;
index = current.parentIndex;
}
}
return result;
};
FoldingModel.prototype.getRegionAtLine = function (lineNumber) {
if (this._regions) {
var index = this._regions.findRange(lineNumber);
if (index >= 0) {
return this._regions.toRegion(index);
}
}
return null;
};
FoldingModel.prototype.getRegionsInside = function (region, filter) {
var result = [];
var index = region ? region.regionIndex + 1 : 0;
var endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE;
if (filter && filter.length === 2) {
var levelStack = [];
for (var i = index, len = this._regions.length; i < len; i++) {
var current = this._regions.toRegion(i);
if (this._regions.getStartLineNumber(i) < endLineNumber) {
while (levelStack.length > 0 && !current.containedBy(levelStack[levelStack.length - 1])) {
levelStack.pop();
}
levelStack.push(current);
if (filter(current, levelStack.length)) {
result.push(current);
}
}
else {
break;
}
}
}
else {
for (var i = index, len = this._regions.length; i < len; i++) {
var current = this._regions.toRegion(i);
if (this._regions.getStartLineNumber(i) < endLineNumber) {
if (!filter || filter(current)) {
result.push(current);
}
}
else {
break;
}
}
}
return result;
};
return FoldingModel;
}());
exports.FoldingModel = FoldingModel;
/**
* Collapse or expand the regions at the given locations
* @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
* @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model.
*/
function toggleCollapseState(foldingModel, levels, lineNumbers) {
var toToggle = [];
var _loop_1 = function (lineNumber) {
var region = foldingModel.getRegionAtLine(lineNumber);
if (region) {
var doCollapse_1 = !region.isCollapsed;
toToggle.push(region);
if (levels > 1) {
var regionsInside = foldingModel.getRegionsInside(region, function (r, level) { return r.isCollapsed !== doCollapse_1 && level < levels; });
toToggle.push.apply(toToggle, regionsInside);
}
}
};
for (var _i = 0, lineNumbers_1 = lineNumbers; _i < lineNumbers_1.length; _i++) {
var lineNumber = lineNumbers_1[_i];
_loop_1(lineNumber);
}
foldingModel.toggleCollapseState(toToggle);
}
exports.toggleCollapseState = toggleCollapseState;
/**
* Collapse or expand the regions at the given locations including all children.
* @param doCollapse Wheter to collase or expand
* @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
* @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model.
*/
function setCollapseStateLevelsDown(foldingModel, doCollapse, levels, lineNumbers) {
if (levels === void 0) { levels = Number.MAX_VALUE; }
var toToggle = [];
if (lineNumbers && lineNumbers.length > 0) {
for (var _i = 0, lineNumbers_2 = lineNumbers; _i < lineNumbers_2.length; _i++) {
var lineNumber = lineNumbers_2[_i];
var region = foldingModel.getRegionAtLine(lineNumber);
if (region) {
if (region.isCollapsed !== doCollapse) {
toToggle.push(region);
}
if (levels > 1) {
var regionsInside = foldingModel.getRegionsInside(region, function (r, level) { return r.isCollapsed !== doCollapse && level < levels; });
toToggle.push.apply(toToggle, regionsInside);
}
}
}
}
else {
var regionsInside = foldingModel.getRegionsInside(null, function (r, level) { return r.isCollapsed !== doCollapse && level < levels; });
toToggle.push.apply(toToggle, regionsInside);
}
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateLevelsDown = setCollapseStateLevelsDown;
/**
* Collapse or expand the regions at the given locations including all parents.
* @param doCollapse Wheter to collase or expand
* @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
* @param lineNumbers the location of the regions to collapse or expand.
*/
function setCollapseStateLevelsUp(foldingModel, doCollapse, levels, lineNumbers) {
var toToggle = [];
for (var _i = 0, lineNumbers_3 = lineNumbers; _i < lineNumbers_3.length; _i++) {
var lineNumber = lineNumbers_3[_i];
var regions = foldingModel.getAllRegionsAtLine(lineNumber, function (region, level) { return region.isCollapsed !== doCollapse && level <= levels; });
toToggle.push.apply(toToggle, regions);
}
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateLevelsUp = setCollapseStateLevelsUp;
/**
* Collapse or expand a region at the given locations. If the inner most region is already collapsed/expanded, uses the first parent instead.
* @param doCollapse Wheter to collase or expand
* @param lineNumbers the location of the regions to collapse or expand.
*/
function setCollapseStateUp(foldingModel, doCollapse, lineNumbers) {
var toToggle = [];
for (var _i = 0, lineNumbers_4 = lineNumbers; _i < lineNumbers_4.length; _i++) {
var lineNumber = lineNumbers_4[_i];
var regions = foldingModel.getAllRegionsAtLine(lineNumber, function (region) { return region.isCollapsed !== doCollapse; });
if (regions.length > 0) {
toToggle.push(regions[0]);
}
}
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateUp = setCollapseStateUp;
/**
* Folds or unfolds all regions that have a given level, except if they contain one of the blocked lines.
* @param foldLevel level. Level == 1 is the top level
* @param doCollapse Wheter to collase or expand
*/
function setCollapseStateAtLevel(foldingModel, foldLevel, doCollapse, blockedLineNumbers) {
var filter = function (region, level) { return level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some(function (line) { return region.containsLine(line); }); };
var toToggle = foldingModel.getRegionsInside(null, filter);
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateAtLevel = setCollapseStateAtLevel;
/**
* Folds all regions for which the lines start with a given regex
* @param foldingModel the folding model
*/
function setCollapseStateForMatchingLines(foldingModel, regExp, doCollapse) {
var editorModel = foldingModel.textModel;
var regions = foldingModel.regions;
var toToggle = [];
for (var i = regions.length - 1; i >= 0; i--) {
if (doCollapse !== regions.isCollapsed(i)) {
var startLineNumber = regions.getStartLineNumber(i);
if (regExp.test(editorModel.getLineContent(startLineNumber))) {
toToggle.push(regions.toRegion(i));
}
}
}
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateForMatchingLines = setCollapseStateForMatchingLines;
/**
* Folds all regions of the given type
* @param foldingModel the folding model
*/
function setCollapseStateForType(foldingModel, type, doCollapse) {
var regions = foldingModel.regions;
var toToggle = [];
for (var i = regions.length - 1; i >= 0; i--) {
if (doCollapse !== regions.isCollapsed(i) && type === regions.getType(i)) {
toToggle.push(regions.toRegion(i));
}
}
foldingModel.toggleCollapseState(toToggle);
}
exports.setCollapseStateForType = setCollapseStateForType;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[382/*vs/editor/contrib/folding/hiddenRangeModel*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,3/*vs/editor/common/core/range*/,19/*vs/base/common/arrays*/]), function (require, exports, event_1, range_1, arrays_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var HiddenRangeModel = /** @class */ (function () {
function HiddenRangeModel(model) {
var _this = this;
this._updateEventEmitter = new event_1.Emitter();
this._foldingModel = model;
this._foldingModelListener = model.onDidChange(function (_) { return _this.updateHiddenRanges(); });
this._hiddenRanges = [];
if (model.regions.length) {
this.updateHiddenRanges();
}
}
Object.defineProperty(HiddenRangeModel.prototype, "onDidChange", {
get: function () { return this._updateEventEmitter.event; },
enumerable: true,
configurable: true
});
Object.defineProperty(HiddenRangeModel.prototype, "hiddenRanges", {
get: function () { return this._hiddenRanges; },
enumerable: true,
configurable: true
});
HiddenRangeModel.prototype.updateHiddenRanges = function () {
var updateHiddenAreas = false;
var newHiddenAreas = [];
var i = 0; // index into hidden
var k = 0;
var lastCollapsedStart = Number.MAX_VALUE;
var lastCollapsedEnd = -1;
var ranges = this._foldingModel.regions;
for (; i < ranges.length; i++) {
if (!ranges.isCollapsed(i)) {
continue;
}
var startLineNumber = ranges.getStartLineNumber(i) + 1; // the first line is not hidden
var endLineNumber = ranges.getEndLineNumber(i);
if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) {
// ignore ranges contained in collapsed regions
continue;
}
if (!updateHiddenAreas && k < this._hiddenRanges.length && this._hiddenRanges[k].startLineNumber === startLineNumber && this._hiddenRanges[k].endLineNumber === endLineNumber) {
// reuse the old ranges
newHiddenAreas.push(this._hiddenRanges[k]);
k++;
}
else {
updateHiddenAreas = true;
newHiddenAreas.push(new range_1.Range(startLineNumber, 1, endLineNumber, 1));
}
lastCollapsedStart = startLineNumber;
lastCollapsedEnd = endLineNumber;
}
if (updateHiddenAreas || k < this._hiddenRanges.length) {
this.applyHiddenRanges(newHiddenAreas);
}
};
HiddenRangeModel.prototype.applyMemento = function (state) {
if (!Array.isArray(state) || state.length === 0) {
return false;
}
var hiddenRanges = [];
for (var _i = 0, state_1 = state; _i < state_1.length; _i++) {
var r = state_1[_i];
if (!r.startLineNumber || !r.endLineNumber) {
return false;
}
hiddenRanges.push(new range_1.Range(r.startLineNumber + 1, 1, r.endLineNumber, 1));
}
this.applyHiddenRanges(hiddenRanges);
return true;
};
/**
* Collapse state memento, for persistence only, only used if folding model is not yet initialized
*/
HiddenRangeModel.prototype.getMemento = function () {
return this._hiddenRanges.map(function (r) { return ({ startLineNumber: r.startLineNumber - 1, endLineNumber: r.endLineNumber }); });
};
HiddenRangeModel.prototype.applyHiddenRanges = function (newHiddenAreas) {
this._hiddenRanges = newHiddenAreas;
this._updateEventEmitter.fire(newHiddenAreas);
};
HiddenRangeModel.prototype.hasRanges = function () {
return this._hiddenRanges.length > 0;
};
HiddenRangeModel.prototype.isHidden = function (line) {
return findRange(this._hiddenRanges, line) !== null;
};
HiddenRangeModel.prototype.adjustSelections = function (selections) {
var _this = this;
var hasChanges = false;
var editorModel = this._foldingModel.textModel;
var lastRange = null;
var adjustLine = function (line) {
if (!lastRange || !isInside(line, lastRange)) {
lastRange = findRange(_this._hiddenRanges, line);
}
if (lastRange) {
return lastRange.startLineNumber - 1;
}
return null;
};
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
var adjustedStartLine = adjustLine(selection.startLineNumber);
if (adjustedStartLine) {
selection = selection.setStartPosition(adjustedStartLine, editorModel.getLineMaxColumn(adjustedStartLine));
hasChanges = true;
}
var adjustedEndLine = adjustLine(selection.endLineNumber);
if (adjustedEndLine) {
selection = selection.setEndPosition(adjustedEndLine, editorModel.getLineMaxColumn(adjustedEndLine));
hasChanges = true;
}
selections[i] = selection;
}
return hasChanges;
};
HiddenRangeModel.prototype.dispose = function () {
if (this.hiddenRanges.length > 0) {
this._hiddenRanges = [];
this._updateEventEmitter.fire(this._hiddenRanges);
}
if (this._foldingModelListener) {
this._foldingModelListener.dispose();
this._foldingModelListener = null;
}
};
return HiddenRangeModel;
}());
exports.HiddenRangeModel = HiddenRangeModel;
function isInside(line, range) {
return line >= range.startLineNumber && line <= range.endLineNumber;
}
function findRange(ranges, line) {
var i = arrays_1.findFirstInSorted(ranges, function (r) { return line < r.startLineNumber; }) - 1;
if (i >= 0 && ranges[i].endLineNumber >= line) {
return ranges[i];
}
return null;
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[197/*vs/editor/contrib/folding/syntaxRangeProvider*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,150/*vs/editor/contrib/folding/foldingRanges*/]), function (require, exports, errors_1, foldingRanges_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MAX_FOLDING_REGIONS = 5000;
var foldingContext = {};
exports.ID_SYNTAX_PROVIDER = 'syntax';
var SyntaxRangeProvider = /** @class */ (function () {
function SyntaxRangeProvider(editorModel, providers, limit) {
if (limit === void 0) { limit = MAX_FOLDING_REGIONS; }
this.editorModel = editorModel;
this.providers = providers;
this.limit = limit;
this.id = exports.ID_SYNTAX_PROVIDER;
}
SyntaxRangeProvider.prototype.compute = function (cancellationToken) {
var _this = this;
return collectSyntaxRanges(this.providers, this.editorModel, cancellationToken).then(function (ranges) {
if (ranges) {
var res = sanitizeRanges(ranges, _this.limit);
return res;
}
return null;
});
};
SyntaxRangeProvider.prototype.dispose = function () {
};
return SyntaxRangeProvider;
}());
exports.SyntaxRangeProvider = SyntaxRangeProvider;
function collectSyntaxRanges(providers, model, cancellationToken) {
var rangeData = null;
var promises = providers.map(function (provider, i) {
return Promise.resolve(provider.provideFoldingRanges(model, foldingContext, cancellationToken)).then(function (ranges) {
if (cancellationToken.isCancellationRequested) {
return;
}
if (Array.isArray(ranges)) {
if (!Array.isArray(rangeData)) {
rangeData = [];
}
var nLines = model.getLineCount();
for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) {
var r = ranges_1[_i];
if (r.start > 0 && r.end > r.start && r.end <= nLines) {
rangeData.push({ start: r.start, end: r.end, rank: i, kind: r.kind });
}
}
}
}, errors_1.onUnexpectedExternalError);
});
return Promise.all(promises).then(function (_) {
return rangeData;
});
}
var RangesCollector = /** @class */ (function () {
function RangesCollector(foldingRangesLimit) {
this._startIndexes = [];
this._endIndexes = [];
this._nestingLevels = [];
this._nestingLevelCounts = [];
this._types = [];
this._length = 0;
this._foldingRangesLimit = foldingRangesLimit;
}
RangesCollector.prototype.add = function (startLineNumber, endLineNumber, type, nestingLevel) {
if (startLineNumber > foldingRanges_1.MAX_LINE_NUMBER || endLineNumber > foldingRanges_1.MAX_LINE_NUMBER) {
return;
}
var index = this._length;
this._startIndexes[index] = startLineNumber;
this._endIndexes[index] = endLineNumber;
this._nestingLevels[index] = nestingLevel;
this._types[index] = type;
this._length++;
if (nestingLevel < 30) {
this._nestingLevelCounts[nestingLevel] = (this._nestingLevelCounts[nestingLevel] || 0) + 1;
}
};
RangesCollector.prototype.toIndentRanges = function () {
if (this._length <= this._foldingRangesLimit) {
var startIndexes = new Uint32Array(this._length);
var endIndexes = new Uint32Array(this._length);
for (var i = 0; i < this._length; i++) {
startIndexes[i] = this._startIndexes[i];
endIndexes[i] = this._endIndexes[i];
}
return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes, this._types);
}
else {
var entries = 0;
var maxLevel = this._nestingLevelCounts.length;
for (var i = 0; i < this._nestingLevelCounts.length; i++) {
var n = this._nestingLevelCounts[i];
if (n) {
if (n + entries > this._foldingRangesLimit) {
maxLevel = i;
break;
}
entries += n;
}
}
var startIndexes = new Uint32Array(this._foldingRangesLimit);
var endIndexes = new Uint32Array(this._foldingRangesLimit);
var types = [];
for (var i = 0, k = 0; i < this._length; i++) {
var level = this._nestingLevels[i];
if (level < maxLevel || (level === maxLevel && entries++ < this._foldingRangesLimit)) {
startIndexes[k] = this._startIndexes[i];
endIndexes[k] = this._endIndexes[i];
types[k] = this._types[i];
k++;
}
}
return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes, types);
}
};
return RangesCollector;
}());
exports.RangesCollector = RangesCollector;
function sanitizeRanges(rangeData, limit) {
var sorted = rangeData.sort(function (d1, d2) {
var diff = d1.start - d2.start;
if (diff === 0) {
diff = d1.rank - d2.rank;
}
return diff;
});
var collector = new RangesCollector(limit);
var top = undefined;
var previous = [];
for (var _i = 0, sorted_1 = sorted; _i < sorted_1.length; _i++) {
var entry = sorted_1[_i];
if (!top) {
top = entry;
collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
}
else {
if (entry.start > top.start) {
if (entry.end <= top.end) {
previous.push(top);
top = entry;
collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
}
else {
if (entry.start > top.end) {
do {
top = previous.pop();
} while (top && entry.start > top.end);
if (top) {
previous.push(top);
}
top = entry;
}
collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
}
}
}
}
return collector.toIndentRanges();
}
exports.sanitizeRanges = sanitizeRanges;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[383/*vs/editor/contrib/folding/intializingRangeProvider*/], __M([0/*require*/,1/*exports*/,197/*vs/editor/contrib/folding/syntaxRangeProvider*/]), function (require, exports, syntaxRangeProvider_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ID_INIT_PROVIDER = 'init';
var InitializingRangeProvider = /** @class */ (function () {
function InitializingRangeProvider(editorModel, initialRanges, onTimeout, timeoutTime) {
this.editorModel = editorModel;
this.id = exports.ID_INIT_PROVIDER;
if (initialRanges.length) {
var toDecorationRange = function (range) {
return {
range: {
startLineNumber: range.startLineNumber,
startColumn: 0,
endLineNumber: range.endLineNumber,
endColumn: editorModel.getLineLength(range.endLineNumber)
},
options: {
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */
}
};
};
this.decorationIds = editorModel.deltaDecorations([], initialRanges.map(toDecorationRange));
this.timeout = setTimeout(onTimeout, timeoutTime);
}
}
InitializingRangeProvider.prototype.dispose = function () {
if (this.decorationIds) {
this.editorModel.deltaDecorations(this.decorationIds, []);
this.decorationIds = undefined;
}
if (typeof this.timeout === 'number') {
clearTimeout(this.timeout);
this.timeout = undefined;
}
};
InitializingRangeProvider.prototype.compute = function (cancelationToken) {
var foldingRangeData = [];
if (this.decorationIds) {
for (var _i = 0, _a = this.decorationIds; _i < _a.length; _i++) {
var id = _a[_i];
var range = this.editorModel.getDecorationRange(id);
if (range) {
foldingRangeData.push({ start: range.startLineNumber, end: range.endLineNumber, rank: 1 });
}
}
}
return Promise.resolve(syntaxRangeProvider_1.sanitizeRanges(foldingRangeData, Number.MAX_VALUE));
};
return InitializingRangeProvider;
}());
exports.InitializingRangeProvider = InitializingRangeProvider;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[198/*vs/editor/contrib/format/formattingEdit*/], __M([0/*require*/,1/*exports*/,58/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/]), function (require, exports, editOperation_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FormattingEdit = /** @class */ (function () {
function FormattingEdit() {
}
FormattingEdit._handleEolEdits = function (editor, edits) {
var newEol = undefined;
var singleEdits = [];
for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
var edit = edits_1[_i];
if (typeof edit.eol === 'number') {
newEol = edit.eol;
}
if (edit.range && typeof edit.text === 'string') {
singleEdits.push(edit);
}
}
if (typeof newEol === 'number') {
if (editor.hasModel()) {
editor.getModel().pushEOL(newEol);
}
}
return singleEdits;
};
FormattingEdit._isFullModelReplaceEdit = function (editor, edit) {
if (!editor.hasModel()) {
return false;
}
var model = editor.getModel();
var editRange = model.validateRange(edit.range);
var fullModelRange = model.getFullModelRange();
return fullModelRange.equalsRange(editRange);
};
FormattingEdit.execute = function (editor, _edits) {
editor.pushUndoStop();
var edits = FormattingEdit._handleEolEdits(editor, _edits);
if (edits.length === 1 && FormattingEdit._isFullModelReplaceEdit(editor, edits[0])) {
// We use replace semantics and hope that markers stay put...
editor.executeEdits('formatEditsCommand', edits.map(function (edit) { return editOperation_1.EditOperation.replace(range_1.Range.lift(edit.range), edit.text); }));
}
else {
editor.executeEdits('formatEditsCommand', edits.map(function (edit) { return editOperation_1.EditOperation.replaceMove(range_1.Range.lift(edit.range), edit.text); }));
}
editor.pushUndoStop();
};
return FormattingEdit;
}());
exports.FormattingEdit = FormattingEdit;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[199/*vs/editor/contrib/gotoSymbol/link/clickLinkGesture*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,16/*vs/base/common/platform*/]), function (require, exports, browser, lifecycle_1, event_1, platform) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function hasModifier(e, modifier) {
return !!e[modifier];
}
/**
* An event that encapsulates the various trigger modifiers logic needed for go to definition.
*/
var ClickLinkMouseEvent = /** @class */ (function () {
function ClickLinkMouseEvent(source, opts) {
this.target = source.target;
this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier);
this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier);
this.isNoneOrSingleMouseDown = (browser.isIE || source.event.detail <= 1); // IE does not support event.detail properly
}
return ClickLinkMouseEvent;
}());
exports.ClickLinkMouseEvent = ClickLinkMouseEvent;
/**
* An event that encapsulates the various trigger modifiers logic needed for go to definition.
*/
var ClickLinkKeyboardEvent = /** @class */ (function () {
function ClickLinkKeyboardEvent(source, opts) {
this.keyCodeIsTriggerKey = (source.keyCode === opts.triggerKey);
this.keyCodeIsSideBySideKey = (source.keyCode === opts.triggerSideBySideKey);
this.hasTriggerModifier = hasModifier(source, opts.triggerModifier);
}
return ClickLinkKeyboardEvent;
}());
exports.ClickLinkKeyboardEvent = ClickLinkKeyboardEvent;
var ClickLinkOptions = /** @class */ (function () {
function ClickLinkOptions(triggerKey, triggerModifier, triggerSideBySideKey, triggerSideBySideModifier) {
this.triggerKey = triggerKey;
this.triggerModifier = triggerModifier;
this.triggerSideBySideKey = triggerSideBySideKey;
this.triggerSideBySideModifier = triggerSideBySideModifier;
}
ClickLinkOptions.prototype.equals = function (other) {
return (this.triggerKey === other.triggerKey
&& this.triggerModifier === other.triggerModifier
&& this.triggerSideBySideKey === other.triggerSideBySideKey
&& this.triggerSideBySideModifier === other.triggerSideBySideModifier);
};
return ClickLinkOptions;
}());
exports.ClickLinkOptions = ClickLinkOptions;
function createOptions(multiCursorModifier) {
if (multiCursorModifier === 'altKey') {
if (platform.isMacintosh) {
return new ClickLinkOptions(57 /* Meta */, 'metaKey', 6 /* Alt */, 'altKey');
}
return new ClickLinkOptions(5 /* Ctrl */, 'ctrlKey', 6 /* Alt */, 'altKey');
}
if (platform.isMacintosh) {
return new ClickLinkOptions(6 /* Alt */, 'altKey', 57 /* Meta */, 'metaKey');
}
return new ClickLinkOptions(6 /* Alt */, 'altKey', 5 /* Ctrl */, 'ctrlKey');
}
var ClickLinkGesture = /** @class */ (function (_super) {
__extends(ClickLinkGesture, _super);
function ClickLinkGesture(editor) {
var _this = _super.call(this) || this;
_this._onMouseMoveOrRelevantKeyDown = _this._register(new event_1.Emitter());
_this.onMouseMoveOrRelevantKeyDown = _this._onMouseMoveOrRelevantKeyDown.event;
_this._onExecute = _this._register(new event_1.Emitter());
_this.onExecute = _this._onExecute.event;
_this._onCancel = _this._register(new event_1.Emitter());
_this.onCancel = _this._onCancel.event;
_this._editor = editor;
_this._opts = createOptions(_this._editor.getOption(59 /* multiCursorModifier */));
_this.lastMouseMoveEvent = null;
_this.hasTriggerKeyOnMouseDown = false;
_this._register(_this._editor.onDidChangeConfiguration(function (e) {
if (e.hasChanged(59 /* multiCursorModifier */)) {
var newOpts = createOptions(_this._editor.getOption(59 /* multiCursorModifier */));
if (_this._opts.equals(newOpts)) {
return;
}
_this._opts = newOpts;
_this.lastMouseMoveEvent = null;
_this.hasTriggerKeyOnMouseDown = false;
_this._onCancel.fire();
}
}));
_this._register(_this._editor.onMouseMove(function (e) { return _this.onEditorMouseMove(new ClickLinkMouseEvent(e, _this._opts)); }));
_this._register(_this._editor.onMouseDown(function (e) { return _this.onEditorMouseDown(new ClickLinkMouseEvent(e, _this._opts)); }));
_this._register(_this._editor.onMouseUp(function (e) { return _this.onEditorMouseUp(new ClickLinkMouseEvent(e, _this._opts)); }));
_this._register(_this._editor.onKeyDown(function (e) { return _this.onEditorKeyDown(new ClickLinkKeyboardEvent(e, _this._opts)); }));
_this._register(_this._editor.onKeyUp(function (e) { return _this.onEditorKeyUp(new ClickLinkKeyboardEvent(e, _this._opts)); }));
_this._register(_this._editor.onMouseDrag(function () { return _this.resetHandler(); }));
_this._register(_this._editor.onDidChangeCursorSelection(function (e) { return _this.onDidChangeCursorSelection(e); }));
_this._register(_this._editor.onDidChangeModel(function (e) { return _this.resetHandler(); }));
_this._register(_this._editor.onDidChangeModelContent(function () { return _this.resetHandler(); }));
_this._register(_this._editor.onDidScrollChange(function (e) {
if (e.scrollTopChanged || e.scrollLeftChanged) {
_this.resetHandler();
}
}));
return _this;
}
ClickLinkGesture.prototype.onDidChangeCursorSelection = function (e) {
if (e.selection && e.selection.startColumn !== e.selection.endColumn) {
this.resetHandler(); // immediately stop this feature if the user starts to select (https://github.com/Microsoft/vscode/issues/7827)
}
};
ClickLinkGesture.prototype.onEditorMouseMove = function (mouseEvent) {
this.lastMouseMoveEvent = mouseEvent;
this._onMouseMoveOrRelevantKeyDown.fire([mouseEvent, null]);
};
ClickLinkGesture.prototype.onEditorMouseDown = function (mouseEvent) {
// We need to record if we had the trigger key on mouse down because someone might select something in the editor
// holding the mouse down and then while mouse is down start to press Ctrl/Cmd to start a copy operation and then
// release the mouse button without wanting to do the navigation.
// With this flag we prevent goto definition if the mouse was down before the trigger key was pressed.
this.hasTriggerKeyOnMouseDown = mouseEvent.hasTriggerModifier;
};
ClickLinkGesture.prototype.onEditorMouseUp = function (mouseEvent) {
if (this.hasTriggerKeyOnMouseDown) {
this._onExecute.fire(mouseEvent);
}
};
ClickLinkGesture.prototype.onEditorKeyDown = function (e) {
if (this.lastMouseMoveEvent
&& (e.keyCodeIsTriggerKey // User just pressed Ctrl/Cmd (normal goto definition)
|| (e.keyCodeIsSideBySideKey && e.hasTriggerModifier) // User pressed Ctrl/Cmd+Alt (goto definition to the side)
)) {
this._onMouseMoveOrRelevantKeyDown.fire([this.lastMouseMoveEvent, e]);
}
else if (e.hasTriggerModifier) {
this._onCancel.fire(); // remove decorations if user holds another key with ctrl/cmd to prevent accident goto declaration
}
};
ClickLinkGesture.prototype.onEditorKeyUp = function (e) {
if (e.keyCodeIsTriggerKey) {
this._onCancel.fire();
}
};
ClickLinkGesture.prototype.resetHandler = function () {
this.lastMouseMoveEvent = null;
this.hasTriggerKeyOnMouseDown = false;
this._onCancel.fire();
};
return ClickLinkGesture;
}(lifecycle_1.Disposable));
exports.ClickLinkGesture = ClickLinkGesture;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[200/*vs/editor/contrib/hover/hoverOperation*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,10/*vs/base/common/errors*/]), function (require, exports, async_1, errors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var HoverOperation = /** @class */ (function () {
function HoverOperation(computer, success, error, progress, hoverTime) {
var _this = this;
this._computer = computer;
this._state = 0 /* IDLE */;
this._hoverTime = hoverTime;
this._firstWaitScheduler = new async_1.RunOnceScheduler(function () { return _this._triggerAsyncComputation(); }, 0);
this._secondWaitScheduler = new async_1.RunOnceScheduler(function () { return _this._triggerSyncComputation(); }, 0);
this._loadingMessageScheduler = new async_1.RunOnceScheduler(function () { return _this._showLoadingMessage(); }, 0);
this._asyncComputationPromise = null;
this._asyncComputationPromiseDone = false;
this._completeCallback = success;
this._errorCallback = error;
this._progressCallback = progress;
}
HoverOperation.prototype.setHoverTime = function (hoverTime) {
this._hoverTime = hoverTime;
};
HoverOperation.prototype._firstWaitTime = function () {
return this._hoverTime / 2;
};
HoverOperation.prototype._secondWaitTime = function () {
return this._hoverTime / 2;
};
HoverOperation.prototype._loadingMessageTime = function () {
return 3 * this._hoverTime;
};
HoverOperation.prototype._triggerAsyncComputation = function () {
var _this = this;
this._state = 2 /* SECOND_WAIT */;
this._secondWaitScheduler.schedule(this._secondWaitTime());
if (this._computer.computeAsync) {
this._asyncComputationPromiseDone = false;
this._asyncComputationPromise = async_1.createCancelablePromise(function (token) { return _this._computer.computeAsync(token); });
this._asyncComputationPromise.then(function (asyncResult) {
_this._asyncComputationPromiseDone = true;
_this._withAsyncResult(asyncResult);
}, function (e) { return _this._onError(e); });
}
else {
this._asyncComputationPromiseDone = true;
}
};
HoverOperation.prototype._triggerSyncComputation = function () {
if (this._computer.computeSync) {
this._computer.onResult(this._computer.computeSync(), true);
}
if (this._asyncComputationPromiseDone) {
this._state = 0 /* IDLE */;
this._onComplete(this._computer.getResult());
}
else {
this._state = 3 /* WAITING_FOR_ASYNC_COMPUTATION */;
this._onProgress(this._computer.getResult());
}
};
HoverOperation.prototype._showLoadingMessage = function () {
if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) {
this._onProgress(this._computer.getResultWithLoadingMessage());
}
};
HoverOperation.prototype._withAsyncResult = function (asyncResult) {
if (asyncResult) {
this._computer.onResult(asyncResult, false);
}
if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) {
this._state = 0 /* IDLE */;
this._onComplete(this._computer.getResult());
}
};
HoverOperation.prototype._onComplete = function (value) {
if (this._completeCallback) {
this._completeCallback(value);
}
};
HoverOperation.prototype._onError = function (error) {
if (this._errorCallback) {
this._errorCallback(error);
}
else {
errors_1.onUnexpectedError(error);
}
};
HoverOperation.prototype._onProgress = function (value) {
if (this._progressCallback) {
this._progressCallback(value);
}
};
HoverOperation.prototype.start = function (mode) {
if (mode === 0 /* Delayed */) {
if (this._state === 0 /* IDLE */) {
this._state = 1 /* FIRST_WAIT */;
this._firstWaitScheduler.schedule(this._firstWaitTime());
this._loadingMessageScheduler.schedule(this._loadingMessageTime());
}
}
else {
switch (this._state) {
case 0 /* IDLE */:
this._triggerAsyncComputation();
this._secondWaitScheduler.cancel();
this._triggerSyncComputation();
break;
case 2 /* SECOND_WAIT */:
this._secondWaitScheduler.cancel();
this._triggerSyncComputation();
break;
}
}
};
HoverOperation.prototype.cancel = function () {
this._loadingMessageScheduler.cancel();
if (this._state === 1 /* FIRST_WAIT */) {
this._firstWaitScheduler.cancel();
}
if (this._state === 2 /* SECOND_WAIT */) {
this._secondWaitScheduler.cancel();
if (this._asyncComputationPromise) {
this._asyncComputationPromise.cancel();
this._asyncComputationPromise = null;
}
}
if (this._state === 3 /* WAITING_FOR_ASYNC_COMPUTATION */) {
if (this._asyncComputationPromise) {
this._asyncComputationPromise.cancel();
this._asyncComputationPromise = null;
}
}
this._state = 0 /* IDLE */;
};
return HoverOperation;
}());
exports.HoverOperation = HoverOperation;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[201/*vs/editor/contrib/hover/hoverWidgets*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,47/*vs/base/browser/ui/widget*/]), function (require, exports, dom_1, scrollableElement_1, widget_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ContentHoverWidget = /** @class */ (function (_super) {
__extends(ContentHoverWidget, _super);
function ContentHoverWidget(id, editor) {
var _this = _super.call(this) || this;
// Editor.IContentWidget.allowEditorOverflow
_this.allowEditorOverflow = true;
_this._id = id;
_this._editor = editor;
_this._isVisible = false;
_this._stoleFocus = false;
_this._containerDomNode = document.createElement('div');
_this._containerDomNode.className = 'monaco-editor-hover hidden';
_this._containerDomNode.tabIndex = 0;
_this._domNode = document.createElement('div');
_this._domNode.className = 'monaco-editor-hover-content';
_this.scrollbar = new scrollableElement_1.DomScrollableElement(_this._domNode, {});
_this._register(_this.scrollbar);
_this._containerDomNode.appendChild(_this.scrollbar.getDomNode());
_this.onkeydown(_this._containerDomNode, function (e) {
if (e.equals(9 /* Escape */)) {
_this.hide();
}
});
_this._register(_this._editor.onDidChangeConfiguration(function (e) {
if (e.hasChanged(34 /* fontInfo */)) {
_this.updateFont();
}
}));
_this._editor.onDidLayoutChange(function (e) { return _this.layout(); });
_this.layout();
_this._editor.addContentWidget(_this);
_this._showAtPosition = null;
_this._showAtRange = null;
_this._stoleFocus = false;
return _this;
}
Object.defineProperty(ContentHoverWidget.prototype, "isVisible", {
get: function () {
return this._isVisible;
},
set: function (value) {
this._isVisible = value;
dom_1.toggleClass(this._containerDomNode, 'hidden', !this._isVisible);
},
enumerable: true,
configurable: true
});
ContentHoverWidget.prototype.getId = function () {
return this._id;
};
ContentHoverWidget.prototype.getDomNode = function () {
return this._containerDomNode;
};
ContentHoverWidget.prototype.showAt = function (position, range, focus) {
// Position has changed
this._showAtPosition = position;
this._showAtRange = range;
this.isVisible = true;
this._editor.layoutContentWidget(this);
// Simply force a synchronous render on the editor
// such that the widget does not really render with left = '0px'
this._editor.render();
this._stoleFocus = focus;
if (focus) {
this._containerDomNode.focus();
}
};
ContentHoverWidget.prototype.hide = function () {
if (!this.isVisible) {
return;
}
this.isVisible = false;
this._editor.layoutContentWidget(this);
if (this._stoleFocus) {
this._editor.focus();
}
};
ContentHoverWidget.prototype.getPosition = function () {
if (this.isVisible) {
return {
position: this._showAtPosition,
range: this._showAtRange,
preference: [
1 /* ABOVE */,
2 /* BELOW */
]
};
}
return null;
};
ContentHoverWidget.prototype.dispose = function () {
this._editor.removeContentWidget(this);
_super.prototype.dispose.call(this);
};
ContentHoverWidget.prototype.updateFont = function () {
var _this = this;
var codeClasses = Array.prototype.slice.call(this._domNode.getElementsByClassName('code'));
codeClasses.forEach(function (node) { return _this._editor.applyFontInfo(node); });
};
ContentHoverWidget.prototype.updateContents = function (node) {
this._domNode.textContent = '';
this._domNode.appendChild(node);
this.updateFont();
this._editor.layoutContentWidget(this);
this.onContentsChange();
};
ContentHoverWidget.prototype.onContentsChange = function () {
this.scrollbar.scanDomNode();
};
ContentHoverWidget.prototype.layout = function () {
var height = Math.max(this._editor.getLayoutInfo().height / 4, 250);
var _a = this._editor.getOption(34 /* fontInfo */), fontSize = _a.fontSize, lineHeight = _a.lineHeight;
this._domNode.style.fontSize = fontSize + "px";
this._domNode.style.lineHeight = lineHeight + "px";
this._domNode.style.maxHeight = height + "px";
this._domNode.style.maxWidth = Math.max(this._editor.getLayoutInfo().width * 0.66, 500) + "px";
};
return ContentHoverWidget;
}(widget_1.Widget));
exports.ContentHoverWidget = ContentHoverWidget;
var GlyphHoverWidget = /** @class */ (function (_super) {
__extends(GlyphHoverWidget, _super);
function GlyphHoverWidget(id, editor) {
var _this = _super.call(this) || this;
_this._id = id;
_this._editor = editor;
_this._isVisible = false;
_this._domNode = document.createElement('div');
_this._domNode.className = 'monaco-editor-hover hidden';
_this._domNode.setAttribute('aria-hidden', 'true');
_this._domNode.setAttribute('role', 'presentation');
_this._showAtLineNumber = -1;
_this._register(_this._editor.onDidChangeConfiguration(function (e) {
if (e.hasChanged(34 /* fontInfo */)) {
_this.updateFont();
}
}));
_this._editor.addOverlayWidget(_this);
return _this;
}
Object.defineProperty(GlyphHoverWidget.prototype, "isVisible", {
get: function () {
return this._isVisible;
},
set: function (value) {
this._isVisible = value;
dom_1.toggleClass(this._domNode, 'hidden', !this._isVisible);
},
enumerable: true,
configurable: true
});
GlyphHoverWidget.prototype.getId = function () {
return this._id;
};
GlyphHoverWidget.prototype.getDomNode = function () {
return this._domNode;
};
GlyphHoverWidget.prototype.showAt = function (lineNumber) {
this._showAtLineNumber = lineNumber;
if (!this.isVisible) {
this.isVisible = true;
}
var editorLayout = this._editor.getLayoutInfo();
var topForLineNumber = this._editor.getTopForLineNumber(this._showAtLineNumber);
var editorScrollTop = this._editor.getScrollTop();
var lineHeight = this._editor.getOption(49 /* lineHeight */);
var nodeHeight = this._domNode.clientHeight;
var top = topForLineNumber - editorScrollTop - ((nodeHeight - lineHeight) / 2);
this._domNode.style.left = editorLayout.glyphMarginLeft + editorLayout.glyphMarginWidth + "px";
this._domNode.style.top = Math.max(Math.round(top), 0) + "px";
};
GlyphHoverWidget.prototype.hide = function () {
if (!this.isVisible) {
return;
}
this.isVisible = false;
};
GlyphHoverWidget.prototype.getPosition = function () {
return null;
};
GlyphHoverWidget.prototype.dispose = function () {
this._editor.removeOverlayWidget(this);
_super.prototype.dispose.call(this);
};
GlyphHoverWidget.prototype.updateFont = function () {
var _this = this;
var codeTags = Array.prototype.slice.call(this._domNode.getElementsByTagName('code'));
var codeClasses = Array.prototype.slice.call(this._domNode.getElementsByClassName('code'));
__spreadArrays(codeTags, codeClasses).forEach(function (node) { return _this._editor.applyFontInfo(node); });
};
GlyphHoverWidget.prototype.updateContents = function (node) {
this._domNode.textContent = '';
this._domNode.appendChild(node);
this.updateFont();
};
return GlyphHoverWidget;
}(widget_1.Widget));
exports.GlyphHoverWidget = GlyphHoverWidget;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[384/*vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand*/], __M([0/*require*/,1/*exports*/,22/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var InPlaceReplaceCommand = /** @class */ (function () {
function InPlaceReplaceCommand(editRange, originalSelection, text) {
this._editRange = editRange;
this._originalSelection = originalSelection;
this._text = text;
}
InPlaceReplaceCommand.prototype.getEditOperations = function (model, builder) {
builder.addTrackedEditOperation(this._editRange, this._text);
};
InPlaceReplaceCommand.prototype.computeCursorState = function (model, helper) {
var inverseEditOperations = helper.getInverseEditOperations();
var srcRange = inverseEditOperations[0].range;
if (!this._originalSelection.isEmpty()) {
// Preserve selection and extends to typed text
return new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn - this._text.length, srcRange.endLineNumber, srcRange.endColumn);
}
return new selection_1.Selection(srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn), srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn));
};
return InPlaceReplaceCommand;
}());
exports.InPlaceReplaceCommand = InPlaceReplaceCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[385/*vs/editor/contrib/indentation/indentUtils*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getSpaceCnt(str, tabSize) {
var spacesCnt = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) === '\t') {
spacesCnt += tabSize;
}
else {
spacesCnt++;
}
}
return spacesCnt;
}
exports.getSpaceCnt = getSpaceCnt;
function generateIndent(spacesCnt, tabSize, insertSpaces) {
spacesCnt = spacesCnt < 0 ? 0 : spacesCnt;
var result = '';
if (!insertSpaces) {
var tabsCnt = Math.floor(spacesCnt / tabSize);
spacesCnt = spacesCnt % tabSize;
for (var i = 0; i < tabsCnt; i++) {
result += '\t';
}
}
for (var i = 0; i < spacesCnt; i++) {
result += ' ';
}
return result;
}
exports.generateIndent = generateIndent;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[386/*vs/editor/contrib/linesOperations/copyLinesCommand*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CopyLinesCommand = /** @class */ (function () {
function CopyLinesCommand(selection, isCopyingDown) {
this._selection = selection;
this._isCopyingDown = isCopyingDown;
this._selectionDirection = 0 /* LTR */;
this._selectionId = null;
this._startLineNumberDelta = 0;
this._endLineNumberDelta = 0;
}
CopyLinesCommand.prototype.getEditOperations = function (model, builder) {
var s = this._selection;
this._startLineNumberDelta = 0;
this._endLineNumberDelta = 0;
if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
this._endLineNumberDelta = 1;
s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
}
var sourceLines = [];
for (var i = s.startLineNumber; i <= s.endLineNumber; i++) {
sourceLines.push(model.getLineContent(i));
}
var sourceText = sourceLines.join('\n');
if (sourceText === '') {
// Duplicating empty line
if (this._isCopyingDown) {
this._startLineNumberDelta++;
this._endLineNumberDelta++;
}
}
if (!this._isCopyingDown) {
builder.addEditOperation(new range_1.Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), '\n' + sourceText);
}
else {
builder.addEditOperation(new range_1.Range(s.startLineNumber, 1, s.startLineNumber, 1), sourceText + '\n');
}
this._selectionId = builder.trackSelection(s);
this._selectionDirection = this._selection.getDirection();
};
CopyLinesCommand.prototype.computeCursorState = function (model, helper) {
var result = helper.getTrackedSelection(this._selectionId);
if (this._startLineNumberDelta !== 0 || this._endLineNumberDelta !== 0) {
var startLineNumber = result.startLineNumber;
var startColumn = result.startColumn;
var endLineNumber = result.endLineNumber;
var endColumn = result.endColumn;
if (this._startLineNumberDelta !== 0) {
startLineNumber = startLineNumber + this._startLineNumberDelta;
startColumn = 1;
}
if (this._endLineNumberDelta !== 0) {
endLineNumber = endLineNumber + this._endLineNumberDelta;
endColumn = 1;
}
result = selection_1.Selection.createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, this._selectionDirection);
}
return result;
};
return CopyLinesCommand;
}());
exports.CopyLinesCommand = CopyLinesCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[387/*vs/editor/contrib/linesOperations/sortLinesCommand*/], __M([0/*require*/,1/*exports*/,58/*vs/editor/common/core/editOperation*/,3/*vs/editor/common/core/range*/]), function (require, exports, editOperation_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SortLinesCommand = /** @class */ (function () {
function SortLinesCommand(selection, descending) {
this.selection = selection;
this.descending = descending;
this.selectionId = null;
}
SortLinesCommand.getCollator = function () {
if (!SortLinesCommand._COLLATOR) {
SortLinesCommand._COLLATOR = new Intl.Collator();
}
return SortLinesCommand._COLLATOR;
};
SortLinesCommand.prototype.getEditOperations = function (model, builder) {
var op = sortLines(model, this.selection, this.descending);
if (op) {
builder.addEditOperation(op.range, op.text);
}
this.selectionId = builder.trackSelection(this.selection);
};
SortLinesCommand.prototype.computeCursorState = function (model, helper) {
return helper.getTrackedSelection(this.selectionId);
};
SortLinesCommand.canRun = function (model, selection, descending) {
if (model === null) {
return false;
}
var data = getSortData(model, selection, descending);
if (!data) {
return false;
}
for (var i = 0, len = data.before.length; i < len; i++) {
if (data.before[i] !== data.after[i]) {
return true;
}
}
return false;
};
SortLinesCommand._COLLATOR = null;
return SortLinesCommand;
}());
exports.SortLinesCommand = SortLinesCommand;
function getSortData(model, selection, descending) {
var startLineNumber = selection.startLineNumber;
var endLineNumber = selection.endLineNumber;
if (selection.endColumn === 1) {
endLineNumber--;
}
// Nothing to sort if user didn't select anything.
if (startLineNumber >= endLineNumber) {
return null;
}
var linesToSort = [];
// Get the contents of the selection to be sorted.
for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
linesToSort.push(model.getLineContent(lineNumber));
}
var sorted = linesToSort.slice(0);
sorted.sort(SortLinesCommand.getCollator().compare);
// If descending, reverse the order.
if (descending === true) {
sorted = sorted.reverse();
}
return {
startLineNumber: startLineNumber,
endLineNumber: endLineNumber,
before: linesToSort,
after: sorted
};
}
/**
* Generate commands for sorting lines on a model.
*/
function sortLines(model, selection, descending) {
var data = getSortData(model, selection, descending);
if (!data) {
return null;
}
return editOperation_1.EditOperation.replace(new range_1.Range(data.startLineNumber, 1, data.endLineNumber, model.getLineMaxColumn(data.endLineNumber)), data.after.join('\n'));
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[202/*vs/editor/contrib/smartSelect/bracketSelections*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,76/*vs/base/common/linkedList*/]), function (require, exports, position_1, range_1, linkedList_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BracketSelectionRangeProvider = /** @class */ (function () {
function BracketSelectionRangeProvider() {
}
BracketSelectionRangeProvider.prototype.provideSelectionRanges = function (model, positions) {
return __awaiter(this, void 0, void 0, function () {
var result, _loop_1, _i, positions_1, position;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
result = [];
_loop_1 = function (position) {
var bucket, ranges;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
bucket = [];
result.push(bucket);
ranges = new Map();
return [4 /*yield*/, new Promise(function (resolve) { return BracketSelectionRangeProvider._bracketsRightYield(resolve, 0, model, position, ranges); })];
case 1:
_a.sent();
return [4 /*yield*/, new Promise(function (resolve) { return BracketSelectionRangeProvider._bracketsLeftYield(resolve, 0, model, position, ranges, bucket); })];
case 2:
_a.sent();
return [2 /*return*/];
}
});
};
_i = 0, positions_1 = positions;
_a.label = 1;
case 1:
if (!(_i < positions_1.length)) return [3 /*break*/, 4];
position = positions_1[_i];
return [5 /*yield**/, _loop_1(position)];
case 2:
_a.sent();
_a.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, result];
}
});
});
};
BracketSelectionRangeProvider._bracketsRightYield = function (resolve, round, model, pos, ranges) {
var counts = new Map();
var t1 = Date.now();
while (true) {
if (round >= BracketSelectionRangeProvider._maxRounds) {
resolve();
break;
}
if (!pos) {
resolve();
break;
}
var bracket = model.findNextBracket(pos);
if (!bracket) {
resolve();
break;
}
var d = Date.now() - t1;
if (d > BracketSelectionRangeProvider._maxDuration) {
setTimeout(function () { return BracketSelectionRangeProvider._bracketsRightYield(resolve, round + 1, model, pos, ranges); });
break;
}
var key = bracket.close[0];
if (bracket.isOpen) {
// wait for closing
var val = counts.has(key) ? counts.get(key) : 0;
counts.set(key, val + 1);
}
else {
// process closing
var val = counts.has(key) ? counts.get(key) : 0;
val -= 1;
counts.set(key, Math.max(0, val));
if (val < 0) {
var list = ranges.get(key);
if (!list) {
list = new linkedList_1.LinkedList();
ranges.set(key, list);
}
list.push(bracket.range);
}
}
pos = bracket.range.getEndPosition();
}
};
BracketSelectionRangeProvider._bracketsLeftYield = function (resolve, round, model, pos, ranges, bucket) {
var counts = new Map();
var t1 = Date.now();
while (true) {
if (round >= BracketSelectionRangeProvider._maxRounds && ranges.size === 0) {
resolve();
break;
}
if (!pos) {
resolve();
break;
}
var bracket = model.findPrevBracket(pos);
if (!bracket) {
resolve();
break;
}
var d = Date.now() - t1;
if (d > BracketSelectionRangeProvider._maxDuration) {
setTimeout(function () { return BracketSelectionRangeProvider._bracketsLeftYield(resolve, round + 1, model, pos, ranges, bucket); });
break;
}
var key = bracket.close[0];
if (!bracket.isOpen) {
// wait for opening
var val = counts.has(key) ? counts.get(key) : 0;
counts.set(key, val + 1);
}
else {
// opening
var val = counts.has(key) ? counts.get(key) : 0;
val -= 1;
counts.set(key, Math.max(0, val));
if (val < 0) {
var list = ranges.get(key);
if (list) {
var closing = list.shift();
if (list.size === 0) {
ranges.delete(key);
}
var innerBracket = range_1.Range.fromPositions(bracket.range.getEndPosition(), closing.getStartPosition());
var outerBracket = range_1.Range.fromPositions(bracket.range.getStartPosition(), closing.getEndPosition());
bucket.push({ range: innerBracket });
bucket.push({ range: outerBracket });
BracketSelectionRangeProvider._addBracketLeading(model, outerBracket, bucket);
}
}
}
pos = bracket.range.getStartPosition();
}
};
BracketSelectionRangeProvider._addBracketLeading = function (model, bracket, bucket) {
if (bracket.startLineNumber === bracket.endLineNumber) {
return;
}
// xxxxxxxx {
//
// }
var startLine = bracket.startLineNumber;
var column = model.getLineFirstNonWhitespaceColumn(startLine);
if (column !== 0 && column !== bracket.startColumn) {
bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(startLine, column), bracket.getEndPosition()) });
bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(startLine, 1), bracket.getEndPosition()) });
}
// xxxxxxxx
// {
//
// }
var aboveLine = startLine - 1;
if (aboveLine > 0) {
var column_1 = model.getLineFirstNonWhitespaceColumn(aboveLine);
if (column_1 === bracket.startColumn && column_1 !== model.getLineLastNonWhitespaceColumn(aboveLine)) {
bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(aboveLine, column_1), bracket.getEndPosition()) });
bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(aboveLine, 1), bracket.getEndPosition()) });
}
}
};
BracketSelectionRangeProvider._maxDuration = 30;
BracketSelectionRangeProvider._maxRounds = 2;
return BracketSelectionRangeProvider;
}());
exports.BracketSelectionRangeProvider = BracketSelectionRangeProvider;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[388/*vs/editor/contrib/smartSelect/wordSelections*/], __M([0/*require*/,1/*exports*/,3/*vs/editor/common/core/range*/,5/*vs/base/common/strings*/]), function (require, exports, range_1, strings_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var WordSelectionRangeProvider = /** @class */ (function () {
function WordSelectionRangeProvider() {
}
WordSelectionRangeProvider.prototype.provideSelectionRanges = function (model, positions) {
var result = [];
for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
var position = positions_1[_i];
var bucket = [];
result.push(bucket);
this._addInWordRanges(bucket, model, position);
this._addWordRanges(bucket, model, position);
this._addWhitespaceLine(bucket, model, position);
bucket.push({ range: model.getFullModelRange() });
}
return result;
};
WordSelectionRangeProvider.prototype._addInWordRanges = function (bucket, model, pos) {
var obj = model.getWordAtPosition(pos);
if (!obj) {
return;
}
var word = obj.word, startColumn = obj.startColumn;
var offset = pos.column - startColumn;
var start = offset;
var end = offset;
var lastCh = 0;
// LEFT anchor (start)
for (; start >= 0; start--) {
var ch = word.charCodeAt(start);
if (ch === 95 /* Underline */ || ch === 45 /* Dash */) {
// foo-bar OR foo_bar
break;
}
else if (strings_1.isLowerAsciiLetter(ch) && strings_1.isUpperAsciiLetter(lastCh)) {
// fooBar
break;
}
lastCh = ch;
}
start += 1;
// RIGHT anchor (end)
for (; end < word.length; end++) {
var ch = word.charCodeAt(end);
if (strings_1.isUpperAsciiLetter(ch) && strings_1.isLowerAsciiLetter(lastCh)) {
// fooBar
break;
}
else if (ch === 95 /* Underline */ || ch === 45 /* Dash */) {
// foo-bar OR foo_bar
break;
}
lastCh = ch;
}
if (start < end) {
bucket.push({ range: new range_1.Range(pos.lineNumber, startColumn + start, pos.lineNumber, startColumn + end) });
}
};
WordSelectionRangeProvider.prototype._addWordRanges = function (bucket, model, pos) {
var word = model.getWordAtPosition(pos);
if (word) {
bucket.push({ range: new range_1.Range(pos.lineNumber, word.startColumn, pos.lineNumber, word.endColumn) });
}
};
WordSelectionRangeProvider.prototype._addWhitespaceLine = function (bucket, model, pos) {
if (model.getLineLength(pos.lineNumber) > 0
&& model.getLineFirstNonWhitespaceColumn(pos.lineNumber) === 0
&& model.getLineLastNonWhitespaceColumn(pos.lineNumber) === 0) {
bucket.push({ range: new range_1.Range(pos.lineNumber, 1, pos.lineNumber, model.getLineMaxColumn(pos.lineNumber)) });
}
};
return WordSelectionRangeProvider;
}());
exports.WordSelectionRangeProvider = WordSelectionRangeProvider;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[151/*vs/editor/contrib/snippet/snippetParser*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
var Scanner = /** @class */ (function () {
function Scanner() {
this.value = '';
this.pos = 0;
}
Scanner.isDigitCharacter = function (ch) {
return ch >= 48 /* Digit0 */ && ch <= 57 /* Digit9 */;
};
Scanner.isVariableCharacter = function (ch) {
return ch === 95 /* Underline */
|| (ch >= 97 /* a */ && ch <= 122 /* z */)
|| (ch >= 65 /* A */ && ch <= 90 /* Z */);
};
Scanner.prototype.text = function (value) {
this.value = value;
this.pos = 0;
};
Scanner.prototype.tokenText = function (token) {
return this.value.substr(token.pos, token.len);
};
Scanner.prototype.next = function () {
if (this.pos >= this.value.length) {
return { type: 14 /* EOF */, pos: this.pos, len: 0 };
}
var pos = this.pos;
var len = 0;
var ch = this.value.charCodeAt(pos);
var type;
// static types
type = Scanner._table[ch];
if (typeof type === 'number') {
this.pos += 1;
return { type: type, pos: pos, len: 1 };
}
// number
if (Scanner.isDigitCharacter(ch)) {
type = 8 /* Int */;
do {
len += 1;
ch = this.value.charCodeAt(pos + len);
} while (Scanner.isDigitCharacter(ch));
this.pos += len;
return { type: type, pos: pos, len: len };
}
// variable name
if (Scanner.isVariableCharacter(ch)) {
type = 9 /* VariableName */;
do {
ch = this.value.charCodeAt(pos + (++len));
} while (Scanner.isVariableCharacter(ch) || Scanner.isDigitCharacter(ch));
this.pos += len;
return { type: type, pos: pos, len: len };
}
// format
type = 10 /* Format */;
do {
len += 1;
ch = this.value.charCodeAt(pos + len);
} while (!isNaN(ch)
&& typeof Scanner._table[ch] === 'undefined' // not static token
&& !Scanner.isDigitCharacter(ch) // not number
&& !Scanner.isVariableCharacter(ch) // not variable
);
this.pos += len;
return { type: type, pos: pos, len: len };
};
Scanner._table = (_a = {},
_a[36 /* DollarSign */] = 0 /* Dollar */,
_a[58 /* Colon */] = 1 /* Colon */,
_a[44 /* Comma */] = 2 /* Comma */,
_a[123 /* OpenCurlyBrace */] = 3 /* CurlyOpen */,
_a[125 /* CloseCurlyBrace */] = 4 /* CurlyClose */,
_a[92 /* Backslash */] = 5 /* Backslash */,
_a[47 /* Slash */] = 6 /* Forwardslash */,
_a[124 /* Pipe */] = 7 /* Pipe */,
_a[43 /* Plus */] = 11 /* Plus */,
_a[45 /* Dash */] = 12 /* Dash */,
_a[63 /* QuestionMark */] = 13 /* QuestionMark */,
_a);
return Scanner;
}());
exports.Scanner = Scanner;
var Marker = /** @class */ (function () {
function Marker() {
this._children = [];
}
Marker.prototype.appendChild = function (child) {
if (child instanceof Text && this._children[this._children.length - 1] instanceof Text) {
// this and previous child are text -> merge them
this._children[this._children.length - 1].value += child.value;
}
else {
// normal adoption of child
child.parent = this;
this._children.push(child);
}
return this;
};
Marker.prototype.replace = function (child, others) {
var parent = child.parent;
var idx = parent.children.indexOf(child);
var newChildren = parent.children.slice(0);
newChildren.splice.apply(newChildren, __spreadArrays([idx, 1], others));
parent._children = newChildren;
(function _fixParent(children, parent) {
for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
var child_1 = children_1[_i];
child_1.parent = parent;
_fixParent(child_1.children, child_1);
}
})(others, parent);
};
Object.defineProperty(Marker.prototype, "children", {
get: function () {
return this._children;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Marker.prototype, "snippet", {
get: function () {
var candidate = this;
while (true) {
if (!candidate) {
return undefined;
}
if (candidate instanceof TextmateSnippet) {
return candidate;
}
candidate = candidate.parent;
}
},
enumerable: true,
configurable: true
});
Marker.prototype.toString = function () {
return this.children.reduce(function (prev, cur) { return prev + cur.toString(); }, '');
};
Marker.prototype.len = function () {
return 0;
};
return Marker;
}());
exports.Marker = Marker;
var Text = /** @class */ (function (_super) {
__extends(Text, _super);
function Text(value) {
var _this_1 = _super.call(this) || this;
_this_1.value = value;
return _this_1;
}
Text.prototype.toString = function () {
return this.value;
};
Text.prototype.len = function () {
return this.value.length;
};
Text.prototype.clone = function () {
return new Text(this.value);
};
return Text;
}(Marker));
exports.Text = Text;
var TransformableMarker = /** @class */ (function (_super) {
__extends(TransformableMarker, _super);
function TransformableMarker() {
return _super !== null && _super.apply(this, arguments) || this;
}
return TransformableMarker;
}(Marker));
exports.TransformableMarker = TransformableMarker;
var Placeholder = /** @class */ (function (_super) {
__extends(Placeholder, _super);
function Placeholder(index) {
var _this_1 = _super.call(this) || this;
_this_1.index = index;
return _this_1;
}
Placeholder.compareByIndex = function (a, b) {
if (a.index === b.index) {
return 0;
}
else if (a.isFinalTabstop) {
return 1;
}
else if (b.isFinalTabstop) {
return -1;
}
else if (a.index < b.index) {
return -1;
}
else if (a.index > b.index) {
return 1;
}
else {
return 0;
}
};
Object.defineProperty(Placeholder.prototype, "isFinalTabstop", {
get: function () {
return this.index === 0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Placeholder.prototype, "choice", {
get: function () {
return this._children.length === 1 && this._children[0] instanceof Choice
? this._children[0]
: undefined;
},
enumerable: true,
configurable: true
});
Placeholder.prototype.clone = function () {
var ret = new Placeholder(this.index);
if (this.transform) {
ret.transform = this.transform.clone();
}
ret._children = this.children.map(function (child) { return child.clone(); });
return ret;
};
return Placeholder;
}(TransformableMarker));
exports.Placeholder = Placeholder;
var Choice = /** @class */ (function (_super) {
__extends(Choice, _super);
function Choice() {
var _this_1 = _super !== null && _super.apply(this, arguments) || this;
_this_1.options = [];
return _this_1;
}
Choice.prototype.appendChild = function (marker) {
if (marker instanceof Text) {
marker.parent = this;
this.options.push(marker);
}
return this;
};
Choice.prototype.toString = function () {
return this.options[0].value;
};
Choice.prototype.len = function () {
return this.options[0].len();
};
Choice.prototype.clone = function () {
var ret = new Choice();
this.options.forEach(ret.appendChild, ret);
return ret;
};
return Choice;
}(Marker));
exports.Choice = Choice;
var Transform = /** @class */ (function (_super) {
__extends(Transform, _super);
function Transform() {
var _this_1 = _super !== null && _super.apply(this, arguments) || this;
_this_1.regexp = new RegExp('');
return _this_1;
}
Transform.prototype.resolve = function (value) {
var _this = this;
var didMatch = false;
var ret = value.replace(this.regexp, function () {
didMatch = true;
return _this._replace(Array.prototype.slice.call(arguments, 0, -2));
});
// when the regex didn't match and when the transform has
// else branches, then run those
if (!didMatch && this._children.some(function (child) { return child instanceof FormatString && Boolean(child.elseValue); })) {
ret = this._replace([]);
}
return ret;
};
Transform.prototype._replace = function (groups) {
var ret = '';
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var marker = _a[_i];
if (marker instanceof FormatString) {
var value = groups[marker.index] || '';
value = marker.resolve(value);
ret += value;
}
else {
ret += marker.toString();
}
}
return ret;
};
Transform.prototype.toString = function () {
return '';
};
Transform.prototype.clone = function () {
var ret = new Transform();
ret.regexp = new RegExp(this.regexp.source, '' + (this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : ''));
ret._children = this.children.map(function (child) { return child.clone(); });
return ret;
};
return Transform;
}(Marker));
exports.Transform = Transform;
var FormatString = /** @class */ (function (_super) {
__extends(FormatString, _super);
function FormatString(index, shorthandName, ifValue, elseValue) {
var _this_1 = _super.call(this) || this;
_this_1.index = index;
_this_1.shorthandName = shorthandName;
_this_1.ifValue = ifValue;
_this_1.elseValue = elseValue;
return _this_1;
}
FormatString.prototype.resolve = function (value) {
if (this.shorthandName === 'upcase') {
return !value ? '' : value.toLocaleUpperCase();
}
else if (this.shorthandName === 'downcase') {
return !value ? '' : value.toLocaleLowerCase();
}
else if (this.shorthandName === 'capitalize') {
return !value ? '' : (value[0].toLocaleUpperCase() + value.substr(1));
}
else if (this.shorthandName === 'pascalcase') {
return !value ? '' : this._toPascalCase(value);
}
else if (Boolean(value) && typeof this.ifValue === 'string') {
return this.ifValue;
}
else if (!Boolean(value) && typeof this.elseValue === 'string') {
return this.elseValue;
}
else {
return value || '';
}
};
FormatString.prototype._toPascalCase = function (value) {
var match = value.match(/[a-z]+/gi);
if (!match) {
return value;
}
return match.map(function (word) {
return word.charAt(0).toUpperCase()
+ word.substr(1).toLowerCase();
})
.join('');
};
FormatString.prototype.clone = function () {
var ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue);
return ret;
};
return FormatString;
}(Marker));
exports.FormatString = FormatString;
var Variable = /** @class */ (function (_super) {
__extends(Variable, _super);
function Variable(name) {
var _this_1 = _super.call(this) || this;
_this_1.name = name;
return _this_1;
}
Variable.prototype.resolve = function (resolver) {
var value = resolver.resolve(this);
if (this.transform) {
value = this.transform.resolve(value || '');
}
if (value !== undefined) {
this._children = [new Text(value)];
return true;
}
return false;
};
Variable.prototype.clone = function () {
var ret = new Variable(this.name);
if (this.transform) {
ret.transform = this.transform.clone();
}
ret._children = this.children.map(function (child) { return child.clone(); });
return ret;
};
return Variable;
}(TransformableMarker));
exports.Variable = Variable;
function walk(marker, visitor) {
var stack = __spreadArrays(marker);
while (stack.length > 0) {
var marker_1 = stack.shift();
var recurse = visitor(marker_1);
if (!recurse) {
break;
}
stack.unshift.apply(stack, marker_1.children);
}
}
var TextmateSnippet = /** @class */ (function (_super) {
__extends(TextmateSnippet, _super);
function TextmateSnippet() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(TextmateSnippet.prototype, "placeholderInfo", {
get: function () {
if (!this._placeholders) {
// fill in placeholders
var all_1 = [];
var last_1;
this.walk(function (candidate) {
if (candidate instanceof Placeholder) {
all_1.push(candidate);
last_1 = !last_1 || last_1.index < candidate.index ? candidate : last_1;
}
return true;
});
this._placeholders = { all: all_1, last: last_1 };
}
return this._placeholders;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextmateSnippet.prototype, "placeholders", {
get: function () {
var all = this.placeholderInfo.all;
return all;
},
enumerable: true,
configurable: true
});
TextmateSnippet.prototype.offset = function (marker) {
var pos = 0;
var found = false;
this.walk(function (candidate) {
if (candidate === marker) {
found = true;
return false;
}
pos += candidate.len();
return true;
});
if (!found) {
return -1;
}
return pos;
};
TextmateSnippet.prototype.fullLen = function (marker) {
var ret = 0;
walk([marker], function (marker) {
ret += marker.len();
return true;
});
return ret;
};
TextmateSnippet.prototype.enclosingPlaceholders = function (placeholder) {
var ret = [];
var parent = placeholder.parent;
while (parent) {
if (parent instanceof Placeholder) {
ret.push(parent);
}
parent = parent.parent;
}
return ret;
};
TextmateSnippet.prototype.resolveVariables = function (resolver) {
var _this_1 = this;
this.walk(function (candidate) {
if (candidate instanceof Variable) {
if (candidate.resolve(resolver)) {
_this_1._placeholders = undefined;
}
}
return true;
});
return this;
};
TextmateSnippet.prototype.appendChild = function (child) {
this._placeholders = undefined;
return _super.prototype.appendChild.call(this, child);
};
TextmateSnippet.prototype.replace = function (child, others) {
this._placeholders = undefined;
return _super.prototype.replace.call(this, child, others);
};
TextmateSnippet.prototype.clone = function () {
var ret = new TextmateSnippet();
this._children = this.children.map(function (child) { return child.clone(); });
return ret;
};
TextmateSnippet.prototype.walk = function (visitor) {
walk(this.children, visitor);
};
return TextmateSnippet;
}(Marker));
exports.TextmateSnippet = TextmateSnippet;
var SnippetParser = /** @class */ (function () {
function SnippetParser() {
this._scanner = new Scanner();
this._token = { type: 14 /* EOF */, pos: 0, len: 0 };
}
SnippetParser.escape = function (value) {
return value.replace(/\$|}|\\/g, '\\$&');
};
SnippetParser.prototype.parse = function (value, insertFinalTabstop, enforceFinalTabstop) {
this._scanner.text(value);
this._token = this._scanner.next();
var snippet = new TextmateSnippet();
while (this._parse(snippet)) {
// nothing
}
// fill in values for placeholders. the first placeholder of an index
// that has a value defines the value for all placeholders with that index
var placeholderDefaultValues = new Map();
var incompletePlaceholders = [];
var placeholderCount = 0;
snippet.walk(function (marker) {
if (marker instanceof Placeholder) {
placeholderCount += 1;
if (marker.isFinalTabstop) {
placeholderDefaultValues.set(0, undefined);
}
else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) {
placeholderDefaultValues.set(marker.index, marker.children);
}
else {
incompletePlaceholders.push(marker);
}
}
return true;
});
for (var _i = 0, incompletePlaceholders_1 = incompletePlaceholders; _i < incompletePlaceholders_1.length; _i++) {
var placeholder = incompletePlaceholders_1[_i];
var defaultValues = placeholderDefaultValues.get(placeholder.index);
if (defaultValues) {
var clone = new Placeholder(placeholder.index);
clone.transform = placeholder.transform;
for (var _a = 0, defaultValues_1 = defaultValues; _a < defaultValues_1.length; _a++) {
var child = defaultValues_1[_a];
clone.appendChild(child.clone());
}
snippet.replace(placeholder, [clone]);
}
}
if (!enforceFinalTabstop) {
enforceFinalTabstop = placeholderCount > 0 && insertFinalTabstop;
}
if (!placeholderDefaultValues.has(0) && enforceFinalTabstop) {
// the snippet uses placeholders but has no
// final tabstop defined -> insert at the end
snippet.appendChild(new Placeholder(0));
}
return snippet;
};
SnippetParser.prototype._accept = function (type, value) {
if (type === undefined || this._token.type === type) {
var ret = !value ? true : this._scanner.tokenText(this._token);
this._token = this._scanner.next();
return ret;
}
return false;
};
SnippetParser.prototype._backTo = function (token) {
this._scanner.pos = token.pos + token.len;
this._token = token;
return false;
};
SnippetParser.prototype._until = function (type) {
var start = this._token;
while (this._token.type !== type) {
if (this._token.type === 14 /* EOF */) {
return false;
}
else if (this._token.type === 5 /* Backslash */) {
var nextToken = this._scanner.next();
if (nextToken.type !== 0 /* Dollar */
&& nextToken.type !== 4 /* CurlyClose */
&& nextToken.type !== 5 /* Backslash */) {
return false;
}
}
this._token = this._scanner.next();
}
var value = this._scanner.value.substring(start.pos, this._token.pos).replace(/\\(\$|}|\\)/g, '$1');
this._token = this._scanner.next();
return value;
};
SnippetParser.prototype._parse = function (marker) {
return this._parseEscaped(marker)
|| this._parseTabstopOrVariableName(marker)
|| this._parseComplexPlaceholder(marker)
|| this._parseComplexVariable(marker)
|| this._parseAnything(marker);
};
// \$, \\, \} -> just text
SnippetParser.prototype._parseEscaped = function (marker) {
var value;
if (value = this._accept(5 /* Backslash */, true)) {
// saw a backslash, append escaped token or that backslash
value = this._accept(0 /* Dollar */, true)
|| this._accept(4 /* CurlyClose */, true)
|| this._accept(5 /* Backslash */, true)
|| value;
marker.appendChild(new Text(value));
return true;
}
return false;
};
// $foo -> variable, $1 -> tabstop
SnippetParser.prototype._parseTabstopOrVariableName = function (parent) {
var value;
var token = this._token;
var match = this._accept(0 /* Dollar */)
&& (value = this._accept(9 /* VariableName */, true) || this._accept(8 /* Int */, true));
if (!match) {
return this._backTo(token);
}
parent.appendChild(/^\d+$/.test(value)
? new Placeholder(Number(value))
: new Variable(value));
return true;
};
// ${1:}, ${1} -> placeholder
SnippetParser.prototype._parseComplexPlaceholder = function (parent) {
var index;
var token = this._token;
var match = this._accept(0 /* Dollar */)
&& this._accept(3 /* CurlyOpen */)
&& (index = this._accept(8 /* Int */, true));
if (!match) {
return this._backTo(token);
}
var placeholder = new Placeholder(Number(index));
if (this._accept(1 /* Colon */)) {
// ${1:}
while (true) {
// ...} -> done
if (this._accept(4 /* CurlyClose */)) {
parent.appendChild(placeholder);
return true;
}
if (this._parse(placeholder)) {
continue;
}
// fallback
parent.appendChild(new Text('${' + index + ':'));
placeholder.children.forEach(parent.appendChild, parent);
return true;
}
}
else if (placeholder.index > 0 && this._accept(7 /* Pipe */)) {
// ${1|one,two,three|}
var choice = new Choice();
while (true) {
if (this._parseChoiceElement(choice)) {
if (this._accept(2 /* Comma */)) {
// opt, -> more
continue;
}
if (this._accept(7 /* Pipe */)) {
placeholder.appendChild(choice);
if (this._accept(4 /* CurlyClose */)) {
// ..|} -> done
parent.appendChild(placeholder);
return true;
}
}
}
this._backTo(token);
return false;
}
}
else if (this._accept(6 /* Forwardslash */)) {
// ${1///}
if (this._parseTransform(placeholder)) {
parent.appendChild(placeholder);
return true;
}
this._backTo(token);
return false;
}
else if (this._accept(4 /* CurlyClose */)) {
// ${1}
parent.appendChild(placeholder);
return true;
}
else {
// ${1 <- missing curly or colon
return this._backTo(token);
}
};
SnippetParser.prototype._parseChoiceElement = function (parent) {
var token = this._token;
var values = [];
while (true) {
if (this._token.type === 2 /* Comma */ || this._token.type === 7 /* Pipe */) {
break;
}
var value = void 0;
if (value = this._accept(5 /* Backslash */, true)) {
// \, \|, or \\
value = this._accept(2 /* Comma */, true)
|| this._accept(7 /* Pipe */, true)
|| this._accept(5 /* Backslash */, true)
|| value;
}
else {
value = this._accept(undefined, true);
}
if (!value) {
// EOF
this._backTo(token);
return false;
}
values.push(value);
}
if (values.length === 0) {
this._backTo(token);
return false;
}
parent.appendChild(new Text(values.join('')));
return true;
};
// ${foo:}, ${foo} -> variable
SnippetParser.prototype._parseComplexVariable = function (parent) {
var name;
var token = this._token;
var match = this._accept(0 /* Dollar */)
&& this._accept(3 /* CurlyOpen */)
&& (name = this._accept(9 /* VariableName */, true));
if (!match) {
return this._backTo(token);
}
var variable = new Variable(name);
if (this._accept(1 /* Colon */)) {
// ${foo:}
while (true) {
// ...} -> done
if (this._accept(4 /* CurlyClose */)) {
parent.appendChild(variable);
return true;
}
if (this._parse(variable)) {
continue;
}
// fallback
parent.appendChild(new Text('${' + name + ':'));
variable.children.forEach(parent.appendChild, parent);
return true;
}
}
else if (this._accept(6 /* Forwardslash */)) {
// ${foo///}
if (this._parseTransform(variable)) {
parent.appendChild(variable);
return true;
}
this._backTo(token);
return false;
}
else if (this._accept(4 /* CurlyClose */)) {
// ${foo}
parent.appendChild(variable);
return true;
}
else {
// ${foo <- missing curly or colon
return this._backTo(token);
}
};
SnippetParser.prototype._parseTransform = function (parent) {
// ...//}
var transform = new Transform();
var regexValue = '';
var regexOptions = '';
// (1) /regex
while (true) {
if (this._accept(6 /* Forwardslash */)) {
break;
}
var escaped = void 0;
if (escaped = this._accept(5 /* Backslash */, true)) {
escaped = this._accept(6 /* Forwardslash */, true) || escaped;
regexValue += escaped;
continue;
}
if (this._token.type !== 14 /* EOF */) {
regexValue += this._accept(undefined, true);
continue;
}
return false;
}
// (2) /format
while (true) {
if (this._accept(6 /* Forwardslash */)) {
break;
}
var escaped = void 0;
if (escaped = this._accept(5 /* Backslash */, true)) {
escaped = this._accept(5 /* Backslash */, true) || this._accept(6 /* Forwardslash */, true) || escaped;
transform.appendChild(new Text(escaped));
continue;
}
if (this._parseFormatString(transform) || this._parseAnything(transform)) {
continue;
}
return false;
}
// (3) /option
while (true) {
if (this._accept(4 /* CurlyClose */)) {
break;
}
if (this._token.type !== 14 /* EOF */) {
regexOptions += this._accept(undefined, true);
continue;
}
return false;
}
try {
transform.regexp = new RegExp(regexValue, regexOptions);
}
catch (e) {
// invalid regexp
return false;
}
parent.transform = transform;
return true;
};
SnippetParser.prototype._parseFormatString = function (parent) {
var token = this._token;
if (!this._accept(0 /* Dollar */)) {
return false;
}
var complex = false;
if (this._accept(3 /* CurlyOpen */)) {
complex = true;
}
var index = this._accept(8 /* Int */, true);
if (!index) {
this._backTo(token);
return false;
}
else if (!complex) {
// $1
parent.appendChild(new FormatString(Number(index)));
return true;
}
else if (this._accept(4 /* CurlyClose */)) {
// ${1}
parent.appendChild(new FormatString(Number(index)));
return true;
}
else if (!this._accept(1 /* Colon */)) {
this._backTo(token);
return false;
}
if (this._accept(6 /* Forwardslash */)) {
// ${1:/upcase}
var shorthand = this._accept(9 /* VariableName */, true);
if (!shorthand || !this._accept(4 /* CurlyClose */)) {
this._backTo(token);
return false;
}
else {
parent.appendChild(new FormatString(Number(index), shorthand));
return true;
}
}
else if (this._accept(11 /* Plus */)) {
// ${1:+}
var ifValue = this._until(4 /* CurlyClose */);
if (ifValue) {
parent.appendChild(new FormatString(Number(index), undefined, ifValue, undefined));
return true;
}
}
else if (this._accept(12 /* Dash */)) {
// ${2:-}
var elseValue = this._until(4 /* CurlyClose */);
if (elseValue) {
parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue));
return true;
}
}
else if (this._accept(13 /* QuestionMark */)) {
// ${2:?:}
var ifValue = this._until(1 /* Colon */);
if (ifValue) {
var elseValue = this._until(4 /* CurlyClose */);
if (elseValue) {
parent.appendChild(new FormatString(Number(index), undefined, ifValue, elseValue));
return true;
}
}
}
else {
// ${1:}
var elseValue = this._until(4 /* CurlyClose */);
if (elseValue) {
parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue));
return true;
}
}
this._backTo(token);
return false;
};
SnippetParser.prototype._parseAnything = function (marker) {
if (this._token.type !== 14 /* EOF */) {
marker.appendChild(new Text(this._scanner.tokenText(this._token)));
this._accept(undefined);
return true;
}
return false;
};
return SnippetParser;
}());
exports.SnippetParser = SnippetParser;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[389/*vs/editor/contrib/suggest/completionModel*/], __M([0/*require*/,1/*exports*/,61/*vs/base/common/filters*/,5/*vs/base/common/strings*/]), function (require, exports, filters_1, strings_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LineContext = /** @class */ (function () {
function LineContext(leadingLineContent, characterCountDelta) {
this.leadingLineContent = leadingLineContent;
this.characterCountDelta = characterCountDelta;
}
return LineContext;
}());
exports.LineContext = LineContext;
var CompletionModel = /** @class */ (function () {
function CompletionModel(items, column, lineContext, wordDistance, options, snippetSuggestions) {
this._snippetCompareFn = CompletionModel._compareCompletionItems;
this._items = items;
this._column = column;
this._wordDistance = wordDistance;
this._options = options;
this._refilterKind = 1 /* All */;
this._lineContext = lineContext;
if (snippetSuggestions === 'top') {
this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsUp;
}
else if (snippetSuggestions === 'bottom') {
this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsDown;
}
}
Object.defineProperty(CompletionModel.prototype, "lineContext", {
get: function () {
return this._lineContext;
},
set: function (value) {
if (this._lineContext.leadingLineContent !== value.leadingLineContent
|| this._lineContext.characterCountDelta !== value.characterCountDelta) {
this._refilterKind = this._lineContext.characterCountDelta < value.characterCountDelta && this._filteredItems ? 2 /* Incr */ : 1 /* All */;
this._lineContext = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(CompletionModel.prototype, "items", {
get: function () {
this._ensureCachedState();
return this._filteredItems;
},
enumerable: true,
configurable: true
});
Object.defineProperty(CompletionModel.prototype, "incomplete", {
get: function () {
this._ensureCachedState();
return this._isIncomplete;
},
enumerable: true,
configurable: true
});
CompletionModel.prototype.adopt = function (except) {
var res = new Array();
for (var i = 0; i < this._items.length;) {
if (!except.has(this._items[i].provider)) {
res.push(this._items[i]);
// unordered removed
this._items[i] = this._items[this._items.length - 1];
this._items.pop();
}
else {
// continue with next item
i++;
}
}
this._refilterKind = 1 /* All */;
return res;
};
Object.defineProperty(CompletionModel.prototype, "stats", {
get: function () {
this._ensureCachedState();
return this._stats;
},
enumerable: true,
configurable: true
});
CompletionModel.prototype._ensureCachedState = function () {
if (this._refilterKind !== 0 /* Nothing */) {
this._createCachedState();
}
};
CompletionModel.prototype._createCachedState = function () {
this._isIncomplete = new Set();
this._stats = { suggestionCount: 0, snippetCount: 0, textCount: 0 };
var _a = this._lineContext, leadingLineContent = _a.leadingLineContent, characterCountDelta = _a.characterCountDelta;
var word = '';
var wordLow = '';
// incrementally filter less
var source = this._refilterKind === 1 /* All */ ? this._items : this._filteredItems;
var target = [];
// picks a score function based on the number of
// items that we have to score/filter and based on the
// user-configuration
var scoreFn = (!this._options.filterGraceful || source.length > 2000) ? filters_1.fuzzyScore : filters_1.fuzzyScoreGracefulAggressive;
for (var i = 0; i < source.length; i++) {
var item = source[i];
// collect those supports that signaled having
// an incomplete result
if (item.container.incomplete) {
this._isIncomplete.add(item.provider);
}
// 'word' is that remainder of the current line that we
// filter and score against. In theory each suggestion uses a
// different word, but in practice not - that's why we cache
var overwriteBefore = item.position.column - item.editStart.column;
var wordLen = overwriteBefore + characterCountDelta - (item.position.column - this._column);
if (word.length !== wordLen) {
word = wordLen === 0 ? '' : leadingLineContent.slice(-wordLen);
wordLow = word.toLowerCase();
}
// remember the word against which this item was
// scored
item.word = word;
if (wordLen === 0) {
// when there is nothing to score against, don't
// event try to do. Use a const rank and rely on
// the fallback-sort using the initial sort order.
// use a score of `-100` because that is out of the
// bound of values `fuzzyScore` will return
item.score = filters_1.FuzzyScore.Default;
}
else {
// skip word characters that are whitespace until
// we have hit the replace range (overwriteBefore)
var wordPos = 0;
while (wordPos < overwriteBefore) {
var ch = word.charCodeAt(wordPos);
if (ch === 32 /* Space */ || ch === 9 /* Tab */) {
wordPos += 1;
}
else {
break;
}
}
var textLabel = typeof item.completion.label === 'string' ? item.completion.label : item.completion.label.name;
if (wordPos >= wordLen) {
// the wordPos at which scoring starts is the whole word
// and therefore the same rules as not having a word apply
item.score = filters_1.FuzzyScore.Default;
}
else if (typeof item.completion.filterText === 'string') {
// when there is a `filterText` it must match the `word`.
// if it matches we check with the label to compute highlights
// and if that doesn't yield a result we have no highlights,
// despite having the match
var match = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, false);
if (!match) {
continue; // NO match
}
if (strings_1.compareIgnoreCase(item.completion.filterText, textLabel) === 0) {
// filterText and label are actually the same -> use good highlights
item.score = match;
}
else {
// re-run the scorer on the label in the hope of a result BUT use the rank
// of the filterText-match
item.score = filters_1.anyScore(word, wordLow, wordPos, textLabel, item.labelLow, 0);
item.score[0] = match[0]; // use score from filterText
}
}
else {
// by default match `word` against the `label`
var match = scoreFn(word, wordLow, wordPos, textLabel, item.labelLow, 0, false);
if (!match) {
continue; // NO match
}
item.score = match;
}
}
item.idx = i;
item.distance = this._wordDistance.distance(item.position, item.completion);
target.push(item);
// update stats
this._stats.suggestionCount++;
switch (item.completion.kind) {
case 25 /* Snippet */:
this._stats.snippetCount++;
break;
case 18 /* Text */:
this._stats.textCount++;
break;
}
}
this._filteredItems = target.sort(this._snippetCompareFn);
this._refilterKind = 0 /* Nothing */;
};
CompletionModel._compareCompletionItems = function (a, b) {
if (a.score[0] > b.score[0]) {
return -1;
}
else if (a.score[0] < b.score[0]) {
return 1;
}
else if (a.distance < b.distance) {
return -1;
}
else if (a.distance > b.distance) {
return 1;
}
else if (a.idx < b.idx) {
return -1;
}
else if (a.idx > b.idx) {
return 1;
}
else {
return 0;
}
};
CompletionModel._compareCompletionItemsSnippetsDown = function (a, b) {
if (a.completion.kind !== b.completion.kind) {
if (a.completion.kind === 25 /* Snippet */) {
return 1;
}
else if (b.completion.kind === 25 /* Snippet */) {
return -1;
}
}
return CompletionModel._compareCompletionItems(a, b);
};
CompletionModel._compareCompletionItemsSnippetsUp = function (a, b) {
if (a.completion.kind !== b.completion.kind) {
if (a.completion.kind === 25 /* Snippet */) {
return -1;
}
else if (b.completion.kind === 25 /* Snippet */) {
return 1;
}
}
return CompletionModel._compareCompletionItems(a, b);
};
return CompletionModel;
}());
exports.CompletionModel = CompletionModel;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[390/*vs/editor/contrib/suggest/suggestCommitCharacters*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,79/*vs/editor/common/core/characterClassifier*/]), function (require, exports, arrays_1, lifecycle_1, characterClassifier_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CommitCharacterController = /** @class */ (function () {
function CommitCharacterController(editor, widget, accept) {
var _this = this;
this._disposables = new lifecycle_1.DisposableStore();
this._disposables.add(widget.onDidShow(function () { return _this._onItem(widget.getFocusedItem()); }));
this._disposables.add(widget.onDidFocus(this._onItem, this));
this._disposables.add(widget.onDidHide(this.reset, this));
this._disposables.add(editor.onWillType(function (text) {
if (_this._active && !widget.isFrozen()) {
var ch = text.charCodeAt(text.length - 1);
if (_this._active.acceptCharacters.has(ch) && editor.getOption(0 /* acceptSuggestionOnCommitCharacter */)) {
accept(_this._active.item);
}
}
}));
}
CommitCharacterController.prototype._onItem = function (selected) {
if (!selected || !arrays_1.isNonEmptyArray(selected.item.completion.commitCharacters)) {
// no item or no commit characters
this.reset();
return;
}
if (this._active && this._active.item.item === selected.item) {
// still the same item
return;
}
// keep item and its commit characters
var acceptCharacters = new characterClassifier_1.CharacterSet();
for (var _i = 0, _a = selected.item.completion.commitCharacters; _i < _a.length; _i++) {
var ch = _a[_i];
if (ch.length > 0) {
acceptCharacters.add(ch.charCodeAt(0));
}
}
this._active = { acceptCharacters: acceptCharacters, item: selected };
};
CommitCharacterController.prototype.reset = function () {
this._active = undefined;
};
CommitCharacterController.prototype.dispose = function () {
this._disposables.dispose();
};
return CommitCharacterController;
}());
exports.CommitCharacterController = CommitCharacterController;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[391/*vs/editor/contrib/suggest/suggestRangeHighlighter*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/,4/*vs/base/common/event*/,52/*vs/base/browser/event*/]), function (require, exports, lifecycle_1, range_1, event_1, event_2) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SuggestRangeHighlighter = /** @class */ (function () {
function SuggestRangeHighlighter(_controller) {
var _this = this;
this._controller = _controller;
this._disposables = new lifecycle_1.DisposableStore();
this._decorations = [];
this._disposables.add(_controller.model.onDidSuggest(function (e) {
if (!e.shy) {
var widget = _this._controller.widget.getValue();
var focused = widget.getFocusedItem();
if (focused) {
_this._highlight(focused.item);
}
if (!_this._widgetListener) {
_this._widgetListener = widget.onDidFocus(function (e) { return _this._highlight(e.item); });
}
}
}));
this._disposables.add(_controller.model.onDidCancel(function () {
_this._reset();
}));
}
SuggestRangeHighlighter.prototype.dispose = function () {
this._reset();
this._disposables.dispose();
lifecycle_1.dispose(this._widgetListener);
lifecycle_1.dispose(this._shiftKeyListener);
};
SuggestRangeHighlighter.prototype._reset = function () {
this._decorations = this._controller.editor.deltaDecorations(this._decorations, []);
if (this._shiftKeyListener) {
this._shiftKeyListener.dispose();
this._shiftKeyListener = undefined;
}
};
SuggestRangeHighlighter.prototype._highlight = function (item) {
var _this = this;
var _a;
this._currentItem = item;
var opts = this._controller.editor.getOption(89 /* suggest */);
var newDeco = [];
if (opts.insertHighlight) {
if (!this._shiftKeyListener) {
this._shiftKeyListener = shiftKey.event(function () { return _this._highlight(_this._currentItem); });
}
var info = this._controller.getOverwriteInfo(item, shiftKey.isPressed);
var position = this._controller.editor.getPosition();
if (opts.insertMode === 'insert' && info.overwriteAfter > 0) {
// wants inserts but got replace-mode -> highlight AFTER range
newDeco = [{
range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column + info.overwriteAfter),
options: { inlineClassName: 'suggest-insert-unexpected' }
}];
}
else if (opts.insertMode === 'replace' && info.overwriteAfter === 0) {
// want replace but likely got insert -> highlight AFTER range
var wordInfo = (_a = this._controller.editor.getModel()) === null || _a === void 0 ? void 0 : _a.getWordAtPosition(position);
if (wordInfo && wordInfo.endColumn > position.column) {
newDeco = [{
range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, wordInfo.endColumn),
options: { inlineClassName: 'suggest-insert-unexpected' }
}];
}
}
}
// update editor decorations
this._decorations = this._controller.editor.deltaDecorations(this._decorations, newDeco);
};
return SuggestRangeHighlighter;
}());
exports.SuggestRangeHighlighter = SuggestRangeHighlighter;
var shiftKey = new /** @class */ (function (_super) {
__extends(ShiftKey, _super);
function ShiftKey() {
var _this = _super.call(this) || this;
_this._subscriptions = new lifecycle_1.DisposableStore();
_this._isPressed = false;
_this._subscriptions.add(event_2.domEvent(document.body, 'keydown')(function (e) { return _this.isPressed = e.shiftKey; }));
_this._subscriptions.add(event_2.domEvent(document.body, 'keyup')(function () { return _this.isPressed = false; }));
_this._subscriptions.add(event_2.domEvent(document.body, 'mouseleave')(function () { return _this.isPressed = false; }));
_this._subscriptions.add(event_2.domEvent(document.body, 'blur')(function () { return _this.isPressed = false; }));
return _this;
}
Object.defineProperty(ShiftKey.prototype, "isPressed", {
get: function () {
return this._isPressed;
},
set: function (value) {
if (this._isPressed !== value) {
this._isPressed = value;
this.fire(value);
}
},
enumerable: true,
configurable: true
});
ShiftKey.prototype.dispose = function () {
this._subscriptions.dispose();
_super.prototype.dispose.call(this);
};
return ShiftKey;
}(event_1.Emitter));
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[392/*vs/editor/contrib/suggest/wordDistance*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,3/*vs/editor/common/core/range*/,202/*vs/editor/contrib/smartSelect/bracketSelections*/]), function (require, exports, arrays_1, range_1, bracketSelections_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var WordDistance = /** @class */ (function () {
function WordDistance() {
}
WordDistance.create = function (service, editor) {
return __awaiter(this, void 0, void 0, function () {
var model, position, ranges, wordRanges;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!editor.getOption(89 /* suggest */).localityBonus) {
return [2 /*return*/, WordDistance.None];
}
if (!editor.hasModel()) {
return [2 /*return*/, WordDistance.None];
}
model = editor.getModel();
position = editor.getPosition();
if (!service.canComputeWordRanges(model.uri)) {
return [2 /*return*/, WordDistance.None];
}
return [4 /*yield*/, new bracketSelections_1.BracketSelectionRangeProvider().provideSelectionRanges(model, [position])];
case 1:
ranges = _a.sent();
if (!ranges || ranges.length === 0 || ranges[0].length === 0) {
return [2 /*return*/, WordDistance.None];
}
return [4 /*yield*/, service.computeWordRanges(model.uri, ranges[0][0].range)];
case 2:
wordRanges = _a.sent();
return [2 /*return*/, new /** @class */ (function (_super) {
__extends(class_1, _super);
function class_1() {
return _super !== null && _super.apply(this, arguments) || this;
}
class_1.prototype.distance = function (anchor, suggestion) {
if (!wordRanges || !position.equals(editor.getPosition())) {
return 0;
}
if (suggestion.kind === 17 /* Keyword */) {
return 2 << 20;
}
var word = typeof suggestion.label === 'string' ? suggestion.label : suggestion.label.name;
var wordLines = wordRanges[word];
if (arrays_1.isFalsyOrEmpty(wordLines)) {
return 2 << 20;
}
var idx = arrays_1.binarySearch(wordLines, range_1.Range.fromPositions(anchor), range_1.Range.compareRangesUsingStarts);
var bestWordRange = idx >= 0 ? wordLines[idx] : wordLines[Math.max(0, ~idx - 1)];
var blockDistance = ranges.length;
for (var _i = 0, _a = ranges[0]; _i < _a.length; _i++) {
var range = _a[_i];
if (!range_1.Range.containsRange(range.range, bestWordRange)) {
break;
}
blockDistance -= 1;
}
return blockDistance;
};
return class_1;
}(WordDistance))];
}
});
});
};
WordDistance.None = new /** @class */ (function (_super) {
__extends(class_2, _super);
function class_2() {
return _super !== null && _super.apply(this, arguments) || this;
}
class_2.prototype.distance = function () { return 0; };
return class_2;
}(WordDistance));
return WordDistance;
}());
exports.WordDistance = WordDistance;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[203/*vs/editor/standalone/common/monarch/monarchCommon*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function isFuzzyActionArr(what) {
return (Array.isArray(what));
}
exports.isFuzzyActionArr = isFuzzyActionArr;
function isFuzzyAction(what) {
return !isFuzzyActionArr(what);
}
exports.isFuzzyAction = isFuzzyAction;
function isString(what) {
return (typeof what === 'string');
}
exports.isString = isString;
function isIAction(what) {
return !isString(what);
}
exports.isIAction = isIAction;
// Small helper functions
/**
* Is a string null, undefined, or empty?
*/
function empty(s) {
return (s ? false : true);
}
exports.empty = empty;
/**
* Puts a string to lower case if 'ignoreCase' is set.
*/
function fixCase(lexer, str) {
return (lexer.ignoreCase && str ? str.toLowerCase() : str);
}
exports.fixCase = fixCase;
/**
* Ensures there are no bad characters in a CSS token class.
*/
function sanitize(s) {
return s.replace(/[&<>'"_]/g, '-'); // used on all output token CSS classes
}
exports.sanitize = sanitize;
// Logging
/**
* Logs a message.
*/
function log(lexer, msg) {
console.log(lexer.languageId + ": " + msg);
}
exports.log = log;
// Throwing errors
function createError(lexer, msg) {
return new Error(lexer.languageId + ": " + msg);
}
exports.createError = createError;
// Helper functions for rule finding and substitution
/**
* substituteMatches is used on lexer strings and can substitutes predefined patterns:
* $$ => $
* $# => id
* $n => matched entry n
* @attr => contents of lexer[attr]
*
* See documentation for more info
*/
function substituteMatches(lexer, str, id, matches, state) {
var re = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g;
var stateMatches = null;
return str.replace(re, function (full, sub, dollar, hash, n, s, attr, ofs, total) {
if (!empty(dollar)) {
return '$'; // $$
}
if (!empty(hash)) {
return fixCase(lexer, id); // default $#
}
if (!empty(n) && n < matches.length) {
return fixCase(lexer, matches[n]); // $n
}
if (!empty(attr) && lexer && typeof (lexer[attr]) === 'string') {
return lexer[attr]; //@attribute
}
if (stateMatches === null) { // split state on demand
stateMatches = state.split('.');
stateMatches.unshift(state);
}
if (!empty(s) && s < stateMatches.length) {
return fixCase(lexer, stateMatches[s]); //$Sn
}
return '';
});
}
exports.substituteMatches = substituteMatches;
/**
* Find the tokenizer rules for a specific state (i.e. next action)
*/
function findRules(lexer, inState) {
var state = inState;
while (state && state.length > 0) {
var rules = lexer.tokenizer[state];
if (rules) {
return rules;
}
var idx = state.lastIndexOf('.');
if (idx < 0) {
state = null; // no further parent
}
else {
state = state.substr(0, idx);
}
}
return null;
}
exports.findRules = findRules;
/**
* Is a certain state defined? In contrast to 'findRules' this works on a ILexerMin.
* This is used during compilation where we may know the defined states
* but not yet whether the corresponding rules are correct.
*/
function stateExists(lexer, inState) {
var state = inState;
while (state && state.length > 0) {
var exist = lexer.stateNames[state];
if (exist) {
return true;
}
var idx = state.lastIndexOf('.');
if (idx < 0) {
state = null; // no further parent
}
else {
state = state.substr(0, idx);
}
}
return false;
}
exports.stateExists = stateExists;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[393/*vs/editor/standalone/common/monarch/monarchCompile*/], __M([0/*require*/,1/*exports*/,203/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, monarchCommon) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*
* Type helpers
*
* Note: this is just for sanity checks on the JSON description which is
* helpful for the programmer. No checks are done anymore once the lexer is
* already 'compiled and checked'.
*
*/
function isArrayOf(elemType, obj) {
if (!obj) {
return false;
}
if (!(Array.isArray(obj))) {
return false;
}
for (var _i = 0, obj_1 = obj; _i < obj_1.length; _i++) {
var el = obj_1[_i];
if (!(elemType(el))) {
return false;
}
}
return true;
}
function bool(prop, defValue) {
if (typeof prop === 'boolean') {
return prop;
}
return defValue;
}
function string(prop, defValue) {
if (typeof (prop) === 'string') {
return prop;
}
return defValue;
}
function arrayToHash(array) {
var result = {};
for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
var e = array_1[_i];
result[e] = true;
}
return result;
}
function createKeywordMatcher(arr, caseInsensitive) {
if (caseInsensitive === void 0) { caseInsensitive = false; }
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
var hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
}
else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
// Lexer helpers
/**
* Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.
* Also replaces @\w+ or sequences with the content of the specified attribute
*/
function compileRegExp(lexer, str) {
var n = 0;
while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions
n++;
str = str.replace(/@(\w+)/g, function (s, attr) {
var sub = '';
if (typeof (lexer[attr]) === 'string') {
sub = lexer[attr];
}
else if (lexer[attr] && lexer[attr] instanceof RegExp) {
sub = lexer[attr].source;
}
else {
if (lexer[attr] === undefined) {
throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
}
else {
throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
}
}
return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');
});
}
return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));
}
/**
* Compiles guard functions for case matches.
* This compiles 'cases' attributes into efficient match functions.
*
*/
function selectScrutinee(id, matches, state, num) {
if (num < 0) {
return id;
}
if (num < matches.length) {
return matches[num];
}
if (num >= 100) {
num = num - 100;
var parts = state.split('.');
parts.unshift(state);
if (num < parts.length) {
return parts[num];
}
}
return null;
}
function createGuard(lexer, ruleName, tkey, val) {
// get the scrutinee and pattern
var scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
var oppat = tkey;
var matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
if (matches) {
if (matches[3]) { // if digits
scrut = parseInt(matches[3]);
if (matches[2]) {
scrut = scrut + 100; // if [sS] present
}
}
oppat = matches[4];
}
// get operator
var op = '~';
var pat = oppat;
if (!oppat || oppat.length === 0) {
op = '!=';
pat = '';
}
else if (/^\w*$/.test(pat)) { // just a word
op = '==';
}
else {
matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
if (matches) {
op = matches[1];
pat = matches[2];
}
}
// set the tester function
var tester;
// special case a regexp that matches just words
if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
var inWords_1 = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
tester = function (s) { return (op === '~' ? inWords_1(s) : !inWords_1(s)); };
}
else if (op === '@' || op === '!@') {
var words = lexer[pat];
if (!words) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
}
if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
}
var inWords_2 = createKeywordMatcher(words, lexer.ignoreCase);
tester = function (s) { return (op === '@' ? inWords_2(s) : !inWords_2(s)); };
}
else if (op === '~' || op === '!~') {
if (pat.indexOf('$') < 0) {
// precompile regular expression
var re_1 = compileRegExp(lexer, '^' + pat + '$');
tester = function (s) { return (op === '~' ? re_1.test(s) : !re_1.test(s)); };
}
else {
tester = function (s, id, matches, state) {
var re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$');
return re.test(s);
};
}
}
else { // if (op==='==' || op==='!=') {
if (pat.indexOf('$') < 0) {
var patx_1 = monarchCommon.fixCase(lexer, pat);
tester = function (s) { return (op === '==' ? s === patx_1 : s !== patx_1); };
}
else {
var patx_2 = monarchCommon.fixCase(lexer, pat);
tester = function (s, id, matches, state, eos) {
var patexp = monarchCommon.substituteMatches(lexer, patx_2, id, matches, state);
return (op === '==' ? s === patexp : s !== patexp);
};
}
}
// return the branch object
if (scrut === -1) {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
return tester(id, id, matches, state, eos);
}
};
}
else {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
var scrutinee = selectScrutinee(id, matches, state, scrut);
return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
}
};
}
}
/**
* Compiles an action: i.e. optimize regular expressions and case matches
* and do many sanity checks.
*
* This is called only during compilation but if the lexer definition
* contains user functions as actions (which is usually not allowed), then this
* may be called during lexing. It is important therefore to compile common cases efficiently
*/
function compileAction(lexer, ruleName, action) {
if (!action) {
return { token: '' };
}
else if (typeof (action) === 'string') {
return action; // { token: action };
}
else if (action.token || action.token === '') {
if (typeof (action.token) !== 'string') {
throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
}
else {
// only copy specific typed fields (only happens once during compile Lexer)
var newAction = { token: action.token };
if (action.token.indexOf('$') >= 0) {
newAction.tokenSubst = true;
}
if (typeof (action.bracket) === 'string') {
if (action.bracket === '@open') {
newAction.bracket = 1 /* Open */;
}
else if (action.bracket === '@close') {
newAction.bracket = -1 /* Close */;
}
else {
throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
}
}
if (action.next) {
if (typeof (action.next) !== 'string') {
throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
}
else {
var next = action.next;
if (!/^(@pop|@push|@popall)$/.test(next)) {
if (next[0] === '@') {
next = next.substr(1); // peel off starting @ sign
}
if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
}
}
}
newAction.next = next;
}
}
if (typeof (action.goBack) === 'number') {
newAction.goBack = action.goBack;
}
if (typeof (action.switchTo) === 'string') {
newAction.switchTo = action.switchTo;
}
if (typeof (action.log) === 'string') {
newAction.log = action.log;
}
if (typeof (action.nextEmbedded) === 'string') {
newAction.nextEmbedded = action.nextEmbedded;
lexer.usesEmbedded = true;
}
return newAction;
}
}
else if (Array.isArray(action)) {
var results = [];
for (var i = 0, len = action.length; i < len; i++) {
results[i] = compileAction(lexer, ruleName, action[i]);
}
return { group: results };
}
else if (action.cases) {
// build an array of test cases
var cases_1 = [];
// for each case, push a test function and result value
for (var tkey in action.cases) {
if (action.cases.hasOwnProperty(tkey)) {
var val = compileAction(lexer, ruleName, action.cases[tkey]);
// what kind of case
if (tkey === '@default' || tkey === '@' || tkey === '') {
cases_1.push({ test: undefined, value: val, name: tkey });
}
else if (tkey === '@eos') {
cases_1.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
}
else {
cases_1.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
}
}
}
// create a matching function
var def_1 = lexer.defaultToken;
return {
test: function (id, matches, state, eos) {
for (var _i = 0, cases_2 = cases_1; _i < cases_2.length; _i++) {
var _case = cases_2[_i];
var didmatch = (!_case.test || _case.test(id, matches, state, eos));
if (didmatch) {
return _case.value;
}
}
return def_1;
}
};
}
else {
throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
}
}
/**
* Helper class for creating matching rules
*/
var Rule = /** @class */ (function () {
function Rule(name) {
this.regex = new RegExp('');
this.action = { token: '' };
this.matchOnlyAtLineStart = false;
this.name = '';
this.name = name;
}
Rule.prototype.setRegex = function (lexer, re) {
var sregex;
if (typeof (re) === 'string') {
sregex = re;
}
else if (re instanceof RegExp) {
sregex = re.source;
}
else {
throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
}
this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
this.name = this.name + ': ' + sregex;
this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')');
};
Rule.prototype.setAction = function (lexer, act) {
this.action = compileAction(lexer, this.name, act);
};
return Rule;
}());
/**
* Compiles a json description function into json where all regular expressions,
* case matches etc, are compiled and all include rules are expanded.
* We also compile the bracket definitions, supply defaults, and do many sanity checks.
* If the 'jsonStrict' parameter is 'false', we allow at certain locations
* regular expression objects and functions that get called during lexing.
* (Currently we have no samples that need this so perhaps we should always have
* jsonStrict to true).
*/
function compile(languageId, json) {
if (!json || typeof (json) !== 'object') {
throw new Error('Monarch: expecting a language definition object');
}
// Create our lexer
var lexer = {};
lexer.languageId = languageId;
lexer.noThrow = false; // raise exceptions during compilation
lexer.maxStack = 100;
// Set standard fields: be defensive about types
lexer.start = (typeof json.start === 'string' ? json.start : null);
lexer.ignoreCase = bool(json.ignoreCase, false);
lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
lexer.defaultToken = string(json.defaultToken, 'source');
lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
// For calling compileAction later on
var lexerMin = json;
lexerMin.languageId = languageId;
lexerMin.ignoreCase = lexer.ignoreCase;
lexerMin.noThrow = lexer.noThrow;
lexerMin.usesEmbedded = lexer.usesEmbedded;
lexerMin.stateNames = json.tokenizer;
lexerMin.defaultToken = lexer.defaultToken;
// Compile an array of rules into newrules where RegExp objects are created.
function addRules(state, newrules, rules) {
for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
var rule = rules_1[_i];
var include = rule.include;
if (include) {
if (typeof (include) !== 'string') {
throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
}
if (include[0] === '@') {
include = include.substr(1); // peel off starting @
}
if (!json.tokenizer[include]) {
throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
}
addRules(state + '.' + include, newrules, json.tokenizer[include]);
}
else {
var newrule = new Rule(state);
// Set up new rule attributes
if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
newrule.setRegex(lexerMin, rule[0]);
if (rule.length >= 3) {
if (typeof (rule[1]) === 'string') {
newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
}
else if (typeof (rule[1]) === 'object') {
var rule1 = rule[1];
rule1.next = rule[2];
newrule.setAction(lexerMin, rule1);
}
else {
throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
}
}
else {
newrule.setAction(lexerMin, rule[1]);
}
}
else {
if (!rule.regex) {
throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
}
if (rule.name) {
if (typeof rule.name === 'string') {
newrule.name = rule.name;
}
}
if (rule.matchOnlyAtStart) {
newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
}
newrule.setRegex(lexerMin, rule.regex);
newrule.setAction(lexerMin, rule.action);
}
newrules.push(newrule);
}
}
}
// compile the tokenizer rules
if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
}
lexer.tokenizer = [];
for (var key in json.tokenizer) {
if (json.tokenizer.hasOwnProperty(key)) {
if (!lexer.start) {
lexer.start = key;
}
var rules = json.tokenizer[key];
lexer.tokenizer[key] = new Array();
addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
}
}
lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
// Set simple brackets
if (json.brackets) {
if (!(Array.isArray(json.brackets))) {
throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array');
}
}
else {
json.brackets = [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }
];
}
var brackets = [];
for (var _i = 0, _a = json.brackets; _i < _a.length; _i++) {
var el = _a[_i];
var desc = el;
if (desc && Array.isArray(desc) && desc.length === 3) {
desc = { token: desc[2], open: desc[0], close: desc[1] };
}
if (desc.open === desc.close) {
throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
'\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
}
if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
brackets.push({
token: desc.token + lexer.tokenPostfix,
open: monarchCommon.fixCase(lexer, desc.open),
close: monarchCommon.fixCase(lexer, desc.close)
});
}
else {
throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
}
}
lexer.brackets = brackets;
// Disable throw so the syntax highlighter goes, no matter what
lexer.noThrow = true;
return lexer;
}
exports.compile = compile;
});
define(__m[394/*vs/nls!vs/base/browser/ui/actionbar/actionbar*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/actionbar/actionbar", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[70/*vs/base/browser/ui/actionbar/actionbar*/], __M([0/*require*/,1/*exports*/,16/*vs/base/common/platform*/,394/*vs/nls!vs/base/browser/ui/actionbar/actionbar*/,2/*vs/base/common/lifecycle*/,55/*vs/base/common/actions*/,6/*vs/base/browser/dom*/,21/*vs/base/common/types*/,57/*vs/base/browser/touch*/,56/*vs/base/browser/keyboardEvent*/,4/*vs/base/common/event*/,98/*vs/base/browser/dnd*/,24/*vs/base/browser/browser*/,259/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, platform, nls, lifecycle_1, actions_1, DOM, types, touch_1, keyboardEvent_1, event_1, dnd_1, browser_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BaseActionViewItem = /** @class */ (function (_super) {
__extends(BaseActionViewItem, _super);
function BaseActionViewItem(context, action, options) {
var _this = _super.call(this) || this;
_this.options = options;
_this._context = context || _this;
_this._action = action;
if (action instanceof actions_1.Action) {
_this._register(action.onDidChange(function (event) {
if (!_this.element) {
// we have not been rendered yet, so there
// is no point in updating the UI
return;
}
_this.handleActionChangeEvent(event);
}));
}
return _this;
}
BaseActionViewItem.prototype.handleActionChangeEvent = function (event) {
if (event.enabled !== undefined) {
this.updateEnabled();
}
if (event.checked !== undefined) {
this.updateChecked();
}
if (event.class !== undefined) {
this.updateClass();
}
if (event.label !== undefined) {
this.updateLabel();
this.updateTooltip();
}
if (event.tooltip !== undefined) {
this.updateTooltip();
}
};
Object.defineProperty(BaseActionViewItem.prototype, "actionRunner", {
get: function () {
if (!this._actionRunner) {
this._actionRunner = this._register(new actions_1.ActionRunner());
}
return this._actionRunner;
},
set: function (actionRunner) {
this._actionRunner = actionRunner;
},
enumerable: true,
configurable: true
});
BaseActionViewItem.prototype.getAction = function () {
return this._action;
};
BaseActionViewItem.prototype.isEnabled = function () {
return this._action.enabled;
};
BaseActionViewItem.prototype.setActionContext = function (newContext) {
this._context = newContext;
};
BaseActionViewItem.prototype.render = function (container) {
var _this = this;
var element = this.element = container;
this._register(touch_1.Gesture.addTarget(container));
var enableDragging = this.options && this.options.draggable;
if (enableDragging) {
container.draggable = true;
if (browser_1.isFirefox) {
// Firefox: requires to set a text data transfer to get going
this._register(DOM.addDisposableListener(container, DOM.EventType.DRAG_START, function (e) { var _a; return (_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.setData(dnd_1.DataTransfers.TEXT, _this._action.label); }));
}
}
this._register(DOM.addDisposableListener(element, touch_1.EventType.Tap, function (e) { return _this.onClick(e); }));
this._register(DOM.addDisposableListener(element, DOM.EventType.MOUSE_DOWN, function (e) {
if (!enableDragging) {
DOM.EventHelper.stop(e, true); // do not run when dragging is on because that would disable it
}
if (_this._action.enabled && e.button === 0) {
DOM.addClass(element, 'active');
}
}));
this._register(DOM.addDisposableListener(element, DOM.EventType.CLICK, function (e) {
DOM.EventHelper.stop(e, true);
// See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Interact_with_the_clipboard
// > Writing to the clipboard
// > You can use the "cut" and "copy" commands without any special
// permission if you are using them in a short-lived event handler
// for a user action (for example, a click handler).
// => to get the Copy and Paste context menu actions working on Firefox,
// there should be no timeout here
if (_this.options && _this.options.isMenu) {
_this.onClick(e);
}
else {
platform.setImmediate(function () { return _this.onClick(e); });
}
}));
this._register(DOM.addDisposableListener(element, DOM.EventType.DBLCLICK, function (e) {
DOM.EventHelper.stop(e, true);
}));
[DOM.EventType.MOUSE_UP, DOM.EventType.MOUSE_OUT].forEach(function (event) {
_this._register(DOM.addDisposableListener(element, event, function (e) {
DOM.EventHelper.stop(e);
DOM.removeClass(element, 'active');
}));
});
};
BaseActionViewItem.prototype.onClick = function (event) {
DOM.EventHelper.stop(event, true);
var context;
if (types.isUndefinedOrNull(this._context)) {
context = event;
}
else {
context = this._context;
if (types.isObject(context)) {
context.event = event;
}
}
this.actionRunner.run(this._action, context);
};
BaseActionViewItem.prototype.focus = function () {
if (this.element) {
this.element.focus();
DOM.addClass(this.element, 'focused');
}
};
BaseActionViewItem.prototype.blur = function () {
if (this.element) {
this.element.blur();
DOM.removeClass(this.element, 'focused');
}
};
BaseActionViewItem.prototype.updateEnabled = function () {
// implement in subclass
};
BaseActionViewItem.prototype.updateLabel = function () {
// implement in subclass
};
BaseActionViewItem.prototype.updateTooltip = function () {
// implement in subclass
};
BaseActionViewItem.prototype.updateClass = function () {
// implement in subclass
};
BaseActionViewItem.prototype.updateChecked = function () {
// implement in subclass
};
BaseActionViewItem.prototype.dispose = function () {
if (this.element) {
DOM.removeNode(this.element);
this.element = undefined;
}
_super.prototype.dispose.call(this);
};
return BaseActionViewItem;
}(lifecycle_1.Disposable));
exports.BaseActionViewItem = BaseActionViewItem;
var Separator = /** @class */ (function (_super) {
__extends(Separator, _super);
function Separator(label) {
var _this = _super.call(this, Separator.ID, label, label ? 'separator text' : 'separator') || this;
_this.checked = false;
_this.enabled = false;
return _this;
}
Separator.ID = 'vs.actions.separator';
return Separator;
}(actions_1.Action));
exports.Separator = Separator;
var ActionViewItem = /** @class */ (function (_super) {
__extends(ActionViewItem, _super);
function ActionViewItem(context, action, options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, context, action, options) || this;
_this.options = options;
_this.options.icon = options.icon !== undefined ? options.icon : false;
_this.options.label = options.label !== undefined ? options.label : true;
_this.cssClass = '';
return _this;
}
ActionViewItem.prototype.render = function (container) {
_super.prototype.render.call(this, container);
if (this.element) {
this.label = DOM.append(this.element, DOM.$('a.action-label'));
}
if (this.label) {
if (this._action.id === Separator.ID) {
this.label.setAttribute('role', 'presentation'); // A separator is a presentation item
}
else {
if (this.options.isMenu) {
this.label.setAttribute('role', 'menuitem');
}
else {
this.label.setAttribute('role', 'button');
}
}
}
if (this.options.label && this.options.keybinding && this.element) {
DOM.append(this.element, DOM.$('span.keybinding')).textContent = this.options.keybinding;
}
this.updateClass();
this.updateLabel();
this.updateTooltip();
this.updateEnabled();
this.updateChecked();
};
ActionViewItem.prototype.focus = function () {
_super.prototype.focus.call(this);
if (this.label) {
this.label.focus();
}
};
ActionViewItem.prototype.updateLabel = function () {
if (this.options.label && this.label) {
this.label.textContent = this.getAction().label;
}
};
ActionViewItem.prototype.updateTooltip = function () {
var title = null;
if (this.getAction().tooltip) {
title = this.getAction().tooltip;
}
else if (!this.options.label && this.getAction().label && this.options.icon) {
title = this.getAction().label;
if (this.options.keybinding) {
title = nls.localize(0, null, title, this.options.keybinding);
}
}
if (title && this.label) {
this.label.title = title;
}
};
ActionViewItem.prototype.updateClass = function () {
if (this.cssClass && this.label) {
DOM.removeClasses(this.label, this.cssClass);
}
if (this.options.icon) {
this.cssClass = this.getAction().class;
if (this.label) {
DOM.addClass(this.label, 'codicon');
if (this.cssClass) {
DOM.addClasses(this.label, this.cssClass);
}
}
this.updateEnabled();
}
else {
if (this.label) {
DOM.removeClass(this.label, 'codicon');
}
}
};
ActionViewItem.prototype.updateEnabled = function () {
if (this.getAction().enabled) {
if (this.label) {
this.label.removeAttribute('aria-disabled');
DOM.removeClass(this.label, 'disabled');
this.label.tabIndex = 0;
}
if (this.element) {
DOM.removeClass(this.element, 'disabled');
}
}
else {
if (this.label) {
this.label.setAttribute('aria-disabled', 'true');
DOM.addClass(this.label, 'disabled');
DOM.removeTabIndexAndUpdateFocus(this.label);
}
if (this.element) {
DOM.addClass(this.element, 'disabled');
}
}
};
ActionViewItem.prototype.updateChecked = function () {
if (this.label) {
if (this.getAction().checked) {
DOM.addClass(this.label, 'checked');
}
else {
DOM.removeClass(this.label, 'checked');
}
}
};
return ActionViewItem;
}(BaseActionViewItem));
exports.ActionViewItem = ActionViewItem;
var defaultOptions = {
orientation: 0 /* HORIZONTAL */,
context: null,
triggerKeys: {
keys: [3 /* Enter */, 10 /* Space */],
keyDown: false
}
};
var ActionBar = /** @class */ (function (_super) {
__extends(ActionBar, _super);
function ActionBar(container, options) {
if (options === void 0) { options = defaultOptions; }
var _this = _super.call(this) || this;
_this._onDidBlur = _this._register(new event_1.Emitter());
_this.onDidBlur = _this._onDidBlur.event;
_this._onDidCancel = _this._register(new event_1.Emitter());
_this.onDidCancel = _this._onDidCancel.event;
_this._onDidRun = _this._register(new event_1.Emitter());
_this.onDidRun = _this._onDidRun.event;
_this._onDidBeforeRun = _this._register(new event_1.Emitter());
_this.onDidBeforeRun = _this._onDidBeforeRun.event;
_this.options = options;
_this._context = options.context;
if (!_this.options.triggerKeys) {
_this.options.triggerKeys = defaultOptions.triggerKeys;
}
if (_this.options.actionRunner) {
_this._actionRunner = _this.options.actionRunner;
}
else {
_this._actionRunner = new actions_1.ActionRunner();
_this._register(_this._actionRunner);
}
_this._register(_this._actionRunner.onDidRun(function (e) { return _this._onDidRun.fire(e); }));
_this._register(_this._actionRunner.onDidBeforeRun(function (e) { return _this._onDidBeforeRun.fire(e); }));
_this.viewItems = [];
_this.focusedItem = undefined;
_this.domNode = document.createElement('div');
_this.domNode.className = 'monaco-action-bar';
if (options.animated !== false) {
DOM.addClass(_this.domNode, 'animated');
}
var previousKey;
var nextKey;
switch (_this.options.orientation) {
case 0 /* HORIZONTAL */:
previousKey = 15 /* LeftArrow */;
nextKey = 17 /* RightArrow */;
break;
case 1 /* HORIZONTAL_REVERSE */:
previousKey = 17 /* RightArrow */;
nextKey = 15 /* LeftArrow */;
_this.domNode.className += ' reverse';
break;
case 2 /* VERTICAL */:
previousKey = 16 /* UpArrow */;
nextKey = 18 /* DownArrow */;
_this.domNode.className += ' vertical';
break;
case 3 /* VERTICAL_REVERSE */:
previousKey = 18 /* DownArrow */;
nextKey = 16 /* UpArrow */;
_this.domNode.className += ' vertical reverse';
break;
}
_this._register(DOM.addDisposableListener(_this.domNode, DOM.EventType.KEY_DOWN, function (e) {
var event = new keyboardEvent_1.StandardKeyboardEvent(e);
var eventHandled = true;
if (event.equals(previousKey)) {
_this.focusPrevious();
}
else if (event.equals(nextKey)) {
_this.focusNext();
}
else if (event.equals(9 /* Escape */)) {
_this.cancel();
}
else if (_this.isTriggerKeyEvent(event)) {
// Staying out of the else branch even if not triggered
if (_this.options.triggerKeys && _this.options.triggerKeys.keyDown) {
_this.doTrigger(event);
}
}
else {
eventHandled = false;
}
if (eventHandled) {
event.preventDefault();
event.stopPropagation();
}
}));
_this._register(DOM.addDisposableListener(_this.domNode, DOM.EventType.KEY_UP, function (e) {
var event = new keyboardEvent_1.StandardKeyboardEvent(e);
// Run action on Enter/Space
if (_this.isTriggerKeyEvent(event)) {
if (_this.options.triggerKeys && !_this.options.triggerKeys.keyDown) {
_this.doTrigger(event);
}
event.preventDefault();
event.stopPropagation();
}
// Recompute focused item
else if (event.equals(2 /* Tab */) || event.equals(1024 /* Shift */ | 2 /* Tab */)) {
_this.updateFocusedItem();
}
}));
_this.focusTracker = _this._register(DOM.trackFocus(_this.domNode));
_this._register(_this.focusTracker.onDidBlur(function () {
if (document.activeElement === _this.domNode || !DOM.isAncestor(document.activeElement, _this.domNode)) {
_this._onDidBlur.fire();
_this.focusedItem = undefined;
}
}));
_this._register(_this.focusTracker.onDidFocus(function () { return _this.updateFocusedItem(); }));
_this.actionsList = document.createElement('ul');
_this.actionsList.className = 'actions-container';
_this.actionsList.setAttribute('role', 'toolbar');
if (_this.options.ariaLabel) {
_this.actionsList.setAttribute('aria-label', _this.options.ariaLabel);
}
_this.domNode.appendChild(_this.actionsList);
container.appendChild(_this.domNode);
return _this;
}
ActionBar.prototype.isTriggerKeyEvent = function (event) {
var ret = false;
if (this.options.triggerKeys) {
this.options.triggerKeys.keys.forEach(function (keyCode) {
ret = ret || event.equals(keyCode);
});
}
return ret;
};
ActionBar.prototype.updateFocusedItem = function () {
for (var i = 0; i < this.actionsList.children.length; i++) {
var elem = this.actionsList.children[i];
if (DOM.isAncestor(document.activeElement, elem)) {
this.focusedItem = i;
break;
}
}
};
Object.defineProperty(ActionBar.prototype, "context", {
get: function () {
return this._context;
},
set: function (context) {
this._context = context;
this.viewItems.forEach(function (i) { return i.setActionContext(context); });
},
enumerable: true,
configurable: true
});
ActionBar.prototype.getContainer = function () {
return this.domNode;
};
ActionBar.prototype.push = function (arg, options) {
var _this = this;
if (options === void 0) { options = {}; }
var actions = Array.isArray(arg) ? arg : [arg];
var index = types.isNumber(options.index) ? options.index : null;
actions.forEach(function (action) {
var actionViewItemElement = document.createElement('li');
actionViewItemElement.className = 'action-item';
actionViewItemElement.setAttribute('role', 'presentation');
// Prevent native context menu on actions
_this._register(DOM.addDisposableListener(actionViewItemElement, DOM.EventType.CONTEXT_MENU, function (e) {
e.preventDefault();
e.stopPropagation();
}));
var item;
if (_this.options.actionViewItemProvider) {
item = _this.options.actionViewItemProvider(action);
}
if (!item) {
item = new ActionViewItem(_this.context, action, options);
}
item.actionRunner = _this._actionRunner;
item.setActionContext(_this.context);
item.render(actionViewItemElement);
if (index === null || index < 0 || index >= _this.actionsList.children.length) {
_this.actionsList.appendChild(actionViewItemElement);
_this.viewItems.push(item);
}
else {
_this.actionsList.insertBefore(actionViewItemElement, _this.actionsList.children[index]);
_this.viewItems.splice(index, 0, item);
index++;
}
});
};
ActionBar.prototype.clear = function () {
this.viewItems = lifecycle_1.dispose(this.viewItems);
DOM.clearNode(this.actionsList);
};
ActionBar.prototype.isEmpty = function () {
return this.viewItems.length === 0;
};
ActionBar.prototype.focus = function (arg) {
var selectFirst = false;
var index = undefined;
if (arg === undefined) {
selectFirst = true;
}
else if (typeof arg === 'number') {
index = arg;
}
else if (typeof arg === 'boolean') {
selectFirst = arg;
}
if (selectFirst && typeof this.focusedItem === 'undefined') {
// Focus the first enabled item
this.focusedItem = this.viewItems.length - 1;
this.focusNext();
}
else {
if (index !== undefined) {
this.focusedItem = index;
}
this.updateFocus();
}
};
ActionBar.prototype.focusNext = function () {
if (typeof this.focusedItem === 'undefined') {
this.focusedItem = this.viewItems.length - 1;
}
var startIndex = this.focusedItem;
var item;
do {
this.focusedItem = (this.focusedItem + 1) % this.viewItems.length;
item = this.viewItems[this.focusedItem];
} while (this.focusedItem !== startIndex && !item.isEnabled());
if (this.focusedItem === startIndex && !item.isEnabled()) {
this.focusedItem = undefined;
}
this.updateFocus();
};
ActionBar.prototype.focusPrevious = function () {
if (typeof this.focusedItem === 'undefined') {
this.focusedItem = 0;
}
var startIndex = this.focusedItem;
var item;
do {
this.focusedItem = this.focusedItem - 1;
if (this.focusedItem < 0) {
this.focusedItem = this.viewItems.length - 1;
}
item = this.viewItems[this.focusedItem];
} while (this.focusedItem !== startIndex && !item.isEnabled());
if (this.focusedItem === startIndex && !item.isEnabled()) {
this.focusedItem = undefined;
}
this.updateFocus(true);
};
ActionBar.prototype.updateFocus = function (fromRight, preventScroll) {
if (typeof this.focusedItem === 'undefined') {
this.actionsList.focus({ preventScroll: preventScroll });
}
for (var i = 0; i < this.viewItems.length; i++) {
var item = this.viewItems[i];
var actionViewItem = item;
if (i === this.focusedItem) {
if (types.isFunction(actionViewItem.isEnabled)) {
if (actionViewItem.isEnabled() && types.isFunction(actionViewItem.focus)) {
actionViewItem.focus(fromRight);
}
else {
this.actionsList.focus({ preventScroll: preventScroll });
}
}
}
else {
if (types.isFunction(actionViewItem.blur)) {
actionViewItem.blur();
}
}
}
};
ActionBar.prototype.doTrigger = function (event) {
if (typeof this.focusedItem === 'undefined') {
return; //nothing to focus
}
// trigger action
var actionViewItem = this.viewItems[this.focusedItem];
if (actionViewItem instanceof BaseActionViewItem) {
var context = (actionViewItem._context === null || actionViewItem._context === undefined) ? event : actionViewItem._context;
this.run(actionViewItem._action, context);
}
};
ActionBar.prototype.cancel = function () {
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur(); // remove focus from focused action
}
this._onDidCancel.fire();
};
ActionBar.prototype.run = function (action, context) {
return this._actionRunner.run(action, context);
};
ActionBar.prototype.dispose = function () {
lifecycle_1.dispose(this.viewItems);
this.viewItems = [];
DOM.removeNode(this.getContainer());
_super.prototype.dispose.call(this);
};
return ActionBar;
}(lifecycle_1.Disposable));
exports.ActionBar = ActionBar;
});
define(__m[395/*vs/nls!vs/base/browser/ui/aria/aria*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/aria/aria", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[50/*vs/base/browser/ui/aria/aria*/], __M([0/*require*/,1/*exports*/,395/*vs/nls!vs/base/browser/ui/aria/aria*/,16/*vs/base/common/platform*/,6/*vs/base/browser/dom*/,260/*vs/css!vs/base/browser/ui/aria/aria*/]), function (require, exports, nls, platform_1, dom) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ariaContainer;
var alertContainer;
var statusContainer;
function setARIAContainer(parent) {
ariaContainer = document.createElement('div');
ariaContainer.className = 'monaco-aria-container';
alertContainer = document.createElement('div');
alertContainer.className = 'monaco-alert';
alertContainer.setAttribute('role', 'alert');
alertContainer.setAttribute('aria-atomic', 'true');
ariaContainer.appendChild(alertContainer);
statusContainer = document.createElement('div');
statusContainer.className = 'monaco-status';
statusContainer.setAttribute('role', 'status');
statusContainer.setAttribute('aria-atomic', 'true');
ariaContainer.appendChild(statusContainer);
parent.appendChild(ariaContainer);
}
exports.setARIAContainer = setARIAContainer;
/**
* Given the provided message, will make sure that it is read as alert to screen readers.
*/
function alert(msg, disableRepeat) {
insertMessage(alertContainer, msg, disableRepeat);
}
exports.alert = alert;
/**
* Given the provided message, will make sure that it is read as status to screen readers.
*/
function status(msg, disableRepeat) {
if (platform_1.isMacintosh) {
alert(msg, disableRepeat); // VoiceOver does not seem to support status role
}
else {
insertMessage(statusContainer, msg, disableRepeat);
}
}
exports.status = status;
var repeatedTimes = 0;
var prevText = undefined;
function insertMessage(target, msg, disableRepeat) {
if (!ariaContainer) {
return;
}
// If the same message should be inserted that is already present, a screen reader would
// not announce this message because it matches the previous one. As a workaround, we
// alter the message with the number of occurences unless this is explicitly disabled
// via the disableRepeat flag.
if (!disableRepeat) {
if (prevText === msg) {
repeatedTimes++;
}
else {
prevText = msg;
repeatedTimes = 0;
}
switch (repeatedTimes) {
case 0: break;
case 1:
msg = nls.localize(0, null, msg);
break;
default:
msg = nls.localize(1, null, msg, repeatedTimes);
break;
}
}
dom.clearNode(target);
target.textContent = msg;
// See https://www.paciellogroup.com/blog/2012/06/html5-accessibility-chops-aria-rolealert-browser-support/
target.style.visibility = 'hidden';
target.style.visibility = 'visible';
}
});
define(__m[396/*vs/nls!vs/base/browser/ui/findinput/findInput*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/findInput", data); });
define(__m[397/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/findInputCheckboxes", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[204/*vs/base/browser/ui/findinput/findInputCheckboxes*/], __M([0/*require*/,1/*exports*/,138/*vs/base/browser/ui/checkbox/checkbox*/,397/*vs/nls!vs/base/browser/ui/findinput/findInputCheckboxes*/]), function (require, exports, checkbox_1, nls) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var NLS_CASE_SENSITIVE_CHECKBOX_LABEL = nls.localize(0, null);
var NLS_WHOLE_WORD_CHECKBOX_LABEL = nls.localize(1, null);
var NLS_REGEX_CHECKBOX_LABEL = nls.localize(2, null);
var CaseSensitiveCheckbox = /** @class */ (function (_super) {
__extends(CaseSensitiveCheckbox, _super);
function CaseSensitiveCheckbox(opts) {
return _super.call(this, {
actionClassName: 'codicon-case-sensitive',
title: NLS_CASE_SENSITIVE_CHECKBOX_LABEL + opts.appendTitle,
isChecked: opts.isChecked,
inputActiveOptionBorder: opts.inputActiveOptionBorder,
inputActiveOptionBackground: opts.inputActiveOptionBackground
}) || this;
}
return CaseSensitiveCheckbox;
}(checkbox_1.Checkbox));
exports.CaseSensitiveCheckbox = CaseSensitiveCheckbox;
var WholeWordsCheckbox = /** @class */ (function (_super) {
__extends(WholeWordsCheckbox, _super);
function WholeWordsCheckbox(opts) {
return _super.call(this, {
actionClassName: 'codicon-whole-word',
title: NLS_WHOLE_WORD_CHECKBOX_LABEL + opts.appendTitle,
isChecked: opts.isChecked,
inputActiveOptionBorder: opts.inputActiveOptionBorder,
inputActiveOptionBackground: opts.inputActiveOptionBackground
}) || this;
}
return WholeWordsCheckbox;
}(checkbox_1.Checkbox));
exports.WholeWordsCheckbox = WholeWordsCheckbox;
var RegexCheckbox = /** @class */ (function (_super) {
__extends(RegexCheckbox, _super);
function RegexCheckbox(opts) {
return _super.call(this, {
actionClassName: 'codicon-regex',
title: NLS_REGEX_CHECKBOX_LABEL + opts.appendTitle,
isChecked: opts.isChecked,
inputActiveOptionBorder: opts.inputActiveOptionBorder,
inputActiveOptionBackground: opts.inputActiveOptionBackground
}) || this;
}
return RegexCheckbox;
}(checkbox_1.Checkbox));
exports.RegexCheckbox = RegexCheckbox;
});
define(__m[398/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/findinput/replaceInput", data); });
define(__m[399/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/inputbox/inputBox", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[152/*vs/base/browser/ui/inputbox/inputBox*/], __M([0/*require*/,1/*exports*/,399/*vs/nls!vs/base/browser/ui/inputbox/inputBox*/,24/*vs/base/browser/browser*/,6/*vs/base/browser/dom*/,134/*vs/base/browser/formattedTextRenderer*/,50/*vs/base/browser/ui/aria/aria*/,70/*vs/base/browser/ui/actionbar/actionbar*/,4/*vs/base/common/event*/,47/*vs/base/browser/ui/widget*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,242/*vs/base/common/history*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,52/*vs/base/browser/event*/,269/*vs/css!vs/base/browser/ui/inputbox/inputBox*/]), function (require, exports, nls, Bal, dom, formattedTextRenderer_1, aria, actionbar_1, event_1, widget_1, color_1, objects_1, history_1, scrollableElement_1, event_2) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var $ = dom.$;
var defaultOpts = {
inputBackground: color_1.Color.fromHex('#3C3C3C'),
inputForeground: color_1.Color.fromHex('#CCCCCC'),
inputValidationInfoBorder: color_1.Color.fromHex('#55AAFF'),
inputValidationInfoBackground: color_1.Color.fromHex('#063B49'),
inputValidationWarningBorder: color_1.Color.fromHex('#B89500'),
inputValidationWarningBackground: color_1.Color.fromHex('#352A05'),
inputValidationErrorBorder: color_1.Color.fromHex('#BE1100'),
inputValidationErrorBackground: color_1.Color.fromHex('#5A1D1D')
};
var InputBox = /** @class */ (function (_super) {
__extends(InputBox, _super);
function InputBox(container, contextViewProvider, options) {
var _this = _super.call(this) || this;
_this.state = 'idle';
_this.maxHeight = Number.POSITIVE_INFINITY;
_this._onDidChange = _this._register(new event_1.Emitter());
_this.onDidChange = _this._onDidChange.event;
_this._onDidHeightChange = _this._register(new event_1.Emitter());
_this.onDidHeightChange = _this._onDidHeightChange.event;
_this.contextViewProvider = contextViewProvider;
_this.options = options || Object.create(null);
objects_1.mixin(_this.options, defaultOpts, false);
_this.message = null;
_this.placeholder = _this.options.placeholder || '';
_this.ariaLabel = _this.options.ariaLabel || '';
_this.inputBackground = _this.options.inputBackground;
_this.inputForeground = _this.options.inputForeground;
_this.inputBorder = _this.options.inputBorder;
_this.inputValidationInfoBorder = _this.options.inputValidationInfoBorder;
_this.inputValidationInfoBackground = _this.options.inputValidationInfoBackground;
_this.inputValidationInfoForeground = _this.options.inputValidationInfoForeground;
_this.inputValidationWarningBorder = _this.options.inputValidationWarningBorder;
_this.inputValidationWarningBackground = _this.options.inputValidationWarningBackground;
_this.inputValidationWarningForeground = _this.options.inputValidationWarningForeground;
_this.inputValidationErrorBorder = _this.options.inputValidationErrorBorder;
_this.inputValidationErrorBackground = _this.options.inputValidationErrorBackground;
_this.inputValidationErrorForeground = _this.options.inputValidationErrorForeground;
if (_this.options.validationOptions) {
_this.validation = _this.options.validationOptions.validation;
}
_this.element = dom.append(container, $('.monaco-inputbox.idle'));
var tagName = _this.options.flexibleHeight ? 'textarea' : 'input';
var wrapper = dom.append(_this.element, $('.wrapper'));
_this.input = dom.append(wrapper, $(tagName + '.input.empty'));
_this.input.setAttribute('autocorrect', 'off');
_this.input.setAttribute('autocapitalize', 'off');
_this.input.setAttribute('spellcheck', 'false');
_this.onfocus(_this.input, function () { return dom.addClass(_this.element, 'synthetic-focus'); });
_this.onblur(_this.input, function () { return dom.removeClass(_this.element, 'synthetic-focus'); });
if (_this.options.flexibleHeight) {
_this.maxHeight = typeof _this.options.flexibleMaxHeight === 'number' ? _this.options.flexibleMaxHeight : Number.POSITIVE_INFINITY;
_this.mirror = dom.append(wrapper, $('div.mirror'));
_this.mirror.innerHTML = ' ';
_this.scrollableElement = new scrollableElement_1.ScrollableElement(_this.element, { vertical: 1 /* Auto */ });
if (_this.options.flexibleWidth) {
_this.input.setAttribute('wrap', 'off');
_this.mirror.style.whiteSpace = 'pre';
_this.mirror.style.wordWrap = 'initial';
}
dom.append(container, _this.scrollableElement.getDomNode());
_this._register(_this.scrollableElement);
// from ScrollableElement to DOM
_this._register(_this.scrollableElement.onScroll(function (e) { return _this.input.scrollTop = e.scrollTop; }));
var onSelectionChange = event_1.Event.filter(event_2.domEvent(document, 'selectionchange'), function () {
var selection = document.getSelection();
return (selection === null || selection === void 0 ? void 0 : selection.anchorNode) === wrapper;
});
// from DOM to ScrollableElement
_this._register(onSelectionChange(_this.updateScrollDimensions, _this));
_this._register(_this.onDidHeightChange(_this.updateScrollDimensions, _this));
}
else {
_this.input.type = _this.options.type || 'text';
_this.input.setAttribute('wrap', 'off');
}
if (_this.ariaLabel) {
_this.input.setAttribute('aria-label', _this.ariaLabel);
}
if (_this.placeholder) {
_this.setPlaceHolder(_this.placeholder);
}
_this.oninput(_this.input, function () { return _this.onValueChange(); });
_this.onblur(_this.input, function () { return _this.onBlur(); });
_this.onfocus(_this.input, function () { return _this.onFocus(); });
// Add placeholder shim for IE because IE decides to hide the placeholder on focus (we dont want that!)
if (_this.placeholder && Bal.isIE) {
_this.onclick(_this.input, function (e) {
dom.EventHelper.stop(e, true);
_this.input.focus();
});
}
_this.ignoreGesture(_this.input);
setTimeout(function () { return _this.updateMirror(); }, 0);
// Support actions
if (_this.options.actions) {
_this.actionbar = _this._register(new actionbar_1.ActionBar(_this.element));
_this.actionbar.push(_this.options.actions, { icon: true, label: false });
}
_this.applyStyles();
return _this;
}
InputBox.prototype.onBlur = function () {
this._hideMessage();
};
InputBox.prototype.onFocus = function () {
this._showMessage();
};
InputBox.prototype.setPlaceHolder = function (placeHolder) {
this.placeholder = placeHolder;
this.input.setAttribute('placeholder', placeHolder);
this.input.title = placeHolder;
};
InputBox.prototype.setAriaLabel = function (label) {
this.ariaLabel = label;
if (label) {
this.input.setAttribute('aria-label', this.ariaLabel);
}
else {
this.input.removeAttribute('aria-label');
}
};
Object.defineProperty(InputBox.prototype, "inputElement", {
get: function () {
return this.input;
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputBox.prototype, "value", {
get: function () {
return this.input.value;
},
set: function (newValue) {
if (this.input.value !== newValue) {
this.input.value = newValue;
this.onValueChange();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputBox.prototype, "height", {
get: function () {
return typeof this.cachedHeight === 'number' ? this.cachedHeight : dom.getTotalHeight(this.element);
},
enumerable: true,
configurable: true
});
InputBox.prototype.focus = function () {
this.input.focus();
};
InputBox.prototype.blur = function () {
this.input.blur();
};
InputBox.prototype.hasFocus = function () {
return document.activeElement === this.input;
};
InputBox.prototype.select = function (range) {
if (range === void 0) { range = null; }
this.input.select();
if (range) {
this.input.setSelectionRange(range.start, range.end);
}
};
InputBox.prototype.enable = function () {
this.input.removeAttribute('disabled');
};
InputBox.prototype.disable = function () {
this.blur();
this.input.disabled = true;
this._hideMessage();
};
Object.defineProperty(InputBox.prototype, "width", {
get: function () {
return dom.getTotalWidth(this.input);
},
set: function (width) {
if (this.options.flexibleHeight && this.options.flexibleWidth) {
// textarea with horizontal scrolling
var horizontalPadding = 0;
if (this.mirror) {
var paddingLeft = parseFloat(this.mirror.style.paddingLeft || '') || 0;
var paddingRight = parseFloat(this.mirror.style.paddingRight || '') || 0;
horizontalPadding = paddingLeft + paddingRight;
}
this.input.style.width = (width - horizontalPadding) + 'px';
}
else {
this.input.style.width = width + 'px';
}
if (this.mirror) {
this.mirror.style.width = width + 'px';
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(InputBox.prototype, "paddingRight", {
set: function (paddingRight) {
if (this.options.flexibleHeight && this.options.flexibleWidth) {
this.input.style.width = "calc(100% - " + paddingRight + "px)";
}
else {
this.input.style.paddingRight = paddingRight + 'px';
}
if (this.mirror) {
this.mirror.style.paddingRight = paddingRight + 'px';
}
},
enumerable: true,
configurable: true
});
InputBox.prototype.updateScrollDimensions = function () {
if (typeof this.cachedContentHeight !== 'number' || typeof this.cachedHeight !== 'number' || !this.scrollableElement) {
return;
}
var scrollHeight = this.cachedContentHeight;
var height = this.cachedHeight;
var scrollTop = this.input.scrollTop;
this.scrollableElement.setScrollDimensions({ scrollHeight: scrollHeight, height: height });
this.scrollableElement.setScrollPosition({ scrollTop: scrollTop });
};
InputBox.prototype.showMessage = function (message, force) {
this.message = message;
dom.removeClass(this.element, 'idle');
dom.removeClass(this.element, 'info');
dom.removeClass(this.element, 'warning');
dom.removeClass(this.element, 'error');
dom.addClass(this.element, this.classForType(message.type));
var styles = this.stylesForType(this.message.type);
this.element.style.border = styles.border ? "1px solid " + styles.border : '';
// ARIA Support
var alertText;
if (message.type === 3 /* ERROR */) {
alertText = nls.localize(0, null, message.content);
}
else if (message.type === 2 /* WARNING */) {
alertText = nls.localize(1, null, message.content);
}
else {
alertText = nls.localize(2, null, message.content);
}
aria.alert(alertText);
if (this.hasFocus() || force) {
this._showMessage();
}
};
InputBox.prototype.hideMessage = function () {
this.message = null;
dom.removeClass(this.element, 'info');
dom.removeClass(this.element, 'warning');
dom.removeClass(this.element, 'error');
dom.addClass(this.element, 'idle');
this._hideMessage();
this.applyStyles();
};
InputBox.prototype.validate = function () {
var errorMsg = null;
if (this.validation) {
errorMsg = this.validation(this.value);
if (errorMsg) {
this.inputElement.setAttribute('aria-invalid', 'true');
this.showMessage(errorMsg);
}
else if (this.inputElement.hasAttribute('aria-invalid')) {
this.inputElement.removeAttribute('aria-invalid');
this.hideMessage();
}
}
return !errorMsg;
};
InputBox.prototype.stylesForType = function (type) {
switch (type) {
case 1 /* INFO */: return { border: this.inputValidationInfoBorder, background: this.inputValidationInfoBackground, foreground: this.inputValidationInfoForeground };
case 2 /* WARNING */: return { border: this.inputValidationWarningBorder, background: this.inputValidationWarningBackground, foreground: this.inputValidationWarningForeground };
default: return { border: this.inputValidationErrorBorder, background: this.inputValidationErrorBackground, foreground: this.inputValidationErrorForeground };
}
};
InputBox.prototype.classForType = function (type) {
switch (type) {
case 1 /* INFO */: return 'info';
case 2 /* WARNING */: return 'warning';
default: return 'error';
}
};
InputBox.prototype._showMessage = function () {
var _this = this;
if (!this.contextViewProvider || !this.message) {
return;
}
var div;
var layout = function () { return div.style.width = dom.getTotalWidth(_this.element) + 'px'; };
this.contextViewProvider.showContextView({
getAnchor: function () { return _this.element; },
anchorAlignment: 1 /* RIGHT */,
render: function (container) {
if (!_this.message) {
return null;
}
div = dom.append(container, $('.monaco-inputbox-container'));
layout();
var renderOptions = {
inline: true,
className: 'monaco-inputbox-message'
};
var spanElement = (_this.message.formatContent
? formattedTextRenderer_1.renderFormattedText(_this.message.content, renderOptions)
: formattedTextRenderer_1.renderText(_this.message.content, renderOptions));
dom.addClass(spanElement, _this.classForType(_this.message.type));
var styles = _this.stylesForType(_this.message.type);
spanElement.style.backgroundColor = styles.background ? styles.background.toString() : '';
spanElement.style.color = styles.foreground ? styles.foreground.toString() : '';
spanElement.style.border = styles.border ? "1px solid " + styles.border : '';
dom.append(div, spanElement);
return null;
},
onHide: function () {
_this.state = 'closed';
},
layout: layout
});
this.state = 'open';
};
InputBox.prototype._hideMessage = function () {
if (!this.contextViewProvider) {
return;
}
if (this.state === 'open') {
this.contextViewProvider.hideContextView();
}
this.state = 'idle';
};
InputBox.prototype.onValueChange = function () {
this._onDidChange.fire(this.value);
this.validate();
this.updateMirror();
dom.toggleClass(this.input, 'empty', !this.value);
if (this.state === 'open' && this.contextViewProvider) {
this.contextViewProvider.layout();
}
};
InputBox.prototype.updateMirror = function () {
if (!this.mirror) {
return;
}
var value = this.value;
var lastCharCode = value.charCodeAt(value.length - 1);
var suffix = lastCharCode === 10 ? ' ' : '';
var mirrorTextContent = value + suffix;
if (mirrorTextContent) {
this.mirror.textContent = value + suffix;
}
else {
this.mirror.innerHTML = ' ';
}
this.layout();
};
InputBox.prototype.style = function (styles) {
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
};
InputBox.prototype.applyStyles = function () {
var background = this.inputBackground ? this.inputBackground.toString() : '';
var foreground = this.inputForeground ? this.inputForeground.toString() : '';
var border = this.inputBorder ? this.inputBorder.toString() : '';
this.element.style.backgroundColor = background;
this.element.style.color = foreground;
this.input.style.backgroundColor = background;
this.input.style.color = foreground;
this.element.style.borderWidth = border ? '1px' : '';
this.element.style.borderStyle = border ? 'solid' : '';
this.element.style.borderColor = border;
};
InputBox.prototype.layout = function () {
if (!this.mirror) {
return;
}
var previousHeight = this.cachedContentHeight;
this.cachedContentHeight = dom.getTotalHeight(this.mirror);
if (previousHeight !== this.cachedContentHeight) {
this.cachedHeight = Math.min(this.cachedContentHeight, this.maxHeight);
this.input.style.height = this.cachedHeight + 'px';
this._onDidHeightChange.fire(this.cachedContentHeight);
}
};
InputBox.prototype.insertAtCursor = function (text) {
var inputElement = this.inputElement;
var start = inputElement.selectionStart;
var end = inputElement.selectionEnd;
var content = inputElement.value;
if (start !== null && end !== null) {
this.value = content.substr(0, start) + text + content.substr(end);
inputElement.setSelectionRange(start + 1, start + 1);
this.layout();
}
};
InputBox.prototype.dispose = function () {
this._hideMessage();
this.message = null;
if (this.actionbar) {
this.actionbar.dispose();
}
_super.prototype.dispose.call(this);
};
return InputBox;
}(widget_1.Widget));
exports.InputBox = InputBox;
var HistoryInputBox = /** @class */ (function (_super) {
__extends(HistoryInputBox, _super);
function HistoryInputBox(container, contextViewProvider, options) {
var _this = _super.call(this, container, contextViewProvider, options) || this;
_this.history = new history_1.HistoryNavigator(options.history, 100);
return _this;
}
HistoryInputBox.prototype.addToHistory = function () {
if (this.value && this.value !== this.getCurrentValue()) {
this.history.add(this.value);
}
};
HistoryInputBox.prototype.showNextValue = function () {
if (!this.history.has(this.value)) {
this.addToHistory();
}
var next = this.getNextValue();
if (next) {
next = next === this.value ? this.getNextValue() : next;
}
if (next) {
this.value = next;
aria.status(this.value);
}
};
HistoryInputBox.prototype.showPreviousValue = function () {
if (!this.history.has(this.value)) {
this.addToHistory();
}
var previous = this.getPreviousValue();
if (previous) {
previous = previous === this.value ? this.getPreviousValue() : previous;
}
if (previous) {
this.value = previous;
aria.status(this.value);
}
};
HistoryInputBox.prototype.getCurrentValue = function () {
var currentValue = this.history.current();
if (!currentValue) {
currentValue = this.history.last();
this.history.next();
}
return currentValue;
};
HistoryInputBox.prototype.getPreviousValue = function () {
return this.history.previous() || this.history.first();
};
HistoryInputBox.prototype.getNextValue = function () {
return this.history.next() || this.history.last();
};
return HistoryInputBox;
}(InputBox));
exports.HistoryInputBox = HistoryInputBox;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[400/*vs/base/browser/ui/findinput/findInput*/], __M([0/*require*/,1/*exports*/,396/*vs/nls!vs/base/browser/ui/findinput/findInput*/,6/*vs/base/browser/dom*/,152/*vs/base/browser/ui/inputbox/inputBox*/,47/*vs/base/browser/ui/widget*/,4/*vs/base/common/event*/,204/*vs/base/browser/ui/findinput/findInputCheckboxes*/,184/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, nls, dom, inputBox_1, widget_1, event_1, findInputCheckboxes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var NLS_DEFAULT_LABEL = nls.localize(0, null);
var FindInput = /** @class */ (function (_super) {
__extends(FindInput, _super);
function FindInput(parent, contextViewProvider, _showOptionButtons, options) {
var _this = _super.call(this) || this;
_this._showOptionButtons = _showOptionButtons;
_this.fixFocusOnOptionClickEnabled = true;
_this._onDidOptionChange = _this._register(new event_1.Emitter());
_this.onDidOptionChange = _this._onDidOptionChange.event;
_this._onKeyDown = _this._register(new event_1.Emitter());
_this.onKeyDown = _this._onKeyDown.event;
_this._onMouseDown = _this._register(new event_1.Emitter());
_this.onMouseDown = _this._onMouseDown.event;
_this._onInput = _this._register(new event_1.Emitter());
_this._onKeyUp = _this._register(new event_1.Emitter());
_this._onCaseSensitiveKeyDown = _this._register(new event_1.Emitter());
_this.onCaseSensitiveKeyDown = _this._onCaseSensitiveKeyDown.event;
_this._onRegexKeyDown = _this._register(new event_1.Emitter());
_this.onRegexKeyDown = _this._onRegexKeyDown.event;
_this._lastHighlightFindOptions = 0;
_this.contextViewProvider = contextViewProvider;
_this.placeholder = options.placeholder || '';
_this.validation = options.validation;
_this.label = options.label || NLS_DEFAULT_LABEL;
_this.inputActiveOptionBorder = options.inputActiveOptionBorder;
_this.inputActiveOptionBackground = options.inputActiveOptionBackground;
_this.inputBackground = options.inputBackground;
_this.inputForeground = options.inputForeground;
_this.inputBorder = options.inputBorder;
_this.inputValidationInfoBorder = options.inputValidationInfoBorder;
_this.inputValidationInfoBackground = options.inputValidationInfoBackground;
_this.inputValidationInfoForeground = options.inputValidationInfoForeground;
_this.inputValidationWarningBorder = options.inputValidationWarningBorder;
_this.inputValidationWarningBackground = options.inputValidationWarningBackground;
_this.inputValidationWarningForeground = options.inputValidationWarningForeground;
_this.inputValidationErrorBorder = options.inputValidationErrorBorder;
_this.inputValidationErrorBackground = options.inputValidationErrorBackground;
_this.inputValidationErrorForeground = options.inputValidationErrorForeground;
var appendCaseSensitiveLabel = options.appendCaseSensitiveLabel || '';
var appendWholeWordsLabel = options.appendWholeWordsLabel || '';
var appendRegexLabel = options.appendRegexLabel || '';
var history = options.history || [];
var flexibleHeight = !!options.flexibleHeight;
var flexibleWidth = !!options.flexibleWidth;
var flexibleMaxHeight = options.flexibleMaxHeight;
_this.domNode = document.createElement('div');
dom.addClass(_this.domNode, 'monaco-findInput');
_this.inputBox = _this._register(new inputBox_1.HistoryInputBox(_this.domNode, _this.contextViewProvider, {
placeholder: _this.placeholder || '',
ariaLabel: _this.label || '',
validationOptions: {
validation: _this.validation
},
inputBackground: _this.inputBackground,
inputForeground: _this.inputForeground,
inputBorder: _this.inputBorder,
inputValidationInfoBackground: _this.inputValidationInfoBackground,
inputValidationInfoForeground: _this.inputValidationInfoForeground,
inputValidationInfoBorder: _this.inputValidationInfoBorder,
inputValidationWarningBackground: _this.inputValidationWarningBackground,
inputValidationWarningForeground: _this.inputValidationWarningForeground,
inputValidationWarningBorder: _this.inputValidationWarningBorder,
inputValidationErrorBackground: _this.inputValidationErrorBackground,
inputValidationErrorForeground: _this.inputValidationErrorForeground,
inputValidationErrorBorder: _this.inputValidationErrorBorder,
history: history,
flexibleHeight: flexibleHeight,
flexibleWidth: flexibleWidth,
flexibleMaxHeight: flexibleMaxHeight
}));
_this.regex = _this._register(new findInputCheckboxes_1.RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: _this.inputActiveOptionBorder,
inputActiveOptionBackground: _this.inputActiveOptionBackground
}));
_this._register(_this.regex.onChange(function (viaKeyboard) {
_this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && _this.fixFocusOnOptionClickEnabled) {
_this.inputBox.focus();
}
_this.validate();
}));
_this._register(_this.regex.onKeyDown(function (e) {
_this._onRegexKeyDown.fire(e);
}));
_this.wholeWords = _this._register(new findInputCheckboxes_1.WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: _this.inputActiveOptionBorder,
inputActiveOptionBackground: _this.inputActiveOptionBackground
}));
_this._register(_this.wholeWords.onChange(function (viaKeyboard) {
_this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && _this.fixFocusOnOptionClickEnabled) {
_this.inputBox.focus();
}
_this.validate();
}));
_this.caseSensitive = _this._register(new findInputCheckboxes_1.CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: _this.inputActiveOptionBorder,
inputActiveOptionBackground: _this.inputActiveOptionBackground
}));
_this._register(_this.caseSensitive.onChange(function (viaKeyboard) {
_this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && _this.fixFocusOnOptionClickEnabled) {
_this.inputBox.focus();
}
_this.validate();
}));
_this._register(_this.caseSensitive.onKeyDown(function (e) {
_this._onCaseSensitiveKeyDown.fire(e);
}));
if (_this._showOptionButtons) {
_this.inputBox.paddingRight = _this.caseSensitive.width() + _this.wholeWords.width() + _this.regex.width();
}
// Arrow-Key support to navigate between options
var indexes = [_this.caseSensitive.domNode, _this.wholeWords.domNode, _this.regex.domNode];
_this.onkeydown(_this.domNode, function (event) {
if (event.equals(15 /* LeftArrow */) || event.equals(17 /* RightArrow */) || event.equals(9 /* Escape */)) {
var index = indexes.indexOf(document.activeElement);
if (index >= 0) {
var newIndex = -1;
if (event.equals(17 /* RightArrow */)) {
newIndex = (index + 1) % indexes.length;
}
else if (event.equals(15 /* LeftArrow */)) {
if (index === 0) {
newIndex = indexes.length - 1;
}
else {
newIndex = index - 1;
}
}
if (event.equals(9 /* Escape */)) {
indexes[index].blur();
}
else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
var controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = _this._showOptionButtons ? 'block' : 'none';
controls.appendChild(_this.caseSensitive.domNode);
controls.appendChild(_this.wholeWords.domNode);
controls.appendChild(_this.regex.domNode);
_this.domNode.appendChild(controls);
if (parent) {
parent.appendChild(_this.domNode);
}
_this.onkeydown(_this.inputBox.inputElement, function (e) { return _this._onKeyDown.fire(e); });
_this.onkeyup(_this.inputBox.inputElement, function (e) { return _this._onKeyUp.fire(e); });
_this.oninput(_this.inputBox.inputElement, function (e) { return _this._onInput.fire(); });
_this.onmousedown(_this.inputBox.inputElement, function (e) { return _this._onMouseDown.fire(e); });
return _this;
}
FindInput.prototype.enable = function () {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
};
FindInput.prototype.disable = function () {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
};
FindInput.prototype.setFocusInputOnOptionClick = function (value) {
this.fixFocusOnOptionClickEnabled = value;
};
FindInput.prototype.setEnabled = function (enabled) {
if (enabled) {
this.enable();
}
else {
this.disable();
}
};
FindInput.prototype.getValue = function () {
return this.inputBox.value;
};
FindInput.prototype.setValue = function (value) {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
};
FindInput.prototype.style = function (styles) {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputActiveOptionBackground = styles.inputActiveOptionBackground;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
};
FindInput.prototype.applyStyles = function () {
if (this.domNode) {
var checkBoxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
inputActiveOptionBackground: this.inputActiveOptionBackground,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
var inputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
};
FindInput.prototype.select = function () {
this.inputBox.select();
};
FindInput.prototype.focus = function () {
this.inputBox.focus();
};
FindInput.prototype.getCaseSensitive = function () {
return this.caseSensitive.checked;
};
FindInput.prototype.setCaseSensitive = function (value) {
this.caseSensitive.checked = value;
};
FindInput.prototype.getWholeWords = function () {
return this.wholeWords.checked;
};
FindInput.prototype.setWholeWords = function (value) {
this.wholeWords.checked = value;
};
FindInput.prototype.getRegex = function () {
return this.regex.checked;
};
FindInput.prototype.setRegex = function (value) {
this.regex.checked = value;
this.validate();
};
FindInput.prototype.focusOnCaseSensitive = function () {
this.caseSensitive.focus();
};
FindInput.prototype.highlightFindOptions = function () {
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
};
FindInput.prototype.validate = function () {
this.inputBox.validate();
};
FindInput.prototype.clearMessage = function () {
this.inputBox.hideMessage();
};
return FindInput;
}(widget_1.Widget));
exports.FindInput = FindInput;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[401/*vs/base/browser/ui/findinput/replaceInput*/], __M([0/*require*/,1/*exports*/,398/*vs/nls!vs/base/browser/ui/findinput/replaceInput*/,6/*vs/base/browser/dom*/,152/*vs/base/browser/ui/inputbox/inputBox*/,47/*vs/base/browser/ui/widget*/,4/*vs/base/common/event*/,138/*vs/base/browser/ui/checkbox/checkbox*/,184/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, nls, dom, inputBox_1, widget_1, event_1, checkbox_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var NLS_DEFAULT_LABEL = nls.localize(0, null);
var NLS_PRESERVE_CASE_LABEL = nls.localize(1, null);
var PreserveCaseCheckbox = /** @class */ (function (_super) {
__extends(PreserveCaseCheckbox, _super);
function PreserveCaseCheckbox(opts) {
return _super.call(this, {
// TODO: does this need its own icon?
actionClassName: 'codicon-preserve-case',
title: NLS_PRESERVE_CASE_LABEL + opts.appendTitle,
isChecked: opts.isChecked,
inputActiveOptionBorder: opts.inputActiveOptionBorder,
inputActiveOptionBackground: opts.inputActiveOptionBackground
}) || this;
}
return PreserveCaseCheckbox;
}(checkbox_1.Checkbox));
exports.PreserveCaseCheckbox = PreserveCaseCheckbox;
var ReplaceInput = /** @class */ (function (_super) {
__extends(ReplaceInput, _super);
function ReplaceInput(parent, contextViewProvider, _showOptionButtons, options) {
var _this = _super.call(this) || this;
_this._showOptionButtons = _showOptionButtons;
_this.fixFocusOnOptionClickEnabled = true;
_this.cachedOptionsWidth = 0;
_this._onDidOptionChange = _this._register(new event_1.Emitter());
_this.onDidOptionChange = _this._onDidOptionChange.event;
_this._onKeyDown = _this._register(new event_1.Emitter());
_this.onKeyDown = _this._onKeyDown.event;
_this._onMouseDown = _this._register(new event_1.Emitter());
_this._onInput = _this._register(new event_1.Emitter());
_this._onKeyUp = _this._register(new event_1.Emitter());
_this._onPreserveCaseKeyDown = _this._register(new event_1.Emitter());
_this.onPreserveCaseKeyDown = _this._onPreserveCaseKeyDown.event;
_this.contextViewProvider = contextViewProvider;
_this.placeholder = options.placeholder || '';
_this.validation = options.validation;
_this.label = options.label || NLS_DEFAULT_LABEL;
_this.inputActiveOptionBorder = options.inputActiveOptionBorder;
_this.inputActiveOptionBackground = options.inputActiveOptionBackground;
_this.inputBackground = options.inputBackground;
_this.inputForeground = options.inputForeground;
_this.inputBorder = options.inputBorder;
_this.inputValidationInfoBorder = options.inputValidationInfoBorder;
_this.inputValidationInfoBackground = options.inputValidationInfoBackground;
_this.inputValidationInfoForeground = options.inputValidationInfoForeground;
_this.inputValidationWarningBorder = options.inputValidationWarningBorder;
_this.inputValidationWarningBackground = options.inputValidationWarningBackground;
_this.inputValidationWarningForeground = options.inputValidationWarningForeground;
_this.inputValidationErrorBorder = options.inputValidationErrorBorder;
_this.inputValidationErrorBackground = options.inputValidationErrorBackground;
_this.inputValidationErrorForeground = options.inputValidationErrorForeground;
var history = options.history || [];
var flexibleHeight = !!options.flexibleHeight;
var flexibleWidth = !!options.flexibleWidth;
var flexibleMaxHeight = options.flexibleMaxHeight;
_this.domNode = document.createElement('div');
dom.addClass(_this.domNode, 'monaco-findInput');
_this.inputBox = _this._register(new inputBox_1.HistoryInputBox(_this.domNode, _this.contextViewProvider, {
ariaLabel: _this.label || '',
placeholder: _this.placeholder || '',
validationOptions: {
validation: _this.validation
},
inputBackground: _this.inputBackground,
inputForeground: _this.inputForeground,
inputBorder: _this.inputBorder,
inputValidationInfoBackground: _this.inputValidationInfoBackground,
inputValidationInfoForeground: _this.inputValidationInfoForeground,
inputValidationInfoBorder: _this.inputValidationInfoBorder,
inputValidationWarningBackground: _this.inputValidationWarningBackground,
inputValidationWarningForeground: _this.inputValidationWarningForeground,
inputValidationWarningBorder: _this.inputValidationWarningBorder,
inputValidationErrorBackground: _this.inputValidationErrorBackground,
inputValidationErrorForeground: _this.inputValidationErrorForeground,
inputValidationErrorBorder: _this.inputValidationErrorBorder,
history: history,
flexibleHeight: flexibleHeight,
flexibleWidth: flexibleWidth,
flexibleMaxHeight: flexibleMaxHeight
}));
_this.preserveCase = _this._register(new PreserveCaseCheckbox({
appendTitle: '',
isChecked: false,
inputActiveOptionBorder: _this.inputActiveOptionBorder,
inputActiveOptionBackground: _this.inputActiveOptionBackground,
}));
_this._register(_this.preserveCase.onChange(function (viaKeyboard) {
_this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && _this.fixFocusOnOptionClickEnabled) {
_this.inputBox.focus();
}
_this.validate();
}));
_this._register(_this.preserveCase.onKeyDown(function (e) {
_this._onPreserveCaseKeyDown.fire(e);
}));
if (_this._showOptionButtons) {
_this.cachedOptionsWidth = _this.preserveCase.width();
}
else {
_this.cachedOptionsWidth = 0;
}
// Arrow-Key support to navigate between options
var indexes = [_this.preserveCase.domNode];
_this.onkeydown(_this.domNode, function (event) {
if (event.equals(15 /* LeftArrow */) || event.equals(17 /* RightArrow */) || event.equals(9 /* Escape */)) {
var index = indexes.indexOf(document.activeElement);
if (index >= 0) {
var newIndex = -1;
if (event.equals(17 /* RightArrow */)) {
newIndex = (index + 1) % indexes.length;
}
else if (event.equals(15 /* LeftArrow */)) {
if (index === 0) {
newIndex = indexes.length - 1;
}
else {
newIndex = index - 1;
}
}
if (event.equals(9 /* Escape */)) {
indexes[index].blur();
}
else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
var controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = _this._showOptionButtons ? 'block' : 'none';
controls.appendChild(_this.preserveCase.domNode);
_this.domNode.appendChild(controls);
if (parent) {
parent.appendChild(_this.domNode);
}
_this.onkeydown(_this.inputBox.inputElement, function (e) { return _this._onKeyDown.fire(e); });
_this.onkeyup(_this.inputBox.inputElement, function (e) { return _this._onKeyUp.fire(e); });
_this.oninput(_this.inputBox.inputElement, function (e) { return _this._onInput.fire(); });
_this.onmousedown(_this.inputBox.inputElement, function (e) { return _this._onMouseDown.fire(e); });
return _this;
}
ReplaceInput.prototype.enable = function () {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.preserveCase.enable();
};
ReplaceInput.prototype.disable = function () {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.preserveCase.disable();
};
ReplaceInput.prototype.setEnabled = function (enabled) {
if (enabled) {
this.enable();
}
else {
this.disable();
}
};
ReplaceInput.prototype.style = function (styles) {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputActiveOptionBackground = styles.inputActiveOptionBackground;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
};
ReplaceInput.prototype.applyStyles = function () {
if (this.domNode) {
var checkBoxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
inputActiveOptionBackground: this.inputActiveOptionBackground,
};
this.preserveCase.style(checkBoxStyles);
var inputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
};
ReplaceInput.prototype.select = function () {
this.inputBox.select();
};
ReplaceInput.prototype.focus = function () {
this.inputBox.focus();
};
ReplaceInput.prototype.getPreserveCase = function () {
return this.preserveCase.checked;
};
ReplaceInput.prototype.setPreserveCase = function (value) {
this.preserveCase.checked = value;
};
ReplaceInput.prototype.focusOnPreserve = function () {
this.preserveCase.focus();
};
ReplaceInput.prototype.validate = function () {
if (this.inputBox) {
this.inputBox.validate();
}
};
Object.defineProperty(ReplaceInput.prototype, "width", {
set: function (newWidth) {
this.inputBox.paddingRight = this.cachedOptionsWidth;
this.inputBox.width = newWidth;
this.domNode.style.width = newWidth + 'px';
},
enumerable: true,
configurable: true
});
ReplaceInput.prototype.dispose = function () {
_super.prototype.dispose.call(this);
};
return ReplaceInput;
}(widget_1.Widget));
exports.ReplaceInput = ReplaceInput;
});
define(__m[402/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/keybindingLabel/keybindingLabel", data); });
define(__m[403/*vs/nls!vs/base/browser/ui/list/listWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/list/listWidget", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[153/*vs/base/browser/ui/list/listWidget*/], __M([0/*require*/,1/*exports*/,403/*vs/nls!vs/base/browser/ui/list/listWidget*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/types*/,19/*vs/base/common/arrays*/,101/*vs/base/common/decorators*/,6/*vs/base/browser/dom*/,16/*vs/base/common/platform*/,57/*vs/base/browser/touch*/,56/*vs/base/browser/keyboardEvent*/,4/*vs/base/common/event*/,52/*vs/base/browser/event*/,239/*vs/base/browser/ui/list/list*/,140/*vs/base/browser/ui/list/listView*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,240/*vs/base/browser/ui/list/splice*/,131/*vs/base/common/numbers*/,61/*vs/base/common/filters*/,271/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, nls_1, lifecycle_1, types_1, arrays_1, decorators_1, DOM, platform, touch_1, keyboardEvent_1, event_1, event_2, list_1, listView_1, color_1, objects_1, splice_1, numbers_1, filters_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TraitRenderer = /** @class */ (function () {
function TraitRenderer(trait) {
this.trait = trait;
this.renderedElements = [];
}
Object.defineProperty(TraitRenderer.prototype, "templateId", {
get: function () {
return "template:" + this.trait.trait;
},
enumerable: true,
configurable: true
});
TraitRenderer.prototype.renderTemplate = function (container) {
return container;
};
TraitRenderer.prototype.renderElement = function (element, index, templateData) {
var renderedElementIndex = arrays_1.firstIndex(this.renderedElements, function (el) { return el.templateData === templateData; });
if (renderedElementIndex >= 0) {
var rendered = this.renderedElements[renderedElementIndex];
this.trait.unrender(templateData);
rendered.index = index;
}
else {
var rendered = { index: index, templateData: templateData };
this.renderedElements.push(rendered);
}
this.trait.renderIndex(index, templateData);
};
TraitRenderer.prototype.splice = function (start, deleteCount, insertCount) {
var rendered = [];
for (var _i = 0, _a = this.renderedElements; _i < _a.length; _i++) {
var renderedElement = _a[_i];
if (renderedElement.index < start) {
rendered.push(renderedElement);
}
else if (renderedElement.index >= start + deleteCount) {
rendered.push({
index: renderedElement.index + insertCount - deleteCount,
templateData: renderedElement.templateData
});
}
}
this.renderedElements = rendered;
};
TraitRenderer.prototype.renderIndexes = function (indexes) {
for (var _i = 0, _a = this.renderedElements; _i < _a.length; _i++) {
var _b = _a[_i], index = _b.index, templateData = _b.templateData;
if (indexes.indexOf(index) > -1) {
this.trait.renderIndex(index, templateData);
}
}
};
TraitRenderer.prototype.disposeTemplate = function (templateData) {
var index = arrays_1.firstIndex(this.renderedElements, function (el) { return el.templateData === templateData; });
if (index < 0) {
return;
}
this.renderedElements.splice(index, 1);
};
return TraitRenderer;
}());
var Trait = /** @class */ (function () {
function Trait(_trait) {
this._trait = _trait;
this.indexes = [];
this.sortedIndexes = [];
this._onChange = new event_1.Emitter();
this.onChange = this._onChange.event;
}
Object.defineProperty(Trait.prototype, "trait", {
get: function () { return this._trait; },
enumerable: true,
configurable: true
});
Object.defineProperty(Trait.prototype, "renderer", {
get: function () {
return new TraitRenderer(this);
},
enumerable: true,
configurable: true
});
Trait.prototype.splice = function (start, deleteCount, elements) {
var diff = elements.length - deleteCount;
var end = start + deleteCount;
var indexes = __spreadArrays(this.sortedIndexes.filter(function (i) { return i < start; }), elements.map(function (hasTrait, i) { return hasTrait ? i + start : -1; }).filter(function (i) { return i !== -1; }), this.sortedIndexes.filter(function (i) { return i >= end; }).map(function (i) { return i + diff; }));
this.renderer.splice(start, deleteCount, elements.length);
this._set(indexes, indexes);
};
Trait.prototype.renderIndex = function (index, container) {
DOM.toggleClass(container, this._trait, this.contains(index));
};
Trait.prototype.unrender = function (container) {
DOM.removeClass(container, this._trait);
};
/**
* Sets the indexes which should have this trait.
*
* @param indexes Indexes which should have this trait.
* @return The old indexes which had this trait.
*/
Trait.prototype.set = function (indexes, browserEvent) {
return this._set(indexes, __spreadArrays(indexes).sort(numericSort), browserEvent);
};
Trait.prototype._set = function (indexes, sortedIndexes, browserEvent) {
var result = this.indexes;
var sortedResult = this.sortedIndexes;
this.indexes = indexes;
this.sortedIndexes = sortedIndexes;
var toRender = disjunction(sortedResult, indexes);
this.renderer.renderIndexes(toRender);
this._onChange.fire({ indexes: indexes, browserEvent: browserEvent });
return result;
};
Trait.prototype.get = function () {
return this.indexes;
};
Trait.prototype.contains = function (index) {
return arrays_1.binarySearch(this.sortedIndexes, index, numericSort) >= 0;
};
Trait.prototype.dispose = function () {
lifecycle_1.dispose(this._onChange);
};
__decorate([
decorators_1.memoize
], Trait.prototype, "renderer", null);
return Trait;
}());
var FocusTrait = /** @class */ (function (_super) {
__extends(FocusTrait, _super);
function FocusTrait() {
return _super.call(this, 'focused') || this;
}
FocusTrait.prototype.renderIndex = function (index, container) {
_super.prototype.renderIndex.call(this, index, container);
if (this.contains(index)) {
container.setAttribute('aria-selected', 'true');
}
else {
container.removeAttribute('aria-selected');
}
};
return FocusTrait;
}(Trait));
/**
* The TraitSpliceable is used as a util class to be able
* to preserve traits across splice calls, given an identity
* provider.
*/
var TraitSpliceable = /** @class */ (function () {
function TraitSpliceable(trait, view, identityProvider) {
this.trait = trait;
this.view = view;
this.identityProvider = identityProvider;
}
TraitSpliceable.prototype.splice = function (start, deleteCount, elements) {
var _this = this;
if (!this.identityProvider) {
return this.trait.splice(start, deleteCount, elements.map(function () { return false; }));
}
var pastElementsWithTrait = this.trait.get().map(function (i) { return _this.identityProvider.getId(_this.view.element(i)).toString(); });
var elementsWithTrait = elements.map(function (e) { return pastElementsWithTrait.indexOf(_this.identityProvider.getId(e).toString()) > -1; });
this.trait.splice(start, deleteCount, elementsWithTrait);
};
return TraitSpliceable;
}());
function isInputElement(e) {
return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA';
}
var KeyboardController = /** @class */ (function () {
function KeyboardController(list, view, options) {
this.list = list;
this.view = view;
this.disposables = new lifecycle_1.DisposableStore();
var multipleSelectionSupport = options.multipleSelectionSupport !== false;
this.openController = options.openController || DefaultOpenController;
var onKeyDown = event_1.Event.chain(event_2.domEvent(view.domNode, 'keydown'))
.filter(function (e) { return !isInputElement(e.target); })
.map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); });
onKeyDown.filter(function (e) { return e.keyCode === 3 /* Enter */; }).on(this.onEnter, this, this.disposables);
onKeyDown.filter(function (e) { return e.keyCode === 16 /* UpArrow */; }).on(this.onUpArrow, this, this.disposables);
onKeyDown.filter(function (e) { return e.keyCode === 18 /* DownArrow */; }).on(this.onDownArrow, this, this.disposables);
onKeyDown.filter(function (e) { return e.keyCode === 11 /* PageUp */; }).on(this.onPageUpArrow, this, this.disposables);
onKeyDown.filter(function (e) { return e.keyCode === 12 /* PageDown */; }).on(this.onPageDownArrow, this, this.disposables);
onKeyDown.filter(function (e) { return e.keyCode === 9 /* Escape */; }).on(this.onEscape, this, this.disposables);
if (multipleSelectionSupport) {
onKeyDown.filter(function (e) { return (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31 /* KEY_A */; }).on(this.onCtrlA, this, this.disposables);
}
}
KeyboardController.prototype.onEnter = function (e) {
e.preventDefault();
e.stopPropagation();
this.list.setSelection(this.list.getFocus(), e.browserEvent);
if (this.openController.shouldOpen(e.browserEvent)) {
this.list.open(this.list.getFocus(), e.browserEvent);
}
};
KeyboardController.prototype.onUpArrow = function (e) {
e.preventDefault();
e.stopPropagation();
this.list.focusPrevious(1, false, e.browserEvent);
this.list.reveal(this.list.getFocus()[0]);
this.view.domNode.focus();
};
KeyboardController.prototype.onDownArrow = function (e) {
e.preventDefault();
e.stopPropagation();
this.list.focusNext(1, false, e.browserEvent);
this.list.reveal(this.list.getFocus()[0]);
this.view.domNode.focus();
};
KeyboardController.prototype.onPageUpArrow = function (e) {
e.preventDefault();
e.stopPropagation();
this.list.focusPreviousPage(e.browserEvent);
this.list.reveal(this.list.getFocus()[0]);
this.view.domNode.focus();
};
KeyboardController.prototype.onPageDownArrow = function (e) {
e.preventDefault();
e.stopPropagation();
this.list.focusNextPage(e.browserEvent);
this.list.reveal(this.list.getFocus()[0]);
this.view.domNode.focus();
};
KeyboardController.prototype.onCtrlA = function (e) {
e.preventDefault();
e.stopPropagation();
this.list.setSelection(arrays_1.range(this.list.length), e.browserEvent);
this.view.domNode.focus();
};
KeyboardController.prototype.onEscape = function (e) {
e.preventDefault();
e.stopPropagation();
this.list.setSelection([], e.browserEvent);
this.view.domNode.focus();
};
KeyboardController.prototype.dispose = function () {
this.disposables.dispose();
};
return KeyboardController;
}());
var TypeLabelControllerState;
(function (TypeLabelControllerState) {
TypeLabelControllerState[TypeLabelControllerState["Idle"] = 0] = "Idle";
TypeLabelControllerState[TypeLabelControllerState["Typing"] = 1] = "Typing";
})(TypeLabelControllerState || (TypeLabelControllerState = {}));
exports.DefaultKeyboardNavigationDelegate = new /** @class */ (function () {
function class_1() {
}
class_1.prototype.mightProducePrintableCharacter = function (event) {
if (event.ctrlKey || event.metaKey || event.altKey) {
return false;
}
return (event.keyCode >= 31 /* KEY_A */ && event.keyCode <= 56 /* KEY_Z */)
|| (event.keyCode >= 21 /* KEY_0 */ && event.keyCode <= 30 /* KEY_9 */)
|| (event.keyCode >= 93 /* NUMPAD_0 */ && event.keyCode <= 102 /* NUMPAD_9 */)
|| (event.keyCode >= 80 /* US_SEMICOLON */ && event.keyCode <= 90 /* US_QUOTE */);
};
return class_1;
}());
var TypeLabelController = /** @class */ (function () {
function TypeLabelController(list, view, keyboardNavigationLabelProvider, delegate) {
this.list = list;
this.view = view;
this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
this.delegate = delegate;
this.enabled = false;
this.state = TypeLabelControllerState.Idle;
this.automaticKeyboardNavigation = true;
this.triggered = false;
this.enabledDisposables = new lifecycle_1.DisposableStore();
this.disposables = new lifecycle_1.DisposableStore();
this.updateOptions(list.options);
}
TypeLabelController.prototype.updateOptions = function (options) {
var enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation;
if (enableKeyboardNavigation) {
this.enable();
}
else {
this.disable();
}
if (typeof options.automaticKeyboardNavigation !== 'undefined') {
this.automaticKeyboardNavigation = options.automaticKeyboardNavigation;
}
};
TypeLabelController.prototype.enable = function () {
var _this = this;
if (this.enabled) {
return;
}
var onChar = event_1.Event.chain(event_2.domEvent(this.view.domNode, 'keydown'))
.filter(function (e) { return !isInputElement(e.target); })
.filter(function () { return _this.automaticKeyboardNavigation || _this.triggered; })
.map(function (event) { return new keyboardEvent_1.StandardKeyboardEvent(event); })
.filter(function (e) { return _this.delegate.mightProducePrintableCharacter(e); })
.forEach(function (e) { e.stopPropagation(); e.preventDefault(); })
.map(function (event) { return event.browserEvent.key; })
.event;
var onClear = event_1.Event.debounce(onChar, function () { return null; }, 800);
var onInput = event_1.Event.reduce(event_1.Event.any(onChar, onClear), function (r, i) { return i === null ? null : ((r || '') + i); });
onInput(this.onInput, this, this.enabledDisposables);
this.enabled = true;
this.triggered = false;
};
TypeLabelController.prototype.disable = function () {
if (!this.enabled) {
return;
}
this.enabledDisposables.clear();
this.enabled = false;
this.triggered = false;
};
TypeLabelController.prototype.onInput = function (word) {
if (!word) {
this.state = TypeLabelControllerState.Idle;
this.triggered = false;
return;
}
var focus = this.list.getFocus();
var start = focus.length > 0 ? focus[0] : 0;
var delta = this.state === TypeLabelControllerState.Idle ? 1 : 0;
this.state = TypeLabelControllerState.Typing;
for (var i = 0; i < this.list.length; i++) {
var index = (start + i + delta) % this.list.length;
var label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index));
var labelStr = label && label.toString();
if (typeof labelStr === 'undefined' || filters_1.matchesPrefix(word, labelStr)) {
this.list.setFocus([index]);
this.list.reveal(index);
return;
}
}
};
TypeLabelController.prototype.dispose = function () {
this.disable();
this.enabledDisposables.dispose();
this.disposables.dispose();
};
return TypeLabelController;
}());
var DOMFocusController = /** @class */ (function () {
function DOMFocusController(list, view) {
this.list = list;
this.view = view;
this.disposables = new lifecycle_1.DisposableStore();
var onKeyDown = event_1.Event.chain(event_2.domEvent(view.domNode, 'keydown'))
.filter(function (e) { return !isInputElement(e.target); })
.map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); });
onKeyDown.filter(function (e) { return e.keyCode === 2 /* Tab */ && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey; })
.on(this.onTab, this, this.disposables);
}
DOMFocusController.prototype.onTab = function (e) {
if (e.target !== this.view.domNode) {
return;
}
var focus = this.list.getFocus();
if (focus.length === 0) {
return;
}
var focusedDomElement = this.view.domElement(focus[0]);
if (!focusedDomElement) {
return;
}
var tabIndexElement = focusedDomElement.querySelector('[tabIndex]');
if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) {
return;
}
var style = window.getComputedStyle(tabIndexElement);
if (style.visibility === 'hidden' || style.display === 'none') {
return;
}
e.preventDefault();
e.stopPropagation();
tabIndexElement.focus();
};
DOMFocusController.prototype.dispose = function () {
this.disposables.dispose();
};
return DOMFocusController;
}());
function isSelectionSingleChangeEvent(event) {
return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
}
exports.isSelectionSingleChangeEvent = isSelectionSingleChangeEvent;
function isSelectionRangeChangeEvent(event) {
return event.browserEvent.shiftKey;
}
exports.isSelectionRangeChangeEvent = isSelectionRangeChangeEvent;
function isMouseRightClick(event) {
return event instanceof MouseEvent && event.button === 2;
}
var DefaultMultipleSelectionController = {
isSelectionSingleChangeEvent: isSelectionSingleChangeEvent,
isSelectionRangeChangeEvent: isSelectionRangeChangeEvent
};
var DefaultOpenController = {
shouldOpen: function (event) {
if (event instanceof MouseEvent) {
return !isMouseRightClick(event);
}
return true;
}
};
var MouseController = /** @class */ (function () {
function MouseController(list) {
this.list = list;
this.disposables = new lifecycle_1.DisposableStore();
this.multipleSelectionSupport = !(list.options.multipleSelectionSupport === false);
if (this.multipleSelectionSupport) {
this.multipleSelectionController = list.options.multipleSelectionController || DefaultMultipleSelectionController;
}
this.openController = list.options.openController || DefaultOpenController;
this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport;
if (this.mouseSupport) {
list.onMouseDown(this.onMouseDown, this, this.disposables);
list.onContextMenu(this.onContextMenu, this, this.disposables);
list.onMouseDblClick(this.onDoubleClick, this, this.disposables);
list.onTouchStart(this.onMouseDown, this, this.disposables);
this.disposables.add(touch_1.Gesture.addTarget(list.getHTMLElement()));
}
list.onMouseClick(this.onPointer, this, this.disposables);
list.onMouseMiddleClick(this.onPointer, this, this.disposables);
list.onTap(this.onPointer, this, this.disposables);
}
MouseController.prototype.isSelectionSingleChangeEvent = function (event) {
if (this.multipleSelectionController) {
return this.multipleSelectionController.isSelectionSingleChangeEvent(event);
}
return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
};
MouseController.prototype.isSelectionRangeChangeEvent = function (event) {
if (this.multipleSelectionController) {
return this.multipleSelectionController.isSelectionRangeChangeEvent(event);
}
return event.browserEvent.shiftKey;
};
MouseController.prototype.isSelectionChangeEvent = function (event) {
return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event);
};
MouseController.prototype.onMouseDown = function (e) {
if (document.activeElement !== e.browserEvent.target) {
this.list.domFocus();
}
};
MouseController.prototype.onContextMenu = function (e) {
var focus = typeof e.index === 'undefined' ? [] : [e.index];
this.list.setFocus(focus, e.browserEvent);
};
MouseController.prototype.onPointer = function (e) {
if (!this.mouseSupport) {
return;
}
if (isInputElement(e.browserEvent.target)) {
return;
}
var reference = this.list.getFocus()[0];
var selection = this.list.getSelection();
reference = reference === undefined ? selection[0] : reference;
var focus = e.index;
if (typeof focus === 'undefined') {
this.list.setFocus([], e.browserEvent);
this.list.setSelection([], e.browserEvent);
return;
}
if (this.multipleSelectionSupport && this.isSelectionRangeChangeEvent(e)) {
return this.changeSelection(e, reference);
}
if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) {
return this.changeSelection(e, reference);
}
this.list.setFocus([focus], e.browserEvent);
if (!isMouseRightClick(e.browserEvent)) {
this.list.setSelection([focus], e.browserEvent);
if (this.openController.shouldOpen(e.browserEvent)) {
this.list.open([focus], e.browserEvent);
}
}
};
MouseController.prototype.onDoubleClick = function (e) {
if (isInputElement(e.browserEvent.target)) {
return;
}
if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) {
return;
}
var focus = this.list.getFocus();
this.list.setSelection(focus, e.browserEvent);
this.list.pin(focus);
};
MouseController.prototype.changeSelection = function (e, reference) {
var focus = e.index;
if (this.isSelectionRangeChangeEvent(e) && reference !== undefined) {
var min = Math.min(reference, focus);
var max = Math.max(reference, focus);
var rangeSelection = arrays_1.range(min, max + 1);
var selection = this.list.getSelection();
var contiguousRange = getContiguousRangeContaining(disjunction(selection, [reference]), reference);
if (contiguousRange.length === 0) {
return;
}
var newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange));
this.list.setSelection(newSelection, e.browserEvent);
}
else if (this.isSelectionSingleChangeEvent(e)) {
var selection = this.list.getSelection();
var newSelection = selection.filter(function (i) { return i !== focus; });
this.list.setFocus([focus]);
if (selection.length === newSelection.length) {
this.list.setSelection(__spreadArrays(newSelection, [focus]), e.browserEvent);
}
else {
this.list.setSelection(newSelection, e.browserEvent);
}
}
};
MouseController.prototype.dispose = function () {
this.disposables.dispose();
};
return MouseController;
}());
exports.MouseController = MouseController;
var DefaultStyleController = /** @class */ (function () {
function DefaultStyleController(styleElement, selectorSuffix) {
this.styleElement = styleElement;
this.selectorSuffix = selectorSuffix;
}
DefaultStyleController.prototype.style = function (styles) {
var suffix = this.selectorSuffix && "." + this.selectorSuffix;
var content = [];
if (styles.listBackground) {
if (styles.listBackground.isOpaque()) {
content.push(".monaco-list" + suffix + " .monaco-list-rows { background: " + styles.listBackground + "; }");
}
else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS
console.warn("List with id '" + this.selectorSuffix + "' was styled with a non-opaque background color. This will break sub-pixel antialiasing.");
}
}
if (styles.listFocusBackground) {
content.push(".monaco-list" + suffix + ":focus .monaco-list-row.focused { background-color: " + styles.listFocusBackground + "; }");
content.push(".monaco-list" + suffix + ":focus .monaco-list-row.focused:hover { background-color: " + styles.listFocusBackground + "; }"); // overwrite :hover style in this case!
}
if (styles.listFocusForeground) {
content.push(".monaco-list" + suffix + ":focus .monaco-list-row.focused { color: " + styles.listFocusForeground + "; }");
}
if (styles.listActiveSelectionBackground) {
content.push(".monaco-list" + suffix + ":focus .monaco-list-row.selected { background-color: " + styles.listActiveSelectionBackground + "; }");
content.push(".monaco-list" + suffix + ":focus .monaco-list-row.selected:hover { background-color: " + styles.listActiveSelectionBackground + "; }"); // overwrite :hover style in this case!
}
if (styles.listActiveSelectionForeground) {
content.push(".monaco-list" + suffix + ":focus .monaco-list-row.selected { color: " + styles.listActiveSelectionForeground + "; }");
}
if (styles.listFocusAndSelectionBackground) {
content.push("\n\t\t\t\t.monaco-drag-image,\n\t\t\t\t.monaco-list" + suffix + ":focus .monaco-list-row.selected.focused { background-color: " + styles.listFocusAndSelectionBackground + "; }\n\t\t\t");
}
if (styles.listFocusAndSelectionForeground) {
content.push("\n\t\t\t\t.monaco-drag-image,\n\t\t\t\t.monaco-list" + suffix + ":focus .monaco-list-row.selected.focused { color: " + styles.listFocusAndSelectionForeground + "; }\n\t\t\t");
}
if (styles.listInactiveFocusBackground) {
content.push(".monaco-list" + suffix + " .monaco-list-row.focused { background-color: " + styles.listInactiveFocusBackground + "; }");
content.push(".monaco-list" + suffix + " .monaco-list-row.focused:hover { background-color: " + styles.listInactiveFocusBackground + "; }"); // overwrite :hover style in this case!
}
if (styles.listInactiveSelectionBackground) {
content.push(".monaco-list" + suffix + " .monaco-list-row.selected { background-color: " + styles.listInactiveSelectionBackground + "; }");
content.push(".monaco-list" + suffix + " .monaco-list-row.selected:hover { background-color: " + styles.listInactiveSelectionBackground + "; }"); // overwrite :hover style in this case!
}
if (styles.listInactiveSelectionForeground) {
content.push(".monaco-list" + suffix + " .monaco-list-row.selected { color: " + styles.listInactiveSelectionForeground + "; }");
}
if (styles.listHoverBackground) {
content.push(".monaco-list" + suffix + ":not(.drop-target) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: " + styles.listHoverBackground + "; }");
}
if (styles.listHoverForeground) {
content.push(".monaco-list" + suffix + " .monaco-list-row:hover:not(.selected):not(.focused) { color: " + styles.listHoverForeground + "; }");
}
if (styles.listSelectionOutline) {
content.push(".monaco-list" + suffix + " .monaco-list-row.selected { outline: 1px dotted " + styles.listSelectionOutline + "; outline-offset: -1px; }");
}
if (styles.listFocusOutline) {
content.push("\n\t\t\t\t.monaco-drag-image,\n\t\t\t\t.monaco-list" + suffix + ":focus .monaco-list-row.focused { outline: 1px solid " + styles.listFocusOutline + "; outline-offset: -1px; }\n\t\t\t");
}
if (styles.listInactiveFocusOutline) {
content.push(".monaco-list" + suffix + " .monaco-list-row.focused { outline: 1px dotted " + styles.listInactiveFocusOutline + "; outline-offset: -1px; }");
}
if (styles.listHoverOutline) {
content.push(".monaco-list" + suffix + " .monaco-list-row:hover { outline: 1px dashed " + styles.listHoverOutline + "; outline-offset: -1px; }");
}
if (styles.listDropBackground) {
content.push("\n\t\t\t\t.monaco-list" + suffix + ".drop-target,\n\t\t\t\t.monaco-list" + suffix + " .monaco-list-rows.drop-target,\n\t\t\t\t.monaco-list" + suffix + " .monaco-list-row.drop-target { background-color: " + styles.listDropBackground + " !important; color: inherit !important; }\n\t\t\t");
}
if (styles.listFilterWidgetBackground) {
content.push(".monaco-list-type-filter { background-color: " + styles.listFilterWidgetBackground + " }");
}
if (styles.listFilterWidgetOutline) {
content.push(".monaco-list-type-filter { border: 1px solid " + styles.listFilterWidgetOutline + "; }");
}
if (styles.listFilterWidgetNoMatchesOutline) {
content.push(".monaco-list-type-filter.no-matches { border: 1px solid " + styles.listFilterWidgetNoMatchesOutline + "; }");
}
if (styles.listMatchesShadow) {
content.push(".monaco-list-type-filter { box-shadow: 1px 1px 1px " + styles.listMatchesShadow + "; }");
}
var newStyles = content.join('\n');
if (newStyles !== this.styleElement.innerHTML) {
this.styleElement.innerHTML = newStyles;
}
};
return DefaultStyleController;
}());
exports.DefaultStyleController = DefaultStyleController;
var defaultStyles = {
listFocusBackground: color_1.Color.fromHex('#7FB0D0'),
listActiveSelectionBackground: color_1.Color.fromHex('#0E639C'),
listActiveSelectionForeground: color_1.Color.fromHex('#FFFFFF'),
listFocusAndSelectionBackground: color_1.Color.fromHex('#094771'),
listFocusAndSelectionForeground: color_1.Color.fromHex('#FFFFFF'),
listInactiveSelectionBackground: color_1.Color.fromHex('#3F3F46'),
listHoverBackground: color_1.Color.fromHex('#2A2D2E'),
listDropBackground: color_1.Color.fromHex('#383B3D'),
treeIndentGuidesStroke: color_1.Color.fromHex('#a9a9a9')
};
var DefaultOptions = {
keyboardSupport: true,
mouseSupport: true,
multipleSelectionSupport: true,
dnd: {
getDragURI: function () { return null; },
onDragStart: function () { },
onDragOver: function () { return false; },
drop: function () { }
},
ariaRootRole: list_1.ListAriaRootRole.TREE
};
// TODO@Joao: move these utils into a SortedArray class
function getContiguousRangeContaining(range, value) {
var index = range.indexOf(value);
if (index === -1) {
return [];
}
var result = [];
var i = index - 1;
while (i >= 0 && range[i] === value - (index - i)) {
result.push(range[i--]);
}
result.reverse();
i = index;
while (i < range.length && range[i] === value + (i - index)) {
result.push(range[i++]);
}
return result;
}
/**
* Given two sorted collections of numbers, returns the intersection
* between them (OR).
*/
function disjunction(one, other) {
var result = [];
var i = 0, j = 0;
while (i < one.length || j < other.length) {
if (i >= one.length) {
result.push(other[j++]);
}
else if (j >= other.length) {
result.push(one[i++]);
}
else if (one[i] === other[j]) {
result.push(one[i]);
i++;
j++;
continue;
}
else if (one[i] < other[j]) {
result.push(one[i++]);
}
else {
result.push(other[j++]);
}
}
return result;
}
/**
* Given two sorted collections of numbers, returns the relative
* complement between them (XOR).
*/
function relativeComplement(one, other) {
var result = [];
var i = 0, j = 0;
while (i < one.length || j < other.length) {
if (i >= one.length) {
result.push(other[j++]);
}
else if (j >= other.length) {
result.push(one[i++]);
}
else if (one[i] === other[j]) {
i++;
j++;
continue;
}
else if (one[i] < other[j]) {
result.push(one[i++]);
}
else {
j++;
}
}
return result;
}
var numericSort = function (a, b) { return a - b; };
var PipelineRenderer = /** @class */ (function () {
function PipelineRenderer(_templateId, renderers) {
this._templateId = _templateId;
this.renderers = renderers;
}
Object.defineProperty(PipelineRenderer.prototype, "templateId", {
get: function () {
return this._templateId;
},
enumerable: true,
configurable: true
});
PipelineRenderer.prototype.renderTemplate = function (container) {
return this.renderers.map(function (r) { return r.renderTemplate(container); });
};
PipelineRenderer.prototype.renderElement = function (element, index, templateData, height) {
var i = 0;
for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) {
var renderer = _a[_i];
renderer.renderElement(element, index, templateData[i++], height);
}
};
PipelineRenderer.prototype.disposeElement = function (element, index, templateData, height) {
var i = 0;
for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) {
var renderer = _a[_i];
if (renderer.disposeElement) {
renderer.disposeElement(element, index, templateData[i], height);
}
i += 1;
}
};
PipelineRenderer.prototype.disposeTemplate = function (templateData) {
var i = 0;
for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) {
var renderer = _a[_i];
renderer.disposeTemplate(templateData[i++]);
}
};
return PipelineRenderer;
}());
var AccessibiltyRenderer = /** @class */ (function () {
function AccessibiltyRenderer(accessibilityProvider) {
this.accessibilityProvider = accessibilityProvider;
this.templateId = 'a18n';
}
AccessibiltyRenderer.prototype.renderTemplate = function (container) {
return container;
};
AccessibiltyRenderer.prototype.renderElement = function (element, index, container) {
var ariaLabel = this.accessibilityProvider.getAriaLabel(element);
if (ariaLabel) {
container.setAttribute('aria-label', ariaLabel);
}
else {
container.removeAttribute('aria-label');
}
var ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);
if (typeof ariaLevel === 'number') {
container.setAttribute('aria-level', "" + ariaLevel);
}
else {
container.removeAttribute('aria-level');
}
};
AccessibiltyRenderer.prototype.disposeTemplate = function (templateData) {
// noop
};
return AccessibiltyRenderer;
}());
var ListViewDragAndDrop = /** @class */ (function () {
function ListViewDragAndDrop(list, dnd) {
this.list = list;
this.dnd = dnd;
}
ListViewDragAndDrop.prototype.getDragElements = function (element) {
var selection = this.list.getSelectedElements();
var elements = selection.indexOf(element) > -1 ? selection : [element];
return elements;
};
ListViewDragAndDrop.prototype.getDragURI = function (element) {
return this.dnd.getDragURI(element);
};
ListViewDragAndDrop.prototype.getDragLabel = function (elements, originalEvent) {
if (this.dnd.getDragLabel) {
return this.dnd.getDragLabel(elements, originalEvent);
}
return undefined;
};
ListViewDragAndDrop.prototype.onDragStart = function (data, originalEvent) {
if (this.dnd.onDragStart) {
this.dnd.onDragStart(data, originalEvent);
}
};
ListViewDragAndDrop.prototype.onDragOver = function (data, targetElement, targetIndex, originalEvent) {
return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent);
};
ListViewDragAndDrop.prototype.onDragEnd = function (originalEvent) {
if (this.dnd.onDragEnd) {
this.dnd.onDragEnd(originalEvent);
}
};
ListViewDragAndDrop.prototype.drop = function (data, targetElement, targetIndex, originalEvent) {
this.dnd.drop(data, targetElement, targetIndex, originalEvent);
};
return ListViewDragAndDrop;
}());
var List = /** @class */ (function () {
function List(user, container, virtualDelegate, renderers, _options) {
if (_options === void 0) { _options = DefaultOptions; }
this.user = user;
this._options = _options;
this.eventBufferer = new event_1.EventBufferer();
this.disposables = new lifecycle_1.DisposableStore();
this._onDidOpen = new event_1.Emitter();
this.onDidOpen = this._onDidOpen.event;
this._onDidPin = new event_1.Emitter();
this.didJustPressContextMenuKey = false;
this._onDidDispose = new event_1.Emitter();
this.onDidDispose = this._onDidDispose.event;
this.focus = new FocusTrait();
this.selection = new Trait('selected');
objects_1.mixin(_options, defaultStyles, false);
var baseRenderers = [this.focus.renderer, this.selection.renderer];
this.accessibilityProvider = _options.accessibilityProvider;
if (this.accessibilityProvider) {
baseRenderers.push(new AccessibiltyRenderer(this.accessibilityProvider));
if (this.accessibilityProvider.onDidChangeActiveDescendant) {
this.accessibilityProvider.onDidChangeActiveDescendant(this.onDidChangeActiveDescendant, this, this.disposables);
}
}
renderers = renderers.map(function (r) { return new PipelineRenderer(r.templateId, __spreadArrays(baseRenderers, [r])); });
var viewOptions = __assign(__assign({}, _options), { dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) });
this.view = new listView_1.ListView(container, virtualDelegate, renderers, viewOptions);
if (typeof _options.ariaRole !== 'string') {
this.view.domNode.setAttribute('role', list_1.ListAriaRootRole.TREE);
}
else {
this.view.domNode.setAttribute('role', _options.ariaRole);
}
if (_options.styleController) {
this.styleController = _options.styleController(this.view.domId);
}
else {
var styleElement = DOM.createStyleSheet(this.view.domNode);
this.styleController = new DefaultStyleController(styleElement, this.view.domId);
}
this.spliceable = new splice_1.CombinedSpliceable([
new TraitSpliceable(this.focus, this.view, _options.identityProvider),
new TraitSpliceable(this.selection, this.view, _options.identityProvider),
this.view
]);
this.disposables.add(this.focus);
this.disposables.add(this.selection);
this.disposables.add(this.view);
this.disposables.add(this._onDidDispose);
this.onDidFocus = event_1.Event.map(event_2.domEvent(this.view.domNode, 'focus', true), function () { return null; });
this.onDidBlur = event_1.Event.map(event_2.domEvent(this.view.domNode, 'blur', true), function () { return null; });
this.disposables.add(new DOMFocusController(this, this.view));
if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) {
var controller = new KeyboardController(this, this.view, _options);
this.disposables.add(controller);
}
if (_options.keyboardNavigationLabelProvider) {
var delegate = _options.keyboardNavigationDelegate || exports.DefaultKeyboardNavigationDelegate;
this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate);
this.disposables.add(this.typeLabelController);
}
this.disposables.add(this.createMouseController(_options));
this.onFocusChange(this._onFocusChange, this, this.disposables);
this.onSelectionChange(this._onSelectionChange, this, this.disposables);
if (_options.ariaLabel) {
this.view.domNode.setAttribute('aria-label', nls_1.localize(0, null, _options.ariaLabel));
}
}
Object.defineProperty(List.prototype, "onFocusChange", {
get: function () {
var _this = this;
return event_1.Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), function (e) { return _this.toListEvent(e); });
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "onSelectionChange", {
get: function () {
var _this = this;
return event_1.Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), function (e) { return _this.toListEvent(e); });
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "domId", {
get: function () { return this.view.domId; },
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "onMouseClick", {
get: function () { return this.view.onMouseClick; },
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "onMouseDblClick", {
get: function () { return this.view.onMouseDblClick; },
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "onMouseMiddleClick", {
get: function () { return this.view.onMouseMiddleClick; },
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "onMouseDown", {
get: function () { return this.view.onMouseDown; },
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "onTouchStart", {
get: function () { return this.view.onTouchStart; },
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "onTap", {
get: function () { return this.view.onTap; },
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "onContextMenu", {
get: function () {
var _this = this;
var fromKeydown = event_1.Event.chain(event_2.domEvent(this.view.domNode, 'keydown'))
.map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); })
.filter(function (e) { return _this.didJustPressContextMenuKey = e.keyCode === 58 /* ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* F10 */); })
.filter(function (e) { e.preventDefault(); e.stopPropagation(); return false; })
.event;
var fromKeyup = event_1.Event.chain(event_2.domEvent(this.view.domNode, 'keyup'))
.filter(function () {
var didJustPressContextMenuKey = _this.didJustPressContextMenuKey;
_this.didJustPressContextMenuKey = false;
return didJustPressContextMenuKey;
})
.filter(function () { return _this.getFocus().length > 0 && !!_this.view.domElement(_this.getFocus()[0]); })
.map(function (browserEvent) {
var index = _this.getFocus()[0];
var element = _this.view.element(index);
var anchor = _this.view.domElement(index);
return { index: index, element: element, anchor: anchor, browserEvent: browserEvent };
})
.event;
var fromMouse = event_1.Event.chain(this.view.onContextMenu)
.filter(function () { return !_this.didJustPressContextMenuKey; })
.map(function (_a) {
var element = _a.element, index = _a.index, browserEvent = _a.browserEvent;
return ({ element: element, index: index, anchor: { x: browserEvent.clientX + 1, y: browserEvent.clientY }, browserEvent: browserEvent });
})
.event;
return event_1.Event.any(fromKeydown, fromKeyup, fromMouse);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "onKeyDown", {
get: function () { return event_2.domEvent(this.view.domNode, 'keydown'); },
enumerable: true,
configurable: true
});
List.prototype.createMouseController = function (options) {
return new MouseController(this);
};
List.prototype.updateOptions = function (optionsUpdate) {
if (optionsUpdate === void 0) { optionsUpdate = {}; }
this._options = __assign(__assign({}, this._options), optionsUpdate);
if (this.typeLabelController) {
this.typeLabelController.updateOptions(this._options);
}
};
Object.defineProperty(List.prototype, "options", {
get: function () {
return this._options;
},
enumerable: true,
configurable: true
});
List.prototype.splice = function (start, deleteCount, elements) {
var _this = this;
if (elements === void 0) { elements = []; }
if (start < 0 || start > this.view.length) {
throw new list_1.ListError(this.user, "Invalid start index: " + start);
}
if (deleteCount < 0) {
throw new list_1.ListError(this.user, "Invalid delete count: " + deleteCount);
}
if (deleteCount === 0 && elements.length === 0) {
return;
}
this.eventBufferer.bufferEvents(function () { return _this.spliceable.splice(start, deleteCount, elements); });
};
List.prototype.rerender = function () {
this.view.rerender();
};
List.prototype.element = function (index) {
return this.view.element(index);
};
Object.defineProperty(List.prototype, "length", {
get: function () {
return this.view.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "contentHeight", {
get: function () {
return this.view.contentHeight;
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "scrollTop", {
get: function () {
return this.view.getScrollTop();
},
set: function (scrollTop) {
this.view.setScrollTop(scrollTop);
},
enumerable: true,
configurable: true
});
List.prototype.domFocus = function () {
this.view.domNode.focus();
};
List.prototype.layout = function (height, width) {
this.view.layout(height, width);
};
List.prototype.setSelection = function (indexes, browserEvent) {
for (var _i = 0, indexes_1 = indexes; _i < indexes_1.length; _i++) {
var index = indexes_1[_i];
if (index < 0 || index >= this.length) {
throw new list_1.ListError(this.user, "Invalid index " + index);
}
}
this.selection.set(indexes, browserEvent);
};
List.prototype.getSelection = function () {
return this.selection.get();
};
List.prototype.getSelectedElements = function () {
var _this = this;
return this.getSelection().map(function (i) { return _this.view.element(i); });
};
List.prototype.setFocus = function (indexes, browserEvent) {
for (var _i = 0, indexes_2 = indexes; _i < indexes_2.length; _i++) {
var index = indexes_2[_i];
if (index < 0 || index >= this.length) {
throw new list_1.ListError(this.user, "Invalid index " + index);
}
}
this.focus.set(indexes, browserEvent);
};
List.prototype.focusNext = function (n, loop, browserEvent, filter) {
if (n === void 0) { n = 1; }
if (loop === void 0) { loop = false; }
if (this.length === 0) {
return;
}
var focus = this.focus.get();
var index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter);
if (index > -1) {
this.setFocus([index], browserEvent);
}
};
List.prototype.focusPrevious = function (n, loop, browserEvent, filter) {
if (n === void 0) { n = 1; }
if (loop === void 0) { loop = false; }
if (this.length === 0) {
return;
}
var focus = this.focus.get();
var index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter);
if (index > -1) {
this.setFocus([index], browserEvent);
}
};
List.prototype.focusNextPage = function (browserEvent, filter) {
var _this = this;
var lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight);
lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
var lastPageElement = this.view.element(lastPageIndex);
var currentlyFocusedElement = this.getFocusedElements()[0];
if (currentlyFocusedElement !== lastPageElement) {
var lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter);
if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) {
this.setFocus([lastGoodPageIndex], browserEvent);
}
else {
this.setFocus([lastPageIndex], browserEvent);
}
}
else {
var previousScrollTop = this.view.getScrollTop();
this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex));
if (this.view.getScrollTop() !== previousScrollTop) {
// Let the scroll event listener run
setTimeout(function () { return _this.focusNextPage(browserEvent, filter); }, 0);
}
}
};
List.prototype.focusPreviousPage = function (browserEvent, filter) {
var _this = this;
var firstPageIndex;
var scrollTop = this.view.getScrollTop();
if (scrollTop === 0) {
firstPageIndex = this.view.indexAt(scrollTop);
}
else {
firstPageIndex = this.view.indexAfter(scrollTop - 1);
}
var firstPageElement = this.view.element(firstPageIndex);
var currentlyFocusedElement = this.getFocusedElements()[0];
if (currentlyFocusedElement !== firstPageElement) {
var firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter);
if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) {
this.setFocus([firstGoodPageIndex], browserEvent);
}
else {
this.setFocus([firstPageIndex], browserEvent);
}
}
else {
var previousScrollTop = scrollTop;
this.view.setScrollTop(scrollTop - this.view.renderHeight);
if (this.view.getScrollTop() !== previousScrollTop) {
// Let the scroll event listener run
setTimeout(function () { return _this.focusPreviousPage(browserEvent, filter); }, 0);
}
}
};
List.prototype.focusLast = function (browserEvent, filter) {
if (this.length === 0) {
return;
}
var index = this.findPreviousIndex(this.length - 1, false, filter);
if (index > -1) {
this.setFocus([index], browserEvent);
}
};
List.prototype.focusFirst = function (browserEvent, filter) {
if (this.length === 0) {
return;
}
var index = this.findNextIndex(0, false, filter);
if (index > -1) {
this.setFocus([index], browserEvent);
}
};
List.prototype.findNextIndex = function (index, loop, filter) {
if (loop === void 0) { loop = false; }
for (var i = 0; i < this.length; i++) {
if (index >= this.length && !loop) {
return -1;
}
index = index % this.length;
if (!filter || filter(this.element(index))) {
return index;
}
index++;
}
return -1;
};
List.prototype.findPreviousIndex = function (index, loop, filter) {
if (loop === void 0) { loop = false; }
for (var i = 0; i < this.length; i++) {
if (index < 0 && !loop) {
return -1;
}
index = (this.length + (index % this.length)) % this.length;
if (!filter || filter(this.element(index))) {
return index;
}
index--;
}
return -1;
};
List.prototype.getFocus = function () {
return this.focus.get();
};
List.prototype.getFocusedElements = function () {
var _this = this;
return this.getFocus().map(function (i) { return _this.view.element(i); });
};
List.prototype.reveal = function (index, relativeTop) {
if (index < 0 || index >= this.length) {
throw new list_1.ListError(this.user, "Invalid index " + index);
}
var scrollTop = this.view.getScrollTop();
var elementTop = this.view.elementTop(index);
var elementHeight = this.view.elementHeight(index);
if (types_1.isNumber(relativeTop)) {
// y = mx + b
var m = elementHeight - this.view.renderHeight;
this.view.setScrollTop(m * numbers_1.clamp(relativeTop, 0, 1) + elementTop);
}
else {
var viewItemBottom = elementTop + elementHeight;
var wrapperBottom = scrollTop + this.view.renderHeight;
if (elementTop < scrollTop && viewItemBottom >= wrapperBottom) {
// The element is already overflowing the viewport, no-op
}
else if (elementTop < scrollTop) {
this.view.setScrollTop(elementTop);
}
else if (viewItemBottom >= wrapperBottom) {
this.view.setScrollTop(viewItemBottom - this.view.renderHeight);
}
}
};
/**
* Returns the relative position of an element rendered in the list.
* Returns `null` if the element isn't *entirely* in the visible viewport.
*/
List.prototype.getRelativeTop = function (index) {
if (index < 0 || index >= this.length) {
throw new list_1.ListError(this.user, "Invalid index " + index);
}
var scrollTop = this.view.getScrollTop();
var elementTop = this.view.elementTop(index);
var elementHeight = this.view.elementHeight(index);
if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) {
return null;
}
// y = mx + b
var m = elementHeight - this.view.renderHeight;
return Math.abs((scrollTop - elementTop) / m);
};
List.prototype.getHTMLElement = function () {
return this.view.domNode;
};
List.prototype.open = function (indexes, browserEvent) {
var _this = this;
for (var _i = 0, indexes_3 = indexes; _i < indexes_3.length; _i++) {
var index = indexes_3[_i];
if (index < 0 || index >= this.length) {
throw new list_1.ListError(this.user, "Invalid index " + index);
}
}
this._onDidOpen.fire({ indexes: indexes, elements: indexes.map(function (i) { return _this.view.element(i); }), browserEvent: browserEvent });
};
List.prototype.pin = function (indexes, browserEvent) {
var _this = this;
for (var _i = 0, indexes_4 = indexes; _i < indexes_4.length; _i++) {
var index = indexes_4[_i];
if (index < 0 || index >= this.length) {
throw new list_1.ListError(this.user, "Invalid index " + index);
}
}
this._onDidPin.fire({ indexes: indexes, elements: indexes.map(function (i) { return _this.view.element(i); }), browserEvent: browserEvent });
};
List.prototype.style = function (styles) {
this.styleController.style(styles);
};
List.prototype.toListEvent = function (_a) {
var _this = this;
var indexes = _a.indexes, browserEvent = _a.browserEvent;
return { indexes: indexes, elements: indexes.map(function (i) { return _this.view.element(i); }), browserEvent: browserEvent };
};
List.prototype._onFocusChange = function () {
var focus = this.focus.get();
DOM.toggleClass(this.view.domNode, 'element-focused', focus.length > 0);
this.onDidChangeActiveDescendant();
};
List.prototype.onDidChangeActiveDescendant = function () {
var _a;
var focus = this.focus.get();
if (focus.length > 0) {
var id = void 0;
if ((_a = this.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getActiveDescendantId) {
id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0]));
}
this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0]));
}
else {
this.view.domNode.removeAttribute('aria-activedescendant');
}
};
List.prototype._onSelectionChange = function () {
var selection = this.selection.get();
DOM.toggleClass(this.view.domNode, 'selection-none', selection.length === 0);
DOM.toggleClass(this.view.domNode, 'selection-single', selection.length === 1);
DOM.toggleClass(this.view.domNode, 'selection-multiple', selection.length > 1);
};
List.prototype.dispose = function () {
this._onDidDispose.fire();
this.disposables.dispose();
this._onDidOpen.dispose();
this._onDidPin.dispose();
this._onDidDispose.dispose();
};
__decorate([
decorators_1.memoize
], List.prototype, "onFocusChange", null);
__decorate([
decorators_1.memoize
], List.prototype, "onSelectionChange", null);
__decorate([
decorators_1.memoize
], List.prototype, "onContextMenu", null);
return List;
}());
exports.List = List;
});
define(__m[404/*vs/nls!vs/base/browser/ui/menu/menu*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/menu/menu", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[205/*vs/base/browser/ui/menu/menu*/], __M([0/*require*/,1/*exports*/,404/*vs/nls!vs/base/browser/ui/menu/menu*/,5/*vs/base/common/strings*/,55/*vs/base/common/actions*/,70/*vs/base/browser/ui/actionbar/actionbar*/,6/*vs/base/browser/dom*/,56/*vs/base/browser/keyboardEvent*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,53/*vs/base/browser/ui/scrollbar/scrollableElement*/,16/*vs/base/common/platform*/,272/*vs/css!vs/base/browser/ui/menu/menu*/]), function (require, exports, nls, strings, actions_1, actionbar_1, dom_1, keyboardEvent_1, async_1, lifecycle_1, scrollableElement_1, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/;
exports.MENU_ESCAPED_MNEMONIC_REGEX = /(&)?(&)([^\s&])/g;
var Direction;
(function (Direction) {
Direction[Direction["Right"] = 0] = "Right";
Direction[Direction["Left"] = 1] = "Left";
})(Direction = exports.Direction || (exports.Direction = {}));
var SubmenuAction = /** @class */ (function (_super) {
__extends(SubmenuAction, _super);
function SubmenuAction(label, entries, cssClass) {
var _this = _super.call(this, !!cssClass ? cssClass : 'submenu', label, '', true) || this;
_this.entries = entries;
return _this;
}
return SubmenuAction;
}(actions_1.Action));
exports.SubmenuAction = SubmenuAction;
var Menu = /** @class */ (function (_super) {
__extends(Menu, _super);
function Menu(container, actions, options) {
if (options === void 0) { options = {}; }
var _this = this;
dom_1.addClass(container, 'monaco-menu-container');
container.setAttribute('role', 'presentation');
var menuElement = document.createElement('div');
dom_1.addClass(menuElement, 'monaco-menu');
menuElement.setAttribute('role', 'presentation');
_this = _super.call(this, menuElement, {
orientation: 2 /* VERTICAL */,
actionViewItemProvider: function (action) { return _this.doGetActionViewItem(action, options, parentData); },
context: options.context,
actionRunner: options.actionRunner,
ariaLabel: options.ariaLabel,
triggerKeys: { keys: __spreadArrays([3 /* Enter */], (platform_1.isMacintosh ? [10 /* Space */] : [])), keyDown: true }
}) || this;
_this.menuElement = menuElement;
_this.actionsList.setAttribute('role', 'menu');
_this.actionsList.tabIndex = 0;
_this.menuDisposables = _this._register(new lifecycle_1.DisposableStore());
dom_1.addDisposableListener(menuElement, dom_1.EventType.KEY_DOWN, function (e) {
var event = new keyboardEvent_1.StandardKeyboardEvent(e);
// Stop tab navigation of menus
if (event.equals(2 /* Tab */)) {
e.preventDefault();
}
});
if (options.enableMnemonics) {
_this.menuDisposables.add(dom_1.addDisposableListener(menuElement, dom_1.EventType.KEY_DOWN, function (e) {
var key = e.key.toLocaleLowerCase();
if (_this.mnemonics.has(key)) {
dom_1.EventHelper.stop(e, true);
var actions_2 = _this.mnemonics.get(key);
if (actions_2.length === 1) {
if (actions_2[0] instanceof SubmenuMenuActionViewItem && actions_2[0].container) {
_this.focusItemByElement(actions_2[0].container);
}
actions_2[0].onClick(e);
}
if (actions_2.length > 1) {
var action = actions_2.shift();
if (action && action.container) {
_this.focusItemByElement(action.container);
actions_2.push(action);
}
_this.mnemonics.set(key, actions_2);
}
}
}));
}
if (platform_1.isLinux) {
_this._register(dom_1.addDisposableListener(menuElement, dom_1.EventType.KEY_DOWN, function (e) {
var event = new keyboardEvent_1.StandardKeyboardEvent(e);
if (event.equals(14 /* Home */) || event.equals(11 /* PageUp */)) {
_this.focusedItem = _this.viewItems.length - 1;
_this.focusNext();
dom_1.EventHelper.stop(e, true);
}
else if (event.equals(13 /* End */) || event.equals(12 /* PageDown */)) {
_this.focusedItem = 0;
_this.focusPrevious();
dom_1.EventHelper.stop(e, true);
}
}));
}
_this._register(dom_1.addDisposableListener(_this.domNode, dom_1.EventType.MOUSE_OUT, function (e) {
var relatedTarget = e.relatedTarget;
if (!dom_1.isAncestor(relatedTarget, _this.domNode)) {
_this.focusedItem = undefined;
_this.updateFocus();
e.stopPropagation();
}
}));
_this._register(dom_1.addDisposableListener(_this.actionsList, dom_1.EventType.MOUSE_OVER, function (e) {
var target = e.target;
if (!target || !dom_1.isAncestor(target, _this.actionsList) || target === _this.actionsList) {
return;
}
while (target.parentElement !== _this.actionsList && target.parentElement !== null) {
target = target.parentElement;
}
if (dom_1.hasClass(target, 'action-item')) {
var lastFocusedItem = _this.focusedItem;
_this.setFocusedItem(target);
if (lastFocusedItem !== _this.focusedItem) {
_this.updateFocus();
}
}
}));
var parentData = {
parent: _this
};
_this.mnemonics = new Map();
// Scroll Logic
_this.scrollableElement = _this._register(new scrollableElement_1.DomScrollableElement(menuElement, {
alwaysConsumeMouseWheel: true,
horizontal: 2 /* Hidden */,
vertical: 3 /* Visible */,
verticalScrollbarSize: 7,
handleMouseWheel: true,
useShadows: true
}));
var scrollElement = _this.scrollableElement.getDomNode();
scrollElement.style.position = '';
_this._register(dom_1.addDisposableListener(scrollElement, dom_1.EventType.MOUSE_UP, function (e) {
// Absorb clicks in menu dead space https://github.com/Microsoft/vscode/issues/63575
// We do this on the scroll element so the scroll bar doesn't dismiss the menu either
e.preventDefault();
}));
menuElement.style.maxHeight = Math.max(10, window.innerHeight - container.getBoundingClientRect().top - 30) + "px";
_this.push(actions, { icon: true, label: true, isMenu: true });
container.appendChild(_this.scrollableElement.getDomNode());
_this.scrollableElement.scanDomNode();
_this.viewItems.filter(function (item) { return !(item instanceof MenuSeparatorActionViewItem); }).forEach(function (item, index, array) {
item.updatePositionInSet(index + 1, array.length);
});
return _this;
}
Menu.prototype.style = function (style) {
var container = this.getContainer();
var fgColor = style.foregroundColor ? "" + style.foregroundColor : '';
var bgColor = style.backgroundColor ? "" + style.backgroundColor : '';
var border = style.borderColor ? "1px solid " + style.borderColor : '';
var shadow = style.shadowColor ? "0 2px 4px " + style.shadowColor : '';
container.style.border = border;
this.domNode.style.color = fgColor;
this.domNode.style.backgroundColor = bgColor;
container.style.boxShadow = shadow;
if (this.viewItems) {
this.viewItems.forEach(function (item) {
if (item instanceof BaseMenuActionViewItem || item instanceof MenuSeparatorActionViewItem) {
item.style(style);
}
});
}
};
Menu.prototype.getContainer = function () {
return this.scrollableElement.getDomNode();
};
Object.defineProperty(Menu.prototype, "onScroll", {
get: function () {
return this.scrollableElement.onScroll;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Menu.prototype, "scrollOffset", {
get: function () {
return this.menuElement.scrollTop;
},
enumerable: true,
configurable: true
});
Menu.prototype.focusItemByElement = function (element) {
var lastFocusedItem = this.focusedItem;
this.setFocusedItem(element);
if (lastFocusedItem !== this.focusedItem) {
this.updateFocus();
}
};
Menu.prototype.setFocusedItem = function (element) {
for (var i = 0; i < this.actionsList.children.length; i++) {
var elem = this.actionsList.children[i];
if (element === elem) {
this.focusedItem = i;
break;
}
}
};
Menu.prototype.updateFocus = function (fromRight) {
_super.prototype.updateFocus.call(this, fromRight, true);
if (typeof this.focusedItem !== 'undefined') {
// Workaround for #80047 caused by an issue in chromium
// https://bugs.chromium.org/p/chromium/issues/detail?id=414283
// When that's fixed, just call this.scrollableElement.scanDomNode()
this.scrollableElement.setScrollPosition({
scrollTop: Math.round(this.menuElement.scrollTop)
});
}
};
Menu.prototype.doGetActionViewItem = function (action, options, parentData) {
if (action instanceof actionbar_1.Separator) {
return new MenuSeparatorActionViewItem(options.context, action, { icon: true });
}
else if (action instanceof SubmenuAction) {
var menuActionViewItem = new SubmenuMenuActionViewItem(action, action.entries, parentData, options);
if (options.enableMnemonics) {
var mnemonic = menuActionViewItem.getMnemonic();
if (mnemonic && menuActionViewItem.isEnabled()) {
var actionViewItems = [];
if (this.mnemonics.has(mnemonic)) {
actionViewItems = this.mnemonics.get(mnemonic);
}
actionViewItems.push(menuActionViewItem);
this.mnemonics.set(mnemonic, actionViewItems);
}
}
return menuActionViewItem;
}
else {
var menuItemOptions = { enableMnemonics: options.enableMnemonics };
if (options.getKeyBinding) {
var keybinding = options.getKeyBinding(action);
if (keybinding) {
var keybindingLabel = keybinding.getLabel();
if (keybindingLabel) {
menuItemOptions.keybinding = keybindingLabel;
}
}
}
var menuActionViewItem = new BaseMenuActionViewItem(options.context, action, menuItemOptions);
if (options.enableMnemonics) {
var mnemonic = menuActionViewItem.getMnemonic();
if (mnemonic && menuActionViewItem.isEnabled()) {
var actionViewItems = [];
if (this.mnemonics.has(mnemonic)) {
actionViewItems = this.mnemonics.get(mnemonic);
}
actionViewItems.push(menuActionViewItem);
this.mnemonics.set(mnemonic, actionViewItems);
}
}
return menuActionViewItem;
}
};
return Menu;
}(actionbar_1.ActionBar));
exports.Menu = Menu;
var BaseMenuActionViewItem = /** @class */ (function (_super) {
__extends(BaseMenuActionViewItem, _super);
function BaseMenuActionViewItem(ctx, action, options) {
if (options === void 0) { options = {}; }
var _this = this;
options.isMenu = true;
_this = _super.call(this, action, action, options) || this;
_this.options = options;
_this.options.icon = options.icon !== undefined ? options.icon : false;
_this.options.label = options.label !== undefined ? options.label : true;
_this.cssClass = '';
// Set mnemonic
if (_this.options.label && options.enableMnemonics) {
var label = _this.getAction().label;
if (label) {
var matches = exports.MENU_MNEMONIC_REGEX.exec(label);
if (matches) {
_this.mnemonic = (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase();
}
}
}
// Add mouse up listener later to avoid accidental clicks
_this.runOnceToEnableMouseUp = new async_1.RunOnceScheduler(function () {
if (!_this.element) {
return;
}
_this._register(dom_1.addDisposableListener(_this.element, dom_1.EventType.MOUSE_UP, function (e) {
if (e.defaultPrevented) {
return;
}
dom_1.EventHelper.stop(e, true);
_this.onClick(e);
}));
}, 100);
_this._register(_this.runOnceToEnableMouseUp);
return _this;
}
BaseMenuActionViewItem.prototype.render = function (container) {
_super.prototype.render.call(this, container);
if (!this.element) {
return;
}
this.container = container;
this.item = dom_1.append(this.element, dom_1.$('a.action-menu-item'));
if (this._action.id === actionbar_1.Separator.ID) {
// A separator is a presentation item
this.item.setAttribute('role', 'presentation');
}
else {
this.item.setAttribute('role', 'menuitem');
if (this.mnemonic) {
this.item.setAttribute('aria-keyshortcuts', "" + this.mnemonic);
}
}
this.check = dom_1.append(this.item, dom_1.$('span.menu-item-check.codicon.codicon-check'));
this.check.setAttribute('role', 'none');
this.label = dom_1.append(this.item, dom_1.$('span.action-label'));
if (this.options.label && this.options.keybinding) {
dom_1.append(this.item, dom_1.$('span.keybinding')).textContent = this.options.keybinding;
}
// Adds mouse up listener to actually run the action
this.runOnceToEnableMouseUp.schedule();
this.updateClass();
this.updateLabel();
this.updateTooltip();
this.updateEnabled();
this.updateChecked();
};
BaseMenuActionViewItem.prototype.blur = function () {
_super.prototype.blur.call(this);
this.applyStyle();
};
BaseMenuActionViewItem.prototype.focus = function () {
_super.prototype.focus.call(this);
if (this.item) {
this.item.focus();
}
this.applyStyle();
};
BaseMenuActionViewItem.prototype.updatePositionInSet = function (pos, setSize) {
if (this.item) {
this.item.setAttribute('aria-posinset', "" + pos);
this.item.setAttribute('aria-setsize', "" + setSize);
}
};
BaseMenuActionViewItem.prototype.updateLabel = function () {
if (this.options.label) {
var label = this.getAction().label;
if (label) {
var cleanLabel = cleanMnemonic(label);
if (!this.options.enableMnemonics) {
label = cleanLabel;
}
if (this.label) {
this.label.setAttribute('aria-label', cleanLabel.replace(/&&/g, '&'));
}
var matches = exports.MENU_MNEMONIC_REGEX.exec(label);
if (matches) {
label = strings.escape(label);
// This is global, reset it
exports.MENU_ESCAPED_MNEMONIC_REGEX.lastIndex = 0;
var escMatch = exports.MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
// We can't use negative lookbehind so if we match our negative and skip
while (escMatch && escMatch[1]) {
escMatch = exports.MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
}
if (escMatch) {
label = label.substr(0, escMatch.index) + "" + escMatch[3] + "" + label.substr(escMatch.index + escMatch[0].length);
}
label = label.replace(/&&/g, '&');
if (this.item) {
this.item.setAttribute('aria-keyshortcuts', (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase());
}
}
else {
label = label.replace(/&&/g, '&');
}
}
if (this.label) {
this.label.innerHTML = label.trim();
}
}
};
BaseMenuActionViewItem.prototype.updateTooltip = function () {
var title = null;
if (this.getAction().tooltip) {
title = this.getAction().tooltip;
}
else if (!this.options.label && this.getAction().label && this.options.icon) {
title = this.getAction().label;
if (this.options.keybinding) {
title = nls.localize(0, null, title, this.options.keybinding);
}
}
if (title && this.item) {
this.item.title = title;
}
};
BaseMenuActionViewItem.prototype.updateClass = function () {
if (this.cssClass && this.item) {
dom_1.removeClasses(this.item, this.cssClass);
}
if (this.options.icon && this.label) {
this.cssClass = this.getAction().class || '';
dom_1.addClass(this.label, 'icon');
if (this.cssClass) {
dom_1.addClasses(this.label, this.cssClass);
}
this.updateEnabled();
}
else if (this.label) {
dom_1.removeClass(this.label, 'icon');
}
};
BaseMenuActionViewItem.prototype.updateEnabled = function () {
if (this.getAction().enabled) {
if (this.element) {
dom_1.removeClass(this.element, 'disabled');
}
if (this.item) {
dom_1.removeClass(this.item, 'disabled');
this.item.tabIndex = 0;
}
}
else {
if (this.element) {
dom_1.addClass(this.element, 'disabled');
}
if (this.item) {
dom_1.addClass(this.item, 'disabled');
dom_1.removeTabIndexAndUpdateFocus(this.item);
}
}
};
BaseMenuActionViewItem.prototype.updateChecked = function () {
if (!this.item) {
return;
}
if (this.getAction().checked) {
dom_1.addClass(this.item, 'checked');
this.item.setAttribute('role', 'menuitemcheckbox');
this.item.setAttribute('aria-checked', 'true');
}
else {
dom_1.removeClass(this.item, 'checked');
this.item.setAttribute('role', 'menuitem');
this.item.setAttribute('aria-checked', 'false');
}
};
BaseMenuActionViewItem.prototype.getMnemonic = function () {
return this.mnemonic;
};
BaseMenuActionViewItem.prototype.applyStyle = function () {
if (!this.menuStyle) {
return;
}
var isSelected = this.element && dom_1.hasClass(this.element, 'focused');
var fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
var bgColor = isSelected && this.menuStyle.selectionBackgroundColor ? this.menuStyle.selectionBackgroundColor : undefined;
var border = isSelected && this.menuStyle.selectionBorderColor ? "thin solid " + this.menuStyle.selectionBorderColor : '';
if (this.item) {
this.item.style.color = fgColor ? fgColor.toString() : '';
this.item.style.backgroundColor = bgColor ? bgColor.toString() : '';
}
if (this.check) {
this.check.style.color = fgColor ? fgColor.toString() : '';
}
if (this.container) {
this.container.style.border = border;
}
};
BaseMenuActionViewItem.prototype.style = function (style) {
this.menuStyle = style;
this.applyStyle();
};
return BaseMenuActionViewItem;
}(actionbar_1.BaseActionViewItem));
var SubmenuMenuActionViewItem = /** @class */ (function (_super) {
__extends(SubmenuMenuActionViewItem, _super);
function SubmenuMenuActionViewItem(action, submenuActions, parentData, submenuOptions) {
var _this = _super.call(this, action, action, submenuOptions) || this;
_this.submenuActions = submenuActions;
_this.parentData = parentData;
_this.submenuOptions = submenuOptions;
_this.mysubmenu = null;
_this.submenuDisposables = _this._register(new lifecycle_1.DisposableStore());
_this.mouseOver = false;
_this.expandDirection = submenuOptions && submenuOptions.expandDirection !== undefined ? submenuOptions.expandDirection : Direction.Right;
_this.showScheduler = new async_1.RunOnceScheduler(function () {
if (_this.mouseOver) {
_this.cleanupExistingSubmenu(false);
_this.createSubmenu(false);
}
}, 250);
_this.hideScheduler = new async_1.RunOnceScheduler(function () {
if (_this.element && (!dom_1.isAncestor(document.activeElement, _this.element) && _this.parentData.submenu === _this.mysubmenu)) {
_this.parentData.parent.focus(false);
_this.cleanupExistingSubmenu(true);
}
}, 750);
return _this;
}
SubmenuMenuActionViewItem.prototype.render = function (container) {
var _this = this;
_super.prototype.render.call(this, container);
if (!this.element) {
return;
}
if (this.item) {
dom_1.addClass(this.item, 'monaco-submenu-item');
this.item.setAttribute('aria-haspopup', 'true');
this.updateAriaExpanded('false');
this.submenuIndicator = dom_1.append(this.item, dom_1.$('span.submenu-indicator.codicon.codicon-chevron-right'));
this.submenuIndicator.setAttribute('aria-hidden', 'true');
}
this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.KEY_UP, function (e) {
var event = new keyboardEvent_1.StandardKeyboardEvent(e);
if (event.equals(17 /* RightArrow */) || event.equals(3 /* Enter */)) {
dom_1.EventHelper.stop(e, true);
_this.createSubmenu(true);
}
}));
this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.KEY_DOWN, function (e) {
var event = new keyboardEvent_1.StandardKeyboardEvent(e);
if (document.activeElement === _this.item) {
if (event.equals(17 /* RightArrow */) || event.equals(3 /* Enter */)) {
dom_1.EventHelper.stop(e, true);
}
}
}));
this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.MOUSE_OVER, function (e) {
if (!_this.mouseOver) {
_this.mouseOver = true;
_this.showScheduler.schedule();
}
}));
this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.MOUSE_LEAVE, function (e) {
_this.mouseOver = false;
}));
this._register(dom_1.addDisposableListener(this.element, dom_1.EventType.FOCUS_OUT, function (e) {
if (_this.element && !dom_1.isAncestor(document.activeElement, _this.element)) {
_this.hideScheduler.schedule();
}
}));
this._register(this.parentData.parent.onScroll(function () {
_this.parentData.parent.focus(false);
_this.cleanupExistingSubmenu(false);
}));
};
SubmenuMenuActionViewItem.prototype.onClick = function (e) {
// stop clicking from trying to run an action
dom_1.EventHelper.stop(e, true);
this.cleanupExistingSubmenu(false);
this.createSubmenu(true);
};
SubmenuMenuActionViewItem.prototype.cleanupExistingSubmenu = function (force) {
if (this.parentData.submenu && (force || (this.parentData.submenu !== this.mysubmenu))) {
this.parentData.submenu.dispose();
this.parentData.submenu = undefined;
this.updateAriaExpanded('false');
if (this.submenuContainer) {
this.submenuDisposables.clear();
this.submenuContainer = undefined;
}
}
};
SubmenuMenuActionViewItem.prototype.createSubmenu = function (selectFirstItem) {
var _this = this;
if (selectFirstItem === void 0) { selectFirstItem = true; }
if (!this.element) {
return;
}
if (!this.parentData.submenu) {
this.updateAriaExpanded('true');
this.submenuContainer = dom_1.append(this.element, dom_1.$('div.monaco-submenu'));
dom_1.addClasses(this.submenuContainer, 'menubar-menu-items-holder', 'context-view');
// Set the top value of the menu container before construction
// This allows the menu constructor to calculate the proper max height
var computedStyles = getComputedStyle(this.parentData.parent.domNode);
var paddingTop = parseFloat(computedStyles.paddingTop || '0') || 0;
this.submenuContainer.style.top = this.element.offsetTop - this.parentData.parent.scrollOffset - paddingTop + "px";
this.parentData.submenu = new Menu(this.submenuContainer, this.submenuActions, this.submenuOptions);
if (this.menuStyle) {
this.parentData.submenu.style(this.menuStyle);
}
var boundingRect = this.element.getBoundingClientRect();
var childBoundingRect = this.submenuContainer.getBoundingClientRect();
if (this.expandDirection === Direction.Right) {
if (window.innerWidth <= boundingRect.right + childBoundingRect.width) {
this.submenuContainer.style.left = '10px';
this.submenuContainer.style.top = this.element.offsetTop - this.parentData.parent.scrollOffset + boundingRect.height + "px";
}
else {
this.submenuContainer.style.left = this.element.offsetWidth + "px";
this.submenuContainer.style.top = this.element.offsetTop - this.parentData.parent.scrollOffset - paddingTop + "px";
}
}
else if (this.expandDirection === Direction.Left) {
this.submenuContainer.style.right = this.element.offsetWidth + "px";
this.submenuContainer.style.left = 'auto';
this.submenuContainer.style.top = this.element.offsetTop - this.parentData.parent.scrollOffset - paddingTop + "px";
}
this.submenuDisposables.add(dom_1.addDisposableListener(this.submenuContainer, dom_1.EventType.KEY_UP, function (e) {
var event = new keyboardEvent_1.StandardKeyboardEvent(e);
if (event.equals(15 /* LeftArrow */)) {
dom_1.EventHelper.stop(e, true);
_this.parentData.parent.focus();
_this.cleanupExistingSubmenu(true);
}
}));
this.submenuDisposables.add(dom_1.addDisposableListener(this.submenuContainer, dom_1.EventType.KEY_DOWN, function (e) {
var event = new keyboardEvent_1.StandardKeyboardEvent(e);
if (event.equals(15 /* LeftArrow */)) {
dom_1.EventHelper.stop(e, true);
}
}));
this.submenuDisposables.add(this.parentData.submenu.onDidCancel(function () {
_this.parentData.parent.focus();
_this.cleanupExistingSubmenu(true);
}));
this.parentData.submenu.focus(selectFirstItem);
this.mysubmenu = this.parentData.submenu;
}
else {
this.parentData.submenu.focus(false);
}
};
SubmenuMenuActionViewItem.prototype.updateAriaExpanded = function (value) {
var _a;
if (this.item) {
(_a = this.item) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-expanded', value);
}
};
SubmenuMenuActionViewItem.prototype.applyStyle = function () {
_super.prototype.applyStyle.call(this);
if (!this.menuStyle) {
return;
}
var isSelected = this.element && dom_1.hasClass(this.element, 'focused');
var fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
if (this.submenuIndicator) {
this.submenuIndicator.style.color = fgColor ? "" + fgColor : '';
}
if (this.parentData.submenu) {
this.parentData.submenu.style(this.menuStyle);
}
};
SubmenuMenuActionViewItem.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.hideScheduler.dispose();
if (this.mysubmenu) {
this.mysubmenu.dispose();
this.mysubmenu = null;
}
if (this.submenuContainer) {
this.submenuContainer = undefined;
}
};
return SubmenuMenuActionViewItem;
}(BaseMenuActionViewItem));
var MenuSeparatorActionViewItem = /** @class */ (function (_super) {
__extends(MenuSeparatorActionViewItem, _super);
function MenuSeparatorActionViewItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
MenuSeparatorActionViewItem.prototype.style = function (style) {
if (this.label) {
this.label.style.borderBottomColor = style.separatorColor ? "" + style.separatorColor : '';
}
};
return MenuSeparatorActionViewItem;
}(actionbar_1.ActionViewItem));
function cleanMnemonic(label) {
var regex = exports.MENU_MNEMONIC_REGEX;
var matches = regex.exec(label);
if (!matches) {
return label;
}
var mnemonicInText = !matches[1];
return label.replace(regex, mnemonicInText ? '$2$3' : '').trim();
}
exports.cleanMnemonic = cleanMnemonic;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[405/*vs/base/browser/contextmenu*/], __M([0/*require*/,1/*exports*/,205/*vs/base/browser/ui/menu/menu*/]), function (require, exports, menu_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ContextSubMenu = /** @class */ (function (_super) {
__extends(ContextSubMenu, _super);
function ContextSubMenu(label, entries) {
var _this = _super.call(this, label, entries, 'contextsubmenu') || this;
_this.entries = entries;
return _this;
}
return ContextSubMenu;
}(menu_1.SubmenuAction));
exports.ContextSubMenu = ContextSubMenu;
});
define(__m[406/*vs/nls!vs/base/browser/ui/tree/abstractTree*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/browser/ui/tree/abstractTree", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[154/*vs/base/browser/ui/tree/abstractTree*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,153/*vs/base/browser/ui/list/listWidget*/,6/*vs/base/browser/dom*/,4/*vs/base/common/event*/,56/*vs/base/browser/keyboardEvent*/,98/*vs/base/browser/dnd*/,19/*vs/base/common/arrays*/,140/*vs/base/browser/ui/list/listView*/,52/*vs/base/browser/event*/,61/*vs/base/common/filters*/,129/*vs/base/browser/ui/tree/indexTreeModel*/,406/*vs/nls!vs/base/browser/ui/tree/abstractTree*/,15/*vs/base/common/async*/,16/*vs/base/common/platform*/,38/*vs/base/common/map*/,131/*vs/base/common/numbers*/,87/*vs/base/common/collections*/,280/*vs/css!vs/base/browser/ui/tree/media/tree*/]), function (require, exports, lifecycle_1, listWidget_1, dom_1, event_1, keyboardEvent_1, dnd_1, arrays_1, listView_1, event_2, filters_1, indexTreeModel_1, nls_1, async_1, platform_1, map_1, numbers_1, collections_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TreeElementsDragAndDropData = /** @class */ (function (_super) {
__extends(TreeElementsDragAndDropData, _super);
function TreeElementsDragAndDropData(data) {
var _this = _super.call(this, data.elements.map(function (node) { return node.element; })) || this;
_this.data = data;
return _this;
}
return TreeElementsDragAndDropData;
}(listView_1.ElementsDragAndDropData));
function asTreeDragAndDropData(data) {
if (data instanceof listView_1.ElementsDragAndDropData) {
return new TreeElementsDragAndDropData(data);
}
return data;
}
var TreeNodeListDragAndDrop = /** @class */ (function () {
function TreeNodeListDragAndDrop(modelProvider, dnd) {
this.modelProvider = modelProvider;
this.dnd = dnd;
this.autoExpandDisposable = lifecycle_1.Disposable.None;
}
TreeNodeListDragAndDrop.prototype.getDragURI = function (node) {
return this.dnd.getDragURI(node.element);
};
TreeNodeListDragAndDrop.prototype.getDragLabel = function (nodes, originalEvent) {
if (this.dnd.getDragLabel) {
return this.dnd.getDragLabel(nodes.map(function (node) { return node.element; }), originalEvent);
}
return undefined;
};
TreeNodeListDragAndDrop.prototype.onDragStart = function (data, originalEvent) {
if (this.dnd.onDragStart) {
this.dnd.onDragStart(asTreeDragAndDropData(data), originalEvent);
}
};
TreeNodeListDragAndDrop.prototype.onDragOver = function (data, targetNode, targetIndex, originalEvent, raw) {
var _this = this;
if (raw === void 0) { raw = true; }
var result = this.dnd.onDragOver(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
var didChangeAutoExpandNode = this.autoExpandNode !== targetNode;
if (didChangeAutoExpandNode) {
this.autoExpandDisposable.dispose();
this.autoExpandNode = targetNode;
}
if (typeof targetNode === 'undefined') {
return result;
}
if (didChangeAutoExpandNode && typeof result !== 'boolean' && result.autoExpand) {
this.autoExpandDisposable = async_1.disposableTimeout(function () {
var model = _this.modelProvider();
var ref = model.getNodeLocation(targetNode);
if (model.isCollapsed(ref)) {
model.setCollapsed(ref, false);
}
_this.autoExpandNode = undefined;
}, 500);
}
if (typeof result === 'boolean' || !result.accept || typeof result.bubble === 'undefined' || result.feedback) {
if (!raw) {
var accept = typeof result === 'boolean' ? result : result.accept;
var effect = typeof result === 'boolean' ? undefined : result.effect;
return { accept: accept, effect: effect, feedback: [targetIndex] };
}
return result;
}
if (result.bubble === 1 /* Up */) {
var model_1 = this.modelProvider();
var ref_1 = model_1.getNodeLocation(targetNode);
var parentRef = model_1.getParentNodeLocation(ref_1);
var parentNode = model_1.getNode(parentRef);
var parentIndex = parentRef && model_1.getListIndex(parentRef);
return this.onDragOver(data, parentNode, parentIndex, originalEvent, false);
}
var model = this.modelProvider();
var ref = model.getNodeLocation(targetNode);
var start = model.getListIndex(ref);
var length = model.getListRenderCount(ref);
return __assign(__assign({}, result), { feedback: arrays_1.range(start, start + length) });
};
TreeNodeListDragAndDrop.prototype.drop = function (data, targetNode, targetIndex, originalEvent) {
this.autoExpandDisposable.dispose();
this.autoExpandNode = undefined;
this.dnd.drop(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
};
TreeNodeListDragAndDrop.prototype.onDragEnd = function (originalEvent) {
if (this.dnd.onDragEnd) {
this.dnd.onDragEnd(originalEvent);
}
};
return TreeNodeListDragAndDrop;
}());
function asListOptions(modelProvider, options) {
return options && __assign(__assign({}, options), { identityProvider: options.identityProvider && {
getId: function (el) {
return options.identityProvider.getId(el.element);
}
}, dnd: options.dnd && new TreeNodeListDragAndDrop(modelProvider, options.dnd), multipleSelectionController: options.multipleSelectionController && {
isSelectionSingleChangeEvent: function (e) {
return options.multipleSelectionController.isSelectionSingleChangeEvent(__assign(__assign({}, e), { element: e.element }));
},
isSelectionRangeChangeEvent: function (e) {
return options.multipleSelectionController.isSelectionRangeChangeEvent(__assign(__assign({}, e), { element: e.element }));
}
}, accessibilityProvider: options.accessibilityProvider && __assign(__assign({}, options.accessibilityProvider), { getAriaLabel: function (e) {
return options.accessibilityProvider.getAriaLabel(e.element);
},
getAriaLevel: function (node) {
return node.depth;
}, getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (function (node) {
return options.accessibilityProvider.getActiveDescendantId(node.element);
}) }), keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && __assign(__assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel: function (node) {
return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element);
} }), enableKeyboardNavigation: options.simpleKeyboardNavigation, ariaProvider: {
getSetSize: function (node) {
var model = modelProvider();
var ref = model.getNodeLocation(node);
var parentRef = model.getParentNodeLocation(ref);
var parentNode = model.getNode(parentRef);
return parentNode.visibleChildrenCount;
},
getPosInSet: function (node) {
return node.visibleChildIndex + 1;
},
isChecked: options.ariaProvider && options.ariaProvider.isChecked ? function (node) {
return options.ariaProvider.isChecked(node.element);
} : undefined,
getRole: options.ariaProvider && options.ariaProvider.getRole ? function (node) {
return options.ariaProvider.getRole(node.element);
} : undefined
} });
}
var ComposedTreeDelegate = /** @class */ (function () {
function ComposedTreeDelegate(delegate) {
this.delegate = delegate;
}
ComposedTreeDelegate.prototype.getHeight = function (element) {
return this.delegate.getHeight(element.element);
};
ComposedTreeDelegate.prototype.getTemplateId = function (element) {
return this.delegate.getTemplateId(element.element);
};
ComposedTreeDelegate.prototype.hasDynamicHeight = function (element) {
return !!this.delegate.hasDynamicHeight && this.delegate.hasDynamicHeight(element.element);
};
ComposedTreeDelegate.prototype.setDynamicHeight = function (element, height) {
if (this.delegate.setDynamicHeight) {
this.delegate.setDynamicHeight(element.element, height);
}
};
return ComposedTreeDelegate;
}());
exports.ComposedTreeDelegate = ComposedTreeDelegate;
var RenderIndentGuides;
(function (RenderIndentGuides) {
RenderIndentGuides["None"] = "none";
RenderIndentGuides["OnHover"] = "onHover";
RenderIndentGuides["Always"] = "always";
})(RenderIndentGuides = exports.RenderIndentGuides || (exports.RenderIndentGuides = {}));
var EventCollection = /** @class */ (function () {
function EventCollection(onDidChange, _elements) {
var _this = this;
if (_elements === void 0) { _elements = []; }
this._elements = _elements;
this.onDidChange = event_1.Event.forEach(onDidChange, function (elements) { return _this._elements = elements; });
}
Object.defineProperty(EventCollection.prototype, "elements", {
get: function () {
return this._elements;
},
enumerable: true,
configurable: true
});
return EventCollection;
}());
var TreeRenderer = /** @class */ (function () {
function TreeRenderer(renderer, modelProvider, onDidChangeCollapseState, activeNodes, options) {
if (options === void 0) { options = {}; }
this.renderer = renderer;
this.modelProvider = modelProvider;
this.activeNodes = activeNodes;
this.renderedElements = new Map();
this.renderedNodes = new Map();
this.indent = TreeRenderer.DefaultIndent;
this.hideTwistiesOfChildlessElements = false;
this.shouldRenderIndentGuides = false;
this.renderedIndentGuides = new collections_1.SetMap();
this.activeIndentNodes = new Set();
this.indentGuidesDisposable = lifecycle_1.Disposable.None;
this.disposables = new lifecycle_1.DisposableStore();
this.templateId = renderer.templateId;
this.updateOptions(options);
event_1.Event.map(onDidChangeCollapseState, function (e) { return e.node; })(this.onDidChangeNodeTwistieState, this, this.disposables);
if (renderer.onDidChangeTwistieState) {
renderer.onDidChangeTwistieState(this.onDidChangeTwistieState, this, this.disposables);
}
}
TreeRenderer.prototype.updateOptions = function (options) {
if (options === void 0) { options = {}; }
if (typeof options.indent !== 'undefined') {
this.indent = numbers_1.clamp(options.indent, 0, 40);
}
if (typeof options.renderIndentGuides !== 'undefined') {
var shouldRenderIndentGuides = options.renderIndentGuides !== RenderIndentGuides.None;
if (shouldRenderIndentGuides !== this.shouldRenderIndentGuides) {
this.shouldRenderIndentGuides = shouldRenderIndentGuides;
this.indentGuidesDisposable.dispose();
if (shouldRenderIndentGuides) {
var disposables = new lifecycle_1.DisposableStore();
this.activeNodes.onDidChange(this._onDidChangeActiveNodes, this, disposables);
this.indentGuidesDisposable = disposables;
this._onDidChangeActiveNodes(this.activeNodes.elements);
}
}
}
if (typeof options.hideTwistiesOfChildlessElements !== 'undefined') {
this.hideTwistiesOfChildlessElements = options.hideTwistiesOfChildlessElements;
}
};
TreeRenderer.prototype.renderTemplate = function (container) {
var el = dom_1.append(container, dom_1.$('.monaco-tl-row'));
var indent = dom_1.append(el, dom_1.$('.monaco-tl-indent'));
var twistie = dom_1.append(el, dom_1.$('.monaco-tl-twistie'));
var contents = dom_1.append(el, dom_1.$('.monaco-tl-contents'));
var templateData = this.renderer.renderTemplate(contents);
return { container: container, indent: indent, twistie: twistie, indentGuidesDisposable: lifecycle_1.Disposable.None, templateData: templateData };
};
TreeRenderer.prototype.renderElement = function (node, index, templateData, height) {
if (typeof height === 'number') {
this.renderedNodes.set(node, { templateData: templateData, height: height });
this.renderedElements.set(node.element, node);
}
var indent = TreeRenderer.DefaultIndent + (node.depth - 1) * this.indent;
templateData.twistie.style.paddingLeft = indent + "px";
templateData.indent.style.width = indent + this.indent - 16 + "px";
this.renderTwistie(node, templateData);
if (typeof height === 'number') {
this.renderIndentGuides(node, templateData);
}
this.renderer.renderElement(node, index, templateData.templateData, height);
};
TreeRenderer.prototype.disposeElement = function (node, index, templateData, height) {
templateData.indentGuidesDisposable.dispose();
if (this.renderer.disposeElement) {
this.renderer.disposeElement(node, index, templateData.templateData, height);
}
if (typeof height === 'number') {
this.renderedNodes.delete(node);
this.renderedElements.delete(node.element);
}
};
TreeRenderer.prototype.disposeTemplate = function (templateData) {
this.renderer.disposeTemplate(templateData.templateData);
};
TreeRenderer.prototype.onDidChangeTwistieState = function (element) {
var node = this.renderedElements.get(element);
if (!node) {
return;
}
this.onDidChangeNodeTwistieState(node);
};
TreeRenderer.prototype.onDidChangeNodeTwistieState = function (node) {
var data = this.renderedNodes.get(node);
if (!data) {
return;
}
this.renderTwistie(node, data.templateData);
this._onDidChangeActiveNodes(this.activeNodes.elements);
this.renderIndentGuides(node, data.templateData);
};
TreeRenderer.prototype.renderTwistie = function (node, templateData) {
if (this.renderer.renderTwistie) {
this.renderer.renderTwistie(node.element, templateData.twistie);
}
if (node.collapsible && (!this.hideTwistiesOfChildlessElements || node.visibleChildrenCount > 0)) {
dom_1.addClasses(templateData.twistie, 'codicon', 'codicon-chevron-down', 'collapsible');
dom_1.toggleClass(templateData.twistie, 'collapsed', node.collapsed);
}
else {
dom_1.removeClasses(templateData.twistie, 'codicon', 'codicon-chevron-down', 'collapsible', 'collapsed');
}
if (node.collapsible) {
templateData.container.setAttribute('aria-expanded', String(!node.collapsed));
}
else {
templateData.container.removeAttribute('aria-expanded');
}
};
TreeRenderer.prototype.renderIndentGuides = function (target, templateData) {
var _this = this;
dom_1.clearNode(templateData.indent);
templateData.indentGuidesDisposable.dispose();
if (!this.shouldRenderIndentGuides) {
return;
}
var disposableStore = new lifecycle_1.DisposableStore();
var model = this.modelProvider();
var node = target;
var _loop_1 = function () {
var ref = model.getNodeLocation(node);
var parentRef = model.getParentNodeLocation(ref);
if (!parentRef) {
return "break";
}
var parent_1 = model.getNode(parentRef);
var guide = dom_1.$('.indent-guide', { style: "width: " + this_1.indent + "px" });
if (this_1.activeIndentNodes.has(parent_1)) {
dom_1.addClass(guide, 'active');
}
if (templateData.indent.childElementCount === 0) {
templateData.indent.appendChild(guide);
}
else {
templateData.indent.insertBefore(guide, templateData.indent.firstElementChild);
}
this_1.renderedIndentGuides.add(parent_1, guide);
disposableStore.add(lifecycle_1.toDisposable(function () { return _this.renderedIndentGuides.delete(parent_1, guide); }));
node = parent_1;
};
var this_1 = this;
while (true) {
var state_1 = _loop_1();
if (state_1 === "break")
break;
}
templateData.indentGuidesDisposable = disposableStore;
};
TreeRenderer.prototype._onDidChangeActiveNodes = function (nodes) {
var _this = this;
if (!this.shouldRenderIndentGuides) {
return;
}
var set = new Set();
var model = this.modelProvider();
nodes.forEach(function (node) {
var ref = model.getNodeLocation(node);
try {
var parentRef = model.getParentNodeLocation(ref);
if (node.collapsible && node.children.length > 0 && !node.collapsed) {
set.add(node);
}
else if (parentRef) {
set.add(model.getNode(parentRef));
}
}
catch (_a) {
// noop
}
});
this.activeIndentNodes.forEach(function (node) {
if (!set.has(node)) {
_this.renderedIndentGuides.forEach(node, function (line) { return dom_1.removeClass(line, 'active'); });
}
});
set.forEach(function (node) {
if (!_this.activeIndentNodes.has(node)) {
_this.renderedIndentGuides.forEach(node, function (line) { return dom_1.addClass(line, 'active'); });
}
});
this.activeIndentNodes = set;
};
TreeRenderer.prototype.dispose = function () {
this.renderedNodes.clear();
this.renderedElements.clear();
this.indentGuidesDisposable.dispose();
lifecycle_1.dispose(this.disposables);
};
TreeRenderer.DefaultIndent = 8;
return TreeRenderer;
}());
var TypeFilter = /** @class */ (function () {
function TypeFilter(tree, keyboardNavigationLabelProvider, _filter) {
this.tree = tree;
this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
this._filter = _filter;
this._totalCount = 0;
this._matchCount = 0;
this._pattern = '';
this._lowercasePattern = '';
this.disposables = new lifecycle_1.DisposableStore();
tree.onWillRefilter(this.reset, this, this.disposables);
}
Object.defineProperty(TypeFilter.prototype, "totalCount", {
get: function () { return this._totalCount; },
enumerable: true,
configurable: true
});
Object.defineProperty(TypeFilter.prototype, "matchCount", {
get: function () { return this._matchCount; },
enumerable: true,
configurable: true
});
Object.defineProperty(TypeFilter.prototype, "pattern", {
set: function (pattern) {
this._pattern = pattern;
this._lowercasePattern = pattern.toLowerCase();
},
enumerable: true,
configurable: true
});
TypeFilter.prototype.filter = function (element, parentVisibility) {
if (this._filter) {
var result = this._filter.filter(element, parentVisibility);
if (this.tree.options.simpleKeyboardNavigation) {
return result;
}
var visibility = void 0;
if (typeof result === 'boolean') {
visibility = result ? 1 /* Visible */ : 0 /* Hidden */;
}
else if (indexTreeModel_1.isFilterResult(result)) {
visibility = indexTreeModel_1.getVisibleState(result.visibility);
}
else {
visibility = result;
}
if (visibility === 0 /* Hidden */) {
return false;
}
}
this._totalCount++;
if (this.tree.options.simpleKeyboardNavigation || !this._pattern) {
this._matchCount++;
return { data: filters_1.FuzzyScore.Default, visibility: true };
}
var label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(element);
var labelStr = label && label.toString();
if (typeof labelStr === 'undefined') {
return { data: filters_1.FuzzyScore.Default, visibility: true };
}
var score = filters_1.fuzzyScore(this._pattern, this._lowercasePattern, 0, labelStr, labelStr.toLowerCase(), 0, true);
if (!score) {
if (this.tree.options.filterOnType) {
return 2 /* Recurse */;
}
else {
return { data: filters_1.FuzzyScore.Default, visibility: true };
}
// DEMO: smarter filter ?
// return parentVisibility === TreeVisibility.Visible ? true : TreeVisibility.Recurse;
}
this._matchCount++;
return { data: score, visibility: true };
};
TypeFilter.prototype.reset = function () {
this._totalCount = 0;
this._matchCount = 0;
};
TypeFilter.prototype.dispose = function () {
lifecycle_1.dispose(this.disposables);
};
return TypeFilter;
}());
var TypeFilterController = /** @class */ (function () {
function TypeFilterController(tree, model, view, filter, keyboardNavigationDelegate) {
this.tree = tree;
this.view = view;
this.filter = filter;
this.keyboardNavigationDelegate = keyboardNavigationDelegate;
this._enabled = false;
this._pattern = '';
this._empty = false;
this._onDidChangeEmptyState = new event_1.Emitter();
this.positionClassName = 'ne';
this.automaticKeyboardNavigation = true;
this.triggered = false;
this._onDidChangePattern = new event_1.Emitter();
this.enabledDisposables = new lifecycle_1.DisposableStore();
this.disposables = new lifecycle_1.DisposableStore();
this.domNode = dom_1.$(".monaco-list-type-filter." + this.positionClassName);
this.domNode.draggable = true;
event_2.domEvent(this.domNode, 'dragstart')(this.onDragStart, this, this.disposables);
this.messageDomNode = dom_1.append(view.getHTMLElement(), dom_1.$(".monaco-list-type-filter-message"));
this.labelDomNode = dom_1.append(this.domNode, dom_1.$('span.label'));
var controls = dom_1.append(this.domNode, dom_1.$('.controls'));
this._filterOnType = !!tree.options.filterOnType;
this.filterOnTypeDomNode = dom_1.append(controls, dom_1.$('input.filter.codicon.codicon-list-selection'));
this.filterOnTypeDomNode.type = 'checkbox';
this.filterOnTypeDomNode.checked = this._filterOnType;
this.filterOnTypeDomNode.tabIndex = -1;
this.updateFilterOnTypeTitle();
event_2.domEvent(this.filterOnTypeDomNode, 'input')(this.onDidChangeFilterOnType, this, this.disposables);
this.clearDomNode = dom_1.append(controls, dom_1.$('button.clear.codicon.codicon-close'));
this.clearDomNode.tabIndex = -1;
this.clearDomNode.title = nls_1.localize(0, null);
this.keyboardNavigationEventFilter = tree.options.keyboardNavigationEventFilter;
model.onDidSplice(this.onDidSpliceModel, this, this.disposables);
this.updateOptions(tree.options);
}
Object.defineProperty(TypeFilterController.prototype, "enabled", {
get: function () { return this._enabled; },
enumerable: true,
configurable: true
});
Object.defineProperty(TypeFilterController.prototype, "pattern", {
get: function () { return this._pattern; },
enumerable: true,
configurable: true
});
Object.defineProperty(TypeFilterController.prototype, "filterOnType", {
get: function () { return this._filterOnType; },
enumerable: true,
configurable: true
});
TypeFilterController.prototype.updateOptions = function (options) {
if (options.simpleKeyboardNavigation) {
this.disable();
}
else {
this.enable();
}
if (typeof options.filterOnType !== 'undefined') {
this._filterOnType = !!options.filterOnType;
this.filterOnTypeDomNode.checked = this._filterOnType;
}
if (typeof options.automaticKeyboardNavigation !== 'undefined') {
this.automaticKeyboardNavigation = options.automaticKeyboardNavigation;
}
this.tree.refilter();
this.render();
if (!this.automaticKeyboardNavigation) {
this.onEventOrInput('');
}
};
TypeFilterController.prototype.enable = function () {
var _this = this;
if (this._enabled) {
return;
}
var onKeyDown = event_1.Event.chain(event_2.domEvent(this.view.getHTMLElement(), 'keydown'))
.filter(function (e) { return !isInputElement(e.target) || e.target === _this.filterOnTypeDomNode; })
.filter(function (e) { return e.key !== 'Dead' && !/^Media/.test(e.key); })
.map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); })
.filter(this.keyboardNavigationEventFilter || (function () { return true; }))
.filter(function () { return _this.automaticKeyboardNavigation || _this.triggered; })
.filter(function (e) { return _this.keyboardNavigationDelegate.mightProducePrintableCharacter(e) || ((_this.pattern.length > 0 || _this.triggered) && ((e.keyCode === 9 /* Escape */ || e.keyCode === 1 /* Backspace */) && !e.altKey && !e.ctrlKey && !e.metaKey) || (e.keyCode === 1 /* Backspace */ && (platform_1.isMacintosh ? (e.altKey && !e.metaKey) : e.ctrlKey) && !e.shiftKey)); })
.forEach(function (e) { e.stopPropagation(); e.preventDefault(); })
.event;
var onClear = event_2.domEvent(this.clearDomNode, 'click');
event_1.Event.chain(event_1.Event.any(onKeyDown, onClear))
.event(this.onEventOrInput, this, this.enabledDisposables);
this.filter.pattern = '';
this.tree.refilter();
this.render();
this._enabled = true;
this.triggered = false;
};
TypeFilterController.prototype.disable = function () {
if (!this._enabled) {
return;
}
this.domNode.remove();
this.enabledDisposables.clear();
this.tree.refilter();
this.render();
this._enabled = false;
this.triggered = false;
};
TypeFilterController.prototype.onEventOrInput = function (e) {
if (typeof e === 'string') {
this.onInput(e);
}
else if (e instanceof MouseEvent || e.keyCode === 9 /* Escape */ || (e.keyCode === 1 /* Backspace */ && (platform_1.isMacintosh ? e.altKey : e.ctrlKey))) {
this.onInput('');
}
else if (e.keyCode === 1 /* Backspace */) {
this.onInput(this.pattern.length === 0 ? '' : this.pattern.substr(0, this.pattern.length - 1));
}
else {
this.onInput(this.pattern + e.browserEvent.key);
}
};
TypeFilterController.prototype.onInput = function (pattern) {
var container = this.view.getHTMLElement();
if (pattern && !this.domNode.parentElement) {
container.append(this.domNode);
}
else if (!pattern && this.domNode.parentElement) {
this.domNode.remove();
this.tree.domFocus();
}
this._pattern = pattern;
this._onDidChangePattern.fire(pattern);
this.filter.pattern = pattern;
this.tree.refilter();
if (pattern) {
this.tree.focusNext(0, true, undefined, function (node) { return !filters_1.FuzzyScore.isDefault(node.filterData); });
}
var focus = this.tree.getFocus();
if (focus.length > 0) {
var element = focus[0];
if (this.tree.getRelativeTop(element) === null) {
this.tree.reveal(element, 0.5);
}
}
this.render();
if (!pattern) {
this.triggered = false;
}
};
TypeFilterController.prototype.onDragStart = function () {
var _this = this;
var container = this.view.getHTMLElement();
var left = dom_1.getDomNodePagePosition(container).left;
var containerWidth = container.clientWidth;
var midContainerWidth = containerWidth / 2;
var width = this.domNode.clientWidth;
var disposables = new lifecycle_1.DisposableStore();
var positionClassName = this.positionClassName;
var updatePosition = function () {
switch (positionClassName) {
case 'nw':
_this.domNode.style.top = "4px";
_this.domNode.style.left = "4px";
break;
case 'ne':
_this.domNode.style.top = "4px";
_this.domNode.style.left = containerWidth - width - 6 + "px";
break;
}
};
var onDragOver = function (event) {
event.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
var x = event.screenX - left;
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'none';
}
if (x < midContainerWidth) {
positionClassName = 'nw';
}
else {
positionClassName = 'ne';
}
updatePosition();
};
var onDragEnd = function () {
_this.positionClassName = positionClassName;
_this.domNode.className = "monaco-list-type-filter " + _this.positionClassName;
_this.domNode.style.top = '';
_this.domNode.style.left = '';
lifecycle_1.dispose(disposables);
};
updatePosition();
dom_1.removeClass(this.domNode, positionClassName);
dom_1.addClass(this.domNode, 'dragging');
disposables.add(lifecycle_1.toDisposable(function () { return dom_1.removeClass(_this.domNode, 'dragging'); }));
event_2.domEvent(document, 'dragover')(onDragOver, null, disposables);
event_2.domEvent(this.domNode, 'dragend')(onDragEnd, null, disposables);
dnd_1.StaticDND.CurrentDragAndDropData = new dnd_1.DragAndDropData('vscode-ui');
disposables.add(lifecycle_1.toDisposable(function () { return dnd_1.StaticDND.CurrentDragAndDropData = undefined; }));
};
TypeFilterController.prototype.onDidSpliceModel = function () {
if (!this._enabled || this.pattern.length === 0) {
return;
}
this.tree.refilter();
this.render();
};
TypeFilterController.prototype.onDidChangeFilterOnType = function () {
this.tree.updateOptions({ filterOnType: this.filterOnTypeDomNode.checked });
this.tree.refilter();
this.tree.domFocus();
this.render();
this.updateFilterOnTypeTitle();
};
TypeFilterController.prototype.updateFilterOnTypeTitle = function () {
if (this.filterOnType) {
this.filterOnTypeDomNode.title = nls_1.localize(1, null);
}
else {
this.filterOnTypeDomNode.title = nls_1.localize(2, null);
}
};
TypeFilterController.prototype.render = function () {
var noMatches = this.filter.totalCount > 0 && this.filter.matchCount === 0;
if (this.pattern && this.tree.options.filterOnType && noMatches) {
this.messageDomNode.textContent = nls_1.localize(3, null);
this._empty = true;
}
else {
this.messageDomNode.innerHTML = '';
this._empty = false;
}
dom_1.toggleClass(this.domNode, 'no-matches', noMatches);
this.domNode.title = nls_1.localize(4, null, this.filter.matchCount, this.filter.totalCount);
this.labelDomNode.textContent = this.pattern.length > 16 ? '…' + this.pattern.substr(this.pattern.length - 16) : this.pattern;
this._onDidChangeEmptyState.fire(this._empty);
};
TypeFilterController.prototype.shouldAllowFocus = function (node) {
if (!this.enabled || !this.pattern || this.filterOnType) {
return true;
}
if (this.filter.totalCount > 0 && this.filter.matchCount <= 1) {
return true;
}
return !filters_1.FuzzyScore.isDefault(node.filterData);
};
TypeFilterController.prototype.dispose = function () {
if (this._enabled) {
this.domNode.remove();
this.enabledDisposables.dispose();
this._enabled = false;
this.triggered = false;
}
this._onDidChangePattern.dispose();
lifecycle_1.dispose(this.disposables);
};
return TypeFilterController;
}());
function isInputElement(e) {
return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA';
}
function asTreeEvent(event) {
return {
elements: event.elements.map(function (node) { return node.element; }),
browserEvent: event.browserEvent
};
}
function dfs(node, fn) {
fn(node);
node.children.forEach(function (child) { return dfs(child, fn); });
}
/**
* The trait concept needs to exist at the tree level, because collapsed
* tree nodes will not be known by the list.
*/
var Trait = /** @class */ (function () {
function Trait(identityProvider) {
this.identityProvider = identityProvider;
this.nodes = [];
this._onDidChange = new event_1.Emitter();
this.onDidChange = this._onDidChange.event;
}
Object.defineProperty(Trait.prototype, "nodeSet", {
get: function () {
if (!this._nodeSet) {
this._nodeSet = this.createNodeSet();
}
return this._nodeSet;
},
enumerable: true,
configurable: true
});
Trait.prototype.set = function (nodes, browserEvent) {
if (arrays_1.equals(this.nodes, nodes)) {
return;
}
this._set(nodes, false, browserEvent);
};
Trait.prototype._set = function (nodes, silent, browserEvent) {
this.nodes = __spreadArrays(nodes);
this.elements = undefined;
this._nodeSet = undefined;
if (!silent) {
var that_1 = this;
this._onDidChange.fire({ get elements() { return that_1.get(); }, browserEvent: browserEvent });
}
};
Trait.prototype.get = function () {
if (!this.elements) {
this.elements = this.nodes.map(function (node) { return node.element; });
}
return __spreadArrays(this.elements);
};
Trait.prototype.getNodes = function () {
return this.nodes;
};
Trait.prototype.has = function (node) {
return this.nodeSet.has(node);
};
Trait.prototype.onDidModelSplice = function (_a) {
var _this = this;
var insertedNodes = _a.insertedNodes, deletedNodes = _a.deletedNodes;
if (!this.identityProvider) {
var set_1 = this.createNodeSet();
var visit_1 = function (node) { return set_1.delete(node); };
deletedNodes.forEach(function (node) { return dfs(node, visit_1); });
this.set(map_1.values(set_1));
return;
}
var deletedNodesIdSet = new Set();
var deletedNodesVisitor = function (node) { return deletedNodesIdSet.add(_this.identityProvider.getId(node.element).toString()); };
deletedNodes.forEach(function (node) { return dfs(node, deletedNodesVisitor); });
var insertedNodesMap = new Map();
var insertedNodesVisitor = function (node) { return insertedNodesMap.set(_this.identityProvider.getId(node.element).toString(), node); };
insertedNodes.forEach(function (node) { return dfs(node, insertedNodesVisitor); });
var nodes = [];
for (var _i = 0, _b = this.nodes; _i < _b.length; _i++) {
var node = _b[_i];
var id = this.identityProvider.getId(node.element).toString();
var wasDeleted = deletedNodesIdSet.has(id);
if (!wasDeleted) {
nodes.push(node);
}
else {
var insertedNode = insertedNodesMap.get(id);
if (insertedNode) {
nodes.push(insertedNode);
}
}
}
this._set(nodes, true);
};
Trait.prototype.createNodeSet = function () {
var set = new Set();
for (var _i = 0, _a = this.nodes; _i < _a.length; _i++) {
var node = _a[_i];
set.add(node);
}
return set;
};
return Trait;
}());
var TreeNodeListMouseController = /** @class */ (function (_super) {
__extends(TreeNodeListMouseController, _super);
function TreeNodeListMouseController(list, tree) {
var _this = _super.call(this, list) || this;
_this.tree = tree;
return _this;
}
TreeNodeListMouseController.prototype.onPointer = function (e) {
if (isInputElement(e.browserEvent.target)) {
return;
}
var node = e.element;
if (!node) {
return _super.prototype.onPointer.call(this, e);
}
if (this.isSelectionRangeChangeEvent(e) || this.isSelectionSingleChangeEvent(e)) {
return _super.prototype.onPointer.call(this, e);
}
var onTwistie = dom_1.hasClass(e.browserEvent.target, 'monaco-tl-twistie');
if (!this.tree.openOnSingleClick && e.browserEvent.detail !== 2 && !onTwistie) {
return _super.prototype.onPointer.call(this, e);
}
var expandOnlyOnTwistieClick = false;
if (typeof this.tree.expandOnlyOnTwistieClick === 'function') {
expandOnlyOnTwistieClick = this.tree.expandOnlyOnTwistieClick(node.element);
}
else {
expandOnlyOnTwistieClick = !!this.tree.expandOnlyOnTwistieClick;
}
if (expandOnlyOnTwistieClick && !onTwistie) {
return _super.prototype.onPointer.call(this, e);
}
if (node.collapsible) {
var model = this.tree.model; // internal
var location_1 = model.getNodeLocation(node);
var recursive = e.browserEvent.altKey;
model.setCollapsed(location_1, undefined, recursive);
if (expandOnlyOnTwistieClick && onTwistie) {
return;
}
}
_super.prototype.onPointer.call(this, e);
};
TreeNodeListMouseController.prototype.onDoubleClick = function (e) {
var onTwistie = dom_1.hasClass(e.browserEvent.target, 'monaco-tl-twistie');
if (onTwistie) {
return;
}
_super.prototype.onDoubleClick.call(this, e);
};
return TreeNodeListMouseController;
}(listWidget_1.MouseController));
/**
* We use this List subclass to restore selection and focus as nodes
* get rendered in the list, possibly due to a node expand() call.
*/
var TreeNodeList = /** @class */ (function (_super) {
__extends(TreeNodeList, _super);
function TreeNodeList(user, container, virtualDelegate, renderers, focusTrait, selectionTrait, options) {
var _this = _super.call(this, user, container, virtualDelegate, renderers, options) || this;
_this.focusTrait = focusTrait;
_this.selectionTrait = selectionTrait;
return _this;
}
TreeNodeList.prototype.createMouseController = function (options) {
return new TreeNodeListMouseController(this, options.tree);
};
TreeNodeList.prototype.splice = function (start, deleteCount, elements) {
var _this = this;
if (elements === void 0) { elements = []; }
_super.prototype.splice.call(this, start, deleteCount, elements);
if (elements.length === 0) {
return;
}
var additionalFocus = [];
var additionalSelection = [];
elements.forEach(function (node, index) {
if (_this.focusTrait.has(node)) {
additionalFocus.push(start + index);
}
if (_this.selectionTrait.has(node)) {
additionalSelection.push(start + index);
}
});
if (additionalFocus.length > 0) {
_super.prototype.setFocus.call(this, arrays_1.distinctES6(__spreadArrays(_super.prototype.getFocus.call(this), additionalFocus)));
}
if (additionalSelection.length > 0) {
_super.prototype.setSelection.call(this, arrays_1.distinctES6(__spreadArrays(_super.prototype.getSelection.call(this), additionalSelection)));
}
};
TreeNodeList.prototype.setFocus = function (indexes, browserEvent, fromAPI) {
var _this = this;
if (fromAPI === void 0) { fromAPI = false; }
_super.prototype.setFocus.call(this, indexes, browserEvent);
if (!fromAPI) {
this.focusTrait.set(indexes.map(function (i) { return _this.element(i); }), browserEvent);
}
};
TreeNodeList.prototype.setSelection = function (indexes, browserEvent, fromAPI) {
var _this = this;
if (fromAPI === void 0) { fromAPI = false; }
_super.prototype.setSelection.call(this, indexes, browserEvent);
if (!fromAPI) {
this.selectionTrait.set(indexes.map(function (i) { return _this.element(i); }), browserEvent);
}
};
return TreeNodeList;
}(listWidget_1.List));
var AbstractTree = /** @class */ (function () {
function AbstractTree(user, container, delegate, renderers, _options) {
var _this = this;
if (_options === void 0) { _options = {}; }
this._options = _options;
this.eventBufferer = new event_1.EventBufferer();
this.disposables = new lifecycle_1.DisposableStore();
this._onWillRefilter = new event_1.Emitter();
this.onWillRefilter = this._onWillRefilter.event;
this._onDidUpdateOptions = new event_1.Emitter();
var treeDelegate = new ComposedTreeDelegate(delegate);
var onDidChangeCollapseStateRelay = new event_1.Relay();
var onDidChangeActiveNodes = new event_1.Relay();
var activeNodes = new EventCollection(onDidChangeActiveNodes.event);
this.renderers = renderers.map(function (r) { return new TreeRenderer(r, function () { return _this.model; }, onDidChangeCollapseStateRelay.event, activeNodes, _options); });
for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) {
var r = _a[_i];
this.disposables.add(r);
}
var filter;
if (_options.keyboardNavigationLabelProvider) {
filter = new TypeFilter(this, _options.keyboardNavigationLabelProvider, _options.filter);
_options = __assign(__assign({}, _options), { filter: filter }); // TODO need typescript help here
this.disposables.add(filter);
}
this.focus = new Trait(_options.identityProvider);
this.selection = new Trait(_options.identityProvider);
this.view = new TreeNodeList(user, container, treeDelegate, this.renderers, this.focus, this.selection, __assign(__assign({}, asListOptions(function () { return _this.model; }, _options)), { tree: this }));
this.model = this.createModel(user, this.view, _options);
onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState;
var onDidModelSplice = event_1.Event.forEach(this.model.onDidSplice, function (e) {
_this.eventBufferer.bufferEvents(function () {
_this.focus.onDidModelSplice(e);
_this.selection.onDidModelSplice(e);
});
});
// Make sure the `forEach` always runs
onDidModelSplice(function () { return null; }, null, this.disposables);
// Active nodes can change when the model changes or when focus or selection change.
// We debounce it with 0 delay since these events may fire in the same stack and we only
// want to run this once. It also doesn't matter if it runs on the next tick since it's only
// a nice to have UI feature.
onDidChangeActiveNodes.input = event_1.Event.chain(event_1.Event.any(onDidModelSplice, this.focus.onDidChange, this.selection.onDidChange))
.debounce(function () { return null; }, 0)
.map(function () {
var set = new Set();
for (var _i = 0, _a = _this.focus.getNodes(); _i < _a.length; _i++) {
var node = _a[_i];
set.add(node);
}
for (var _b = 0, _c = _this.selection.getNodes(); _b < _c.length; _b++) {
var node = _c[_b];
set.add(node);
}
return arrays_1.fromSet(set);
}).event;
if (_options.keyboardSupport !== false) {
var onKeyDown = event_1.Event.chain(this.view.onKeyDown)
.filter(function (e) { return !isInputElement(e.target); })
.map(function (e) { return new keyboardEvent_1.StandardKeyboardEvent(e); });
onKeyDown.filter(function (e) { return e.keyCode === 15 /* LeftArrow */; }).on(this.onLeftArrow, this, this.disposables);
onKeyDown.filter(function (e) { return e.keyCode === 17 /* RightArrow */; }).on(this.onRightArrow, this, this.disposables);
onKeyDown.filter(function (e) { return e.keyCode === 10 /* Space */; }).on(this.onSpace, this, this.disposables);
}
if (_options.keyboardNavigationLabelProvider) {
var delegate_1 = _options.keyboardNavigationDelegate || listWidget_1.DefaultKeyboardNavigationDelegate;
this.typeFilterController = new TypeFilterController(this, this.model, this.view, filter, delegate_1);
this.focusNavigationFilter = function (node) { return _this.typeFilterController.shouldAllowFocus(node); };
this.disposables.add(this.typeFilterController);
}
this.styleElement = dom_1.createStyleSheet(this.view.getHTMLElement());
dom_1.toggleClass(this.getHTMLElement(), 'always', this._options.renderIndentGuides === RenderIndentGuides.Always);
}
Object.defineProperty(AbstractTree.prototype, "onDidChangeFocus", {
get: function () { return this.eventBufferer.wrapEvent(this.focus.onDidChange); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractTree.prototype, "onDidChangeSelection", {
get: function () { return this.eventBufferer.wrapEvent(this.selection.onDidChange); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractTree.prototype, "onDidOpen", {
get: function () { return event_1.Event.map(this.view.onDidOpen, asTreeEvent); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractTree.prototype, "onDidFocus", {
get: function () { return this.view.onDidFocus; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractTree.prototype, "onDidChangeCollapseState", {
get: function () { return this.model.onDidChangeCollapseState; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractTree.prototype, "openOnSingleClick", {
get: function () { return typeof this._options.openOnSingleClick === 'undefined' ? true : this._options.openOnSingleClick; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractTree.prototype, "expandOnlyOnTwistieClick", {
get: function () { return typeof this._options.expandOnlyOnTwistieClick === 'undefined' ? false : this._options.expandOnlyOnTwistieClick; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractTree.prototype, "onDidDispose", {
get: function () { return this.view.onDidDispose; },
enumerable: true,
configurable: true
});
AbstractTree.prototype.updateOptions = function (optionsUpdate) {
if (optionsUpdate === void 0) { optionsUpdate = {}; }
this._options = __assign(__assign({}, this._options), optionsUpdate);
for (var _i = 0, _a = this.renderers; _i < _a.length; _i++) {
var renderer = _a[_i];
renderer.updateOptions(optionsUpdate);
}
this.view.updateOptions({
enableKeyboardNavigation: this._options.simpleKeyboardNavigation,
automaticKeyboardNavigation: this._options.automaticKeyboardNavigation
});
if (this.typeFilterController) {
this.typeFilterController.updateOptions(this._options);
}
this._onDidUpdateOptions.fire(this._options);
dom_1.toggleClass(this.getHTMLElement(), 'always', this._options.renderIndentGuides === RenderIndentGuides.Always);
};
Object.defineProperty(AbstractTree.prototype, "options", {
get: function () {
return this._options;
},
enumerable: true,
configurable: true
});
// Widget
AbstractTree.prototype.getHTMLElement = function () {
return this.view.getHTMLElement();
};
Object.defineProperty(AbstractTree.prototype, "scrollTop", {
get: function () {
return this.view.scrollTop;
},
set: function (scrollTop) {
this.view.scrollTop = scrollTop;
},
enumerable: true,
configurable: true
});
AbstractTree.prototype.domFocus = function () {
this.view.domFocus();
};
AbstractTree.prototype.layout = function (height, width) {
this.view.layout(height, width);
};
AbstractTree.prototype.style = function (styles) {
var suffix = "." + this.view.domId;
var content = [];
if (styles.treeIndentGuidesStroke) {
content.push(".monaco-list" + suffix + ":hover .monaco-tl-indent > .indent-guide, .monaco-list" + suffix + ".always .monaco-tl-indent > .indent-guide { border-color: " + styles.treeIndentGuidesStroke.transparent(0.4) + "; }");
content.push(".monaco-list" + suffix + " .monaco-tl-indent > .indent-guide.active { border-color: " + styles.treeIndentGuidesStroke + "; }");
}
var newStyles = content.join('\n');
if (newStyles !== this.styleElement.innerHTML) {
this.styleElement.innerHTML = newStyles;
}
this.view.style(styles);
};
AbstractTree.prototype.collapse = function (location, recursive) {
if (recursive === void 0) { recursive = false; }
return this.model.setCollapsed(location, true, recursive);
};
AbstractTree.prototype.expand = function (location, recursive) {
if (recursive === void 0) { recursive = false; }
return this.model.setCollapsed(location, false, recursive);
};
AbstractTree.prototype.isCollapsible = function (location) {
return this.model.isCollapsible(location);
};
AbstractTree.prototype.setCollapsible = function (location, collapsible) {
return this.model.setCollapsible(location, collapsible);
};
AbstractTree.prototype.isCollapsed = function (location) {
return this.model.isCollapsed(location);
};
AbstractTree.prototype.refilter = function () {
this._onWillRefilter.fire(undefined);
this.model.refilter();
};
AbstractTree.prototype.setSelection = function (elements, browserEvent) {
var _this = this;
var nodes = elements.map(function (e) { return _this.model.getNode(e); });
this.selection.set(nodes, browserEvent);
var indexes = elements.map(function (e) { return _this.model.getListIndex(e); }).filter(function (i) { return i > -1; });
this.view.setSelection(indexes, browserEvent, true);
};
AbstractTree.prototype.getSelection = function () {
return this.selection.get();
};
AbstractTree.prototype.setFocus = function (elements, browserEvent) {
var _this = this;
var nodes = elements.map(function (e) { return _this.model.getNode(e); });
this.focus.set(nodes, browserEvent);
var indexes = elements.map(function (e) { return _this.model.getListIndex(e); }).filter(function (i) { return i > -1; });
this.view.setFocus(indexes, browserEvent, true);
};
AbstractTree.prototype.focusNext = function (n, loop, browserEvent, filter) {
if (n === void 0) { n = 1; }
if (loop === void 0) { loop = false; }
if (filter === void 0) { filter = this.focusNavigationFilter; }
this.view.focusNext(n, loop, browserEvent, filter);
};
AbstractTree.prototype.getFocus = function () {
return this.focus.get();
};
AbstractTree.prototype.reveal = function (location, relativeTop) {
this.model.expandTo(location);
var index = this.model.getListIndex(location);
if (index === -1) {
return;
}
this.view.reveal(index, relativeTop);
};
/**
* Returns the relative position of an element rendered in the list.
* Returns `null` if the element isn't *entirely* in the visible viewport.
*/
AbstractTree.prototype.getRelativeTop = function (location) {
var index = this.model.getListIndex(location);
if (index === -1) {
return null;
}
return this.view.getRelativeTop(index);
};
// List
AbstractTree.prototype.onLeftArrow = function (e) {
e.preventDefault();
e.stopPropagation();
var nodes = this.view.getFocusedElements();
if (nodes.length === 0) {
return;
}
var node = nodes[0];
var location = this.model.getNodeLocation(node);
var didChange = this.model.setCollapsed(location, true);
if (!didChange) {
var parentLocation = this.model.getParentNodeLocation(location);
if (!parentLocation) {
return;
}
var parentListIndex = this.model.getListIndex(parentLocation);
this.view.reveal(parentListIndex);
this.view.setFocus([parentListIndex]);
}
};
AbstractTree.prototype.onRightArrow = function (e) {
e.preventDefault();
e.stopPropagation();
var nodes = this.view.getFocusedElements();
if (nodes.length === 0) {
return;
}
var node = nodes[0];
var location = this.model.getNodeLocation(node);
var didChange = this.model.setCollapsed(location, false);
if (!didChange) {
if (!node.children.some(function (child) { return child.visible; })) {
return;
}
var focusedIndex = this.view.getFocus()[0];
var firstChildIndex = focusedIndex + 1;
this.view.reveal(firstChildIndex);
this.view.setFocus([firstChildIndex]);
}
};
AbstractTree.prototype.onSpace = function (e) {
e.preventDefault();
e.stopPropagation();
var nodes = this.view.getFocusedElements();
if (nodes.length === 0) {
return;
}
var node = nodes[0];
var location = this.model.getNodeLocation(node);
var recursive = e.browserEvent.altKey;
this.model.setCollapsed(location, undefined, recursive);
};
AbstractTree.prototype.dispose = function () {
lifecycle_1.dispose(this.disposables);
this.view.dispose();
};
return AbstractTree;
}());
exports.AbstractTree = AbstractTree;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[407/*vs/base/browser/ui/tree/dataTree*/], __M([0/*require*/,1/*exports*/,154/*vs/base/browser/ui/tree/abstractTree*/,130/*vs/base/browser/ui/tree/objectTreeModel*/]), function (require, exports, abstractTree_1, objectTreeModel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DataTree = /** @class */ (function (_super) {
__extends(DataTree, _super);
function DataTree(user, container, delegate, renderers, dataSource, options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, user, container, delegate, renderers, options) || this;
_this.user = user;
_this.dataSource = dataSource;
_this.identityProvider = options.identityProvider;
return _this;
}
DataTree.prototype.createModel = function (user, view, options) {
return new objectTreeModel_1.ObjectTreeModel(user, view, options);
};
return DataTree;
}(abstractTree_1.AbstractTree));
exports.DataTree = DataTree;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[206/*vs/base/browser/ui/tree/objectTree*/], __M([0/*require*/,1/*exports*/,154/*vs/base/browser/ui/tree/abstractTree*/,130/*vs/base/browser/ui/tree/objectTreeModel*/,243/*vs/base/browser/ui/tree/compressedObjectTreeModel*/,101/*vs/base/common/decorators*/]), function (require, exports, abstractTree_1, objectTreeModel_1, compressedObjectTreeModel_1, decorators_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ObjectTree = /** @class */ (function (_super) {
__extends(ObjectTree, _super);
function ObjectTree(user, container, delegate, renderers, options) {
if (options === void 0) { options = {}; }
return _super.call(this, user, container, delegate, renderers, options) || this;
}
Object.defineProperty(ObjectTree.prototype, "onDidChangeCollapseState", {
get: function () { return this.model.onDidChangeCollapseState; },
enumerable: true,
configurable: true
});
ObjectTree.prototype.setChildren = function (element, children) {
this.model.setChildren(element, children);
};
ObjectTree.prototype.rerender = function (element) {
if (element === undefined) {
this.view.rerender();
return;
}
this.model.rerender(element);
};
ObjectTree.prototype.hasElement = function (element) {
return this.model.has(element);
};
ObjectTree.prototype.createModel = function (user, view, options) {
return new objectTreeModel_1.ObjectTreeModel(user, view, options);
};
return ObjectTree;
}(abstractTree_1.AbstractTree));
exports.ObjectTree = ObjectTree;
var CompressibleRenderer = /** @class */ (function () {
function CompressibleRenderer(_compressedTreeNodeProvider, renderer) {
this._compressedTreeNodeProvider = _compressedTreeNodeProvider;
this.renderer = renderer;
this.templateId = renderer.templateId;
if (renderer.onDidChangeTwistieState) {
this.onDidChangeTwistieState = renderer.onDidChangeTwistieState;
}
}
Object.defineProperty(CompressibleRenderer.prototype, "compressedTreeNodeProvider", {
get: function () {
return this._compressedTreeNodeProvider();
},
enumerable: true,
configurable: true
});
CompressibleRenderer.prototype.renderTemplate = function (container) {
var data = this.renderer.renderTemplate(container);
return { compressedTreeNode: undefined, data: data };
};
CompressibleRenderer.prototype.renderElement = function (node, index, templateData, height) {
var compressedTreeNode = this.compressedTreeNodeProvider.getCompressedTreeNode(node.element);
if (compressedTreeNode.element.elements.length === 1) {
templateData.compressedTreeNode = undefined;
this.renderer.renderElement(node, index, templateData.data, height);
}
else {
templateData.compressedTreeNode = compressedTreeNode;
this.renderer.renderCompressedElements(compressedTreeNode, index, templateData.data, height);
}
};
CompressibleRenderer.prototype.disposeElement = function (node, index, templateData, height) {
if (templateData.compressedTreeNode) {
if (this.renderer.disposeCompressedElements) {
this.renderer.disposeCompressedElements(templateData.compressedTreeNode, index, templateData.data, height);
}
}
else {
if (this.renderer.disposeElement) {
this.renderer.disposeElement(node, index, templateData.data, height);
}
}
};
CompressibleRenderer.prototype.disposeTemplate = function (templateData) {
this.renderer.disposeTemplate(templateData.data);
};
CompressibleRenderer.prototype.renderTwistie = function (element, twistieElement) {
if (this.renderer.renderTwistie) {
this.renderer.renderTwistie(element, twistieElement);
}
};
__decorate([
decorators_1.memoize
], CompressibleRenderer.prototype, "compressedTreeNodeProvider", null);
return CompressibleRenderer;
}());
function asObjectTreeOptions(compressedTreeNodeProvider, options) {
return options && __assign(__assign({}, options), { keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
getKeyboardNavigationLabel: function (e) {
var compressedTreeNode;
try {
compressedTreeNode = compressedTreeNodeProvider().getCompressedTreeNode(e);
}
catch (_a) {
return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
}
if (compressedTreeNode.element.elements.length === 1) {
return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
}
else {
return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(compressedTreeNode.element.elements);
}
}
} });
}
var CompressibleObjectTree = /** @class */ (function (_super) {
__extends(CompressibleObjectTree, _super);
function CompressibleObjectTree(user, container, delegate, renderers, options) {
if (options === void 0) { options = {}; }
var _this = this;
var compressedTreeNodeProvider = function () { return _this; };
var compressibleRenderers = renderers.map(function (r) { return new CompressibleRenderer(compressedTreeNodeProvider, r); });
_this = _super.call(this, user, container, delegate, compressibleRenderers, asObjectTreeOptions(compressedTreeNodeProvider, options)) || this;
return _this;
}
CompressibleObjectTree.prototype.setChildren = function (element, children) {
this.model.setChildren(element, children);
};
CompressibleObjectTree.prototype.createModel = function (user, view, options) {
return new compressedObjectTreeModel_1.CompressibleObjectTreeModel(user, view, options);
};
CompressibleObjectTree.prototype.updateOptions = function (optionsUpdate) {
if (optionsUpdate === void 0) { optionsUpdate = {}; }
_super.prototype.updateOptions.call(this, optionsUpdate);
if (typeof optionsUpdate.compressionEnabled !== 'undefined') {
this.model.setCompressionEnabled(optionsUpdate.compressionEnabled);
}
};
CompressibleObjectTree.prototype.getCompressedTreeNode = function (element) {
if (element === void 0) { element = null; }
return this.model.getCompressedTreeNode(element);
};
return CompressibleObjectTree;
}(ObjectTree));
exports.CompressibleObjectTree = CompressibleObjectTree;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[408/*vs/base/browser/ui/tree/asyncDataTree*/], __M([0/*require*/,1/*exports*/,154/*vs/base/browser/ui/tree/abstractTree*/,206/*vs/base/browser/ui/tree/objectTree*/,99/*vs/base/browser/ui/tree/tree*/,2/*vs/base/common/lifecycle*/,4/*vs/base/common/event*/,15/*vs/base/common/async*/,54/*vs/base/common/iterator*/,140/*vs/base/browser/ui/list/listView*/,10/*vs/base/common/errors*/,6/*vs/base/browser/dom*/,38/*vs/base/common/map*/,129/*vs/base/browser/ui/tree/indexTreeModel*/]), function (require, exports, abstractTree_1, objectTree_1, tree_1, lifecycle_1, event_1, async_1, iterator_1, listView_1, errors_1, dom_1, map_1, indexTreeModel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function createAsyncDataTreeNode(props) {
return __assign(__assign({}, props), { children: [], refreshPromise: undefined, stale: true, slow: false, collapsedByDefault: undefined });
}
function isAncestor(ancestor, descendant) {
if (!descendant.parent) {
return false;
}
else if (descendant.parent === ancestor) {
return true;
}
else {
return isAncestor(ancestor, descendant.parent);
}
}
function intersects(node, other) {
return node === other || isAncestor(node, other) || isAncestor(other, node);
}
var AsyncDataTreeNodeWrapper = /** @class */ (function () {
function AsyncDataTreeNodeWrapper(node) {
this.node = node;
}
Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "element", {
get: function () { return this.node.element.element; },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "children", {
get: function () { return this.node.children.map(function (node) { return new AsyncDataTreeNodeWrapper(node); }); },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "depth", {
get: function () { return this.node.depth; },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "visibleChildrenCount", {
get: function () { return this.node.visibleChildrenCount; },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "visibleChildIndex", {
get: function () { return this.node.visibleChildIndex; },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "collapsible", {
get: function () { return this.node.collapsible; },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "collapsed", {
get: function () { return this.node.collapsed; },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "visible", {
get: function () { return this.node.visible; },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTreeNodeWrapper.prototype, "filterData", {
get: function () { return this.node.filterData; },
enumerable: true,
configurable: true
});
return AsyncDataTreeNodeWrapper;
}());
var AsyncDataTreeRenderer = /** @class */ (function () {
function AsyncDataTreeRenderer(renderer, nodeMapper, onDidChangeTwistieState) {
this.renderer = renderer;
this.nodeMapper = nodeMapper;
this.onDidChangeTwistieState = onDidChangeTwistieState;
this.renderedNodes = new Map();
this.templateId = renderer.templateId;
}
AsyncDataTreeRenderer.prototype.renderTemplate = function (container) {
var templateData = this.renderer.renderTemplate(container);
return { templateData: templateData };
};
AsyncDataTreeRenderer.prototype.renderElement = function (node, index, templateData, height) {
this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height);
};
AsyncDataTreeRenderer.prototype.renderTwistie = function (element, twistieElement) {
dom_1.toggleClass(twistieElement, 'codicon-loading', element.slow);
return false;
};
AsyncDataTreeRenderer.prototype.disposeElement = function (node, index, templateData, height) {
if (this.renderer.disposeElement) {
this.renderer.disposeElement(this.nodeMapper.map(node), index, templateData.templateData, height);
}
};
AsyncDataTreeRenderer.prototype.disposeTemplate = function (templateData) {
this.renderer.disposeTemplate(templateData.templateData);
};
AsyncDataTreeRenderer.prototype.dispose = function () {
this.renderedNodes.clear();
};
return AsyncDataTreeRenderer;
}());
function asTreeEvent(e) {
return {
browserEvent: e.browserEvent,
elements: e.elements.map(function (e) { return e.element; })
};
}
var AsyncDataTreeElementsDragAndDropData = /** @class */ (function (_super) {
__extends(AsyncDataTreeElementsDragAndDropData, _super);
function AsyncDataTreeElementsDragAndDropData(data) {
var _this = _super.call(this, data.elements.map(function (node) { return node.element; })) || this;
_this.data = data;
return _this;
}
return AsyncDataTreeElementsDragAndDropData;
}(listView_1.ElementsDragAndDropData));
function asAsyncDataTreeDragAndDropData(data) {
if (data instanceof listView_1.ElementsDragAndDropData) {
return new AsyncDataTreeElementsDragAndDropData(data);
}
return data;
}
var AsyncDataTreeNodeListDragAndDrop = /** @class */ (function () {
function AsyncDataTreeNodeListDragAndDrop(dnd) {
this.dnd = dnd;
}
AsyncDataTreeNodeListDragAndDrop.prototype.getDragURI = function (node) {
return this.dnd.getDragURI(node.element);
};
AsyncDataTreeNodeListDragAndDrop.prototype.getDragLabel = function (nodes, originalEvent) {
if (this.dnd.getDragLabel) {
return this.dnd.getDragLabel(nodes.map(function (node) { return node.element; }), originalEvent);
}
return undefined;
};
AsyncDataTreeNodeListDragAndDrop.prototype.onDragStart = function (data, originalEvent) {
if (this.dnd.onDragStart) {
this.dnd.onDragStart(asAsyncDataTreeDragAndDropData(data), originalEvent);
}
};
AsyncDataTreeNodeListDragAndDrop.prototype.onDragOver = function (data, targetNode, targetIndex, originalEvent, raw) {
if (raw === void 0) { raw = true; }
return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
};
AsyncDataTreeNodeListDragAndDrop.prototype.drop = function (data, targetNode, targetIndex, originalEvent) {
this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
};
AsyncDataTreeNodeListDragAndDrop.prototype.onDragEnd = function (originalEvent) {
if (this.dnd.onDragEnd) {
this.dnd.onDragEnd(originalEvent);
}
};
return AsyncDataTreeNodeListDragAndDrop;
}());
function asObjectTreeOptions(options) {
return options && __assign(__assign({}, options), { collapseByDefault: true, identityProvider: options.identityProvider && {
getId: function (el) {
return options.identityProvider.getId(el.element);
}
}, dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd), multipleSelectionController: options.multipleSelectionController && {
isSelectionSingleChangeEvent: function (e) {
return options.multipleSelectionController.isSelectionSingleChangeEvent(__assign(__assign({}, e), { element: e.element }));
},
isSelectionRangeChangeEvent: function (e) {
return options.multipleSelectionController.isSelectionRangeChangeEvent(__assign(__assign({}, e), { element: e.element }));
}
}, accessibilityProvider: options.accessibilityProvider && __assign(__assign({}, options.accessibilityProvider), { getAriaLabel: function (e) {
return options.accessibilityProvider.getAriaLabel(e.element);
}, getAriaLevel: options.accessibilityProvider.getAriaLevel && (function (node) {
return options.accessibilityProvider.getAriaLevel(node.element);
}), getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (function (node) {
return options.accessibilityProvider.getActiveDescendantId(node.element);
}) }), filter: options.filter && {
filter: function (e, parentVisibility) {
return options.filter.filter(e.element, parentVisibility);
}
}, keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && __assign(__assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel: function (e) {
return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e.element);
} }), sorter: undefined, expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === 'undefined' ? undefined : (typeof options.expandOnlyOnTwistieClick !== 'function' ? options.expandOnlyOnTwistieClick : (function (e) { return options.expandOnlyOnTwistieClick(e.element); })), ariaProvider: options.ariaProvider && {
getPosInSet: function (el, index) {
return options.ariaProvider.getPosInSet(el.element, index);
},
getSetSize: function (el, index, listLength) {
return options.ariaProvider.getSetSize(el.element, index, listLength);
},
getRole: options.ariaProvider.getRole ? function (el) {
return options.ariaProvider.getRole(el.element);
} : undefined,
isChecked: options.ariaProvider.isChecked ? function (e) {
var _a;
return ((_a = options.ariaProvider) === null || _a === void 0 ? void 0 : _a.isChecked)(e.element);
} : undefined
}, additionalScrollHeight: options.additionalScrollHeight });
}
function dfs(node, fn) {
fn(node);
node.children.forEach(function (child) { return dfs(child, fn); });
}
var AsyncDataTree = /** @class */ (function () {
function AsyncDataTree(user, container, delegate, renderers, dataSource, options) {
if (options === void 0) { options = {}; }
this.user = user;
this.dataSource = dataSource;
this.nodes = new Map();
this.subTreeRefreshPromises = new Map();
this.refreshPromises = new Map();
this._onDidRender = new event_1.Emitter();
this._onDidChangeNodeSlowState = new event_1.Emitter();
this.nodeMapper = new tree_1.WeakMapper(function (node) { return new AsyncDataTreeNodeWrapper(node); });
this.disposables = new lifecycle_1.DisposableStore();
this.identityProvider = options.identityProvider;
this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren;
this.sorter = options.sorter;
this.collapseByDefault = options.collapseByDefault;
this.tree = this.createTree(user, container, delegate, renderers, options);
this.root = createAsyncDataTreeNode({
element: undefined,
parent: null,
hasChildren: true
});
if (this.identityProvider) {
this.root = __assign(__assign({}, this.root), { id: null });
}
this.nodes.set(null, this.root);
this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables);
}
Object.defineProperty(AsyncDataTree.prototype, "onDidChangeFocus", {
get: function () { return event_1.Event.map(this.tree.onDidChangeFocus, asTreeEvent); },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTree.prototype, "onDidChangeSelection", {
get: function () { return event_1.Event.map(this.tree.onDidChangeSelection, asTreeEvent); },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTree.prototype, "onDidOpen", {
get: function () { return event_1.Event.map(this.tree.onDidOpen, asTreeEvent); },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTree.prototype, "onDidFocus", {
get: function () { return this.tree.onDidFocus; },
enumerable: true,
configurable: true
});
Object.defineProperty(AsyncDataTree.prototype, "onDidDispose", {
get: function () { return this.tree.onDidDispose; },
enumerable: true,
configurable: true
});
AsyncDataTree.prototype.createTree = function (user, container, delegate, renderers, options) {
var _this = this;
var objectTreeDelegate = new abstractTree_1.ComposedTreeDelegate(delegate);
var objectTreeRenderers = renderers.map(function (r) { return new AsyncDataTreeRenderer(r, _this.nodeMapper, _this._onDidChangeNodeSlowState.event); });
var objectTreeOptions = asObjectTreeOptions(options) || {};
return new objectTree_1.ObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
};
AsyncDataTree.prototype.updateOptions = function (options) {
if (options === void 0) { options = {}; }
this.tree.updateOptions(options);
};
// Widget
AsyncDataTree.prototype.getHTMLElement = function () {
return this.tree.getHTMLElement();
};
Object.defineProperty(AsyncDataTree.prototype, "scrollTop", {
get: function () {
return this.tree.scrollTop;
},
set: function (scrollTop) {
this.tree.scrollTop = scrollTop;
},
enumerable: true,
configurable: true
});
AsyncDataTree.prototype.domFocus = function () {
this.tree.domFocus();
};
AsyncDataTree.prototype.layout = function (height, width) {
this.tree.layout(height, width);
};
AsyncDataTree.prototype.style = function (styles) {
this.tree.style(styles);
};
// Model
AsyncDataTree.prototype.getInput = function () {
return this.root.element;
};
AsyncDataTree.prototype.setInput = function (input, viewState) {
return __awaiter(this, void 0, void 0, function () {
var viewStateContext;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.refreshPromises.forEach(function (promise) { return promise.cancel(); });
this.refreshPromises.clear();
this.root.element = input;
viewStateContext = viewState && { viewState: viewState, focus: [], selection: [] };
return [4 /*yield*/, this._updateChildren(input, true, false, viewStateContext)];
case 1:
_a.sent();
if (viewStateContext) {
this.tree.setFocus(viewStateContext.focus);
this.tree.setSelection(viewStateContext.selection);
}
if (viewState && typeof viewState.scrollTop === 'number') {
this.scrollTop = viewState.scrollTop;
}
return [2 /*return*/];
}
});
});
};
AsyncDataTree.prototype._updateChildren = function (element, recursive, rerender, viewStateContext) {
if (element === void 0) { element = this.root.element; }
if (recursive === void 0) { recursive = true; }
if (rerender === void 0) { rerender = false; }
return __awaiter(this, void 0, void 0, function () {
var node;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (typeof this.root.element === 'undefined') {
throw new tree_1.TreeError(this.user, 'Tree input not set');
}
if (!this.root.refreshPromise) return [3 /*break*/, 3];
return [4 /*yield*/, this.root.refreshPromise];
case 1:
_a.sent();
return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)];
case 2:
_a.sent();
_a.label = 3;
case 3:
node = this.getDataNode(element);
return [4 /*yield*/, this.refreshAndRenderNode(node, recursive, viewStateContext)];
case 4:
_a.sent();
if (rerender) {
try {
this.tree.rerender(node);
}
catch (_b) {
// missing nodes are fine, this could've resulted from
// parallel refresh calls, removing `node` altogether
}
}
return [2 /*return*/];
}
});
});
};
// View
AsyncDataTree.prototype.rerender = function (element) {
if (element === undefined || element === this.root.element) {
this.tree.rerender();
return;
}
var node = this.getDataNode(element);
this.tree.rerender(node);
};
AsyncDataTree.prototype.collapse = function (element, recursive) {
if (recursive === void 0) { recursive = false; }
var node = this.getDataNode(element);
return this.tree.collapse(node === this.root ? null : node, recursive);
};
AsyncDataTree.prototype.expand = function (element, recursive) {
if (recursive === void 0) { recursive = false; }
return __awaiter(this, void 0, void 0, function () {
var node, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (typeof this.root.element === 'undefined') {
throw new tree_1.TreeError(this.user, 'Tree input not set');
}
if (!this.root.refreshPromise) return [3 /*break*/, 3];
return [4 /*yield*/, this.root.refreshPromise];
case 1:
_a.sent();
return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)];
case 2:
_a.sent();
_a.label = 3;
case 3:
node = this.getDataNode(element);
if (this.tree.hasElement(node) && !this.tree.isCollapsible(node)) {
return [2 /*return*/, false];
}
if (!node.refreshPromise) return [3 /*break*/, 6];
return [4 /*yield*/, this.root.refreshPromise];
case 4:
_a.sent();
return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)];
case 5:
_a.sent();
_a.label = 6;
case 6:
if (node !== this.root && !node.refreshPromise && !this.tree.isCollapsed(node)) {
return [2 /*return*/, false];
}
result = this.tree.expand(node === this.root ? null : node, recursive);
if (!node.refreshPromise) return [3 /*break*/, 9];
return [4 /*yield*/, this.root.refreshPromise];
case 7:
_a.sent();
return [4 /*yield*/, event_1.Event.toPromise(this._onDidRender.event)];
case 8:
_a.sent();
_a.label = 9;
case 9: return [2 /*return*/, result];
}
});
});
};
AsyncDataTree.prototype.setSelection = function (elements, browserEvent) {
var _this = this;
var nodes = elements.map(function (e) { return _this.getDataNode(e); });
this.tree.setSelection(nodes, browserEvent);
};
AsyncDataTree.prototype.getSelection = function () {
var nodes = this.tree.getSelection();
return nodes.map(function (n) { return n.element; });
};
AsyncDataTree.prototype.setFocus = function (elements, browserEvent) {
var _this = this;
var nodes = elements.map(function (e) { return _this.getDataNode(e); });
this.tree.setFocus(nodes, browserEvent);
};
AsyncDataTree.prototype.getFocus = function () {
var nodes = this.tree.getFocus();
return nodes.map(function (n) { return n.element; });
};
AsyncDataTree.prototype.reveal = function (element, relativeTop) {
this.tree.reveal(this.getDataNode(element), relativeTop);
};
// Implementation
AsyncDataTree.prototype.getDataNode = function (element) {
var node = this.nodes.get((element === this.root.element ? null : element));
if (!node) {
throw new tree_1.TreeError(this.user, "Data tree node not found: " + element);
}
return node;
};
AsyncDataTree.prototype.refreshAndRenderNode = function (node, recursive, viewStateContext) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.refreshNode(node, recursive, viewStateContext)];
case 1:
_a.sent();
this.render(node, viewStateContext);
return [2 /*return*/];
}
});
});
};
AsyncDataTree.prototype.refreshNode = function (node, recursive, viewStateContext) {
return __awaiter(this, void 0, void 0, function () {
var result;
var _this = this;
return __generator(this, function (_a) {
this.subTreeRefreshPromises.forEach(function (refreshPromise, refreshNode) {
if (!result && intersects(refreshNode, node)) {
result = refreshPromise.then(function () { return _this.refreshNode(node, recursive, viewStateContext); });
}
});
if (result) {
return [2 /*return*/, result];
}
return [2 /*return*/, this.doRefreshSubTree(node, recursive, viewStateContext)];
});
});
};
AsyncDataTree.prototype.doRefreshSubTree = function (node, recursive, viewStateContext) {
return __awaiter(this, void 0, void 0, function () {
var done, childrenToRefresh;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
node.refreshPromise = new Promise(function (c) { return done = c; });
this.subTreeRefreshPromises.set(node, node.refreshPromise);
node.refreshPromise.finally(function () {
node.refreshPromise = undefined;
_this.subTreeRefreshPromises.delete(node);
});
_a.label = 1;
case 1:
_a.trys.push([1, , 4, 5]);
return [4 /*yield*/, this.doRefreshNode(node, recursive, viewStateContext)];
case 2:
childrenToRefresh = _a.sent();
node.stale = false;
return [4 /*yield*/, Promise.all(childrenToRefresh.map(function (child) { return _this.doRefreshSubTree(child, recursive, viewStateContext); }))];
case 3:
_a.sent();
return [3 /*break*/, 5];
case 4:
done();
return [7 /*endfinally*/];
case 5: return [2 /*return*/];
}
});
});
};
AsyncDataTree.prototype.doRefreshNode = function (node, recursive, viewStateContext) {
return __awaiter(this, void 0, void 0, function () {
var childrenPromise, slowTimeout_1, children, err_1;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
node.hasChildren = !!this.dataSource.hasChildren(node.element);
if (!node.hasChildren) {
childrenPromise = Promise.resolve([]);
}
else {
slowTimeout_1 = async_1.timeout(800);
slowTimeout_1.then(function () {
node.slow = true;
_this._onDidChangeNodeSlowState.fire(node);
}, function (_) { return null; });
childrenPromise = this.doGetChildren(node)
.finally(function () { return slowTimeout_1.cancel(); });
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, 4, 5]);
return [4 /*yield*/, childrenPromise];
case 2:
children = _a.sent();
return [2 /*return*/, this.setChildren(node, children, recursive, viewStateContext)];
case 3:
err_1 = _a.sent();
if (node !== this.root) {
this.tree.collapse(node === this.root ? null : node);
}
if (errors_1.isPromiseCanceledError(err_1)) {
return [2 /*return*/, []];
}
throw err_1;
case 4:
if (node.slow) {
node.slow = false;
this._onDidChangeNodeSlowState.fire(node);
}
return [7 /*endfinally*/];
case 5: return [2 /*return*/];
}
});
});
};
AsyncDataTree.prototype.doGetChildren = function (node) {
var _this = this;
var result = this.refreshPromises.get(node);
if (result) {
return result;
}
result = async_1.createCancelablePromise(function () { return __awaiter(_this, void 0, void 0, function () {
var children;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.dataSource.getChildren(node.element)];
case 1:
children = _a.sent();
return [2 /*return*/, this.processChildren(children)];
}
});
}); });
this.refreshPromises.set(node, result);
return result.finally(function () { return _this.refreshPromises.delete(node); });
};
AsyncDataTree.prototype._onDidChangeCollapseState = function (_a) {
var node = _a.node, deep = _a.deep;
if (!node.collapsed && node.element.stale) {
if (deep) {
this.collapse(node.element.element);
}
else {
this.refreshAndRenderNode(node.element, false)
.catch(errors_1.onUnexpectedError);
}
}
};
AsyncDataTree.prototype.setChildren = function (node, childrenElements, recursive, viewStateContext) {
var _a;
var _this = this;
// perf: if the node was and still is a leaf, avoid all this hassle
if (node.children.length === 0 && childrenElements.length === 0) {
return [];
}
var nodesToForget = new Map();
var childrenTreeNodesById = new Map();
for (var _i = 0, _b = node.children; _i < _b.length; _i++) {
var child = _b[_i];
nodesToForget.set(child.element, child);
if (this.identityProvider) {
var collapsed = this.tree.isCollapsed(child);
childrenTreeNodesById.set(child.id, { node: child, collapsed: collapsed });
}
}
var childrenToRefresh = [];
var children = childrenElements.map(function (element) {
var hasChildren = !!_this.dataSource.hasChildren(element);
if (!_this.identityProvider) {
var asyncDataTreeNode = createAsyncDataTreeNode({ element: element, parent: node, hasChildren: hasChildren });
if (hasChildren && _this.collapseByDefault && !_this.collapseByDefault(element)) {
asyncDataTreeNode.collapsedByDefault = false;
childrenToRefresh.push(asyncDataTreeNode);
}
return asyncDataTreeNode;
}
var id = _this.identityProvider.getId(element).toString();
var result = childrenTreeNodesById.get(id);
if (result) {
var asyncDataTreeNode = result.node;
nodesToForget.delete(asyncDataTreeNode.element);
_this.nodes.delete(asyncDataTreeNode.element);
_this.nodes.set(element, asyncDataTreeNode);
asyncDataTreeNode.element = element;
asyncDataTreeNode.hasChildren = hasChildren;
if (recursive) {
if (result.collapsed) {
asyncDataTreeNode.children.forEach(function (node) { return dfs(node, function (node) { return _this.nodes.delete(node.element); }); });
asyncDataTreeNode.children.splice(0, asyncDataTreeNode.children.length);
asyncDataTreeNode.stale = true;
}
else {
childrenToRefresh.push(asyncDataTreeNode);
}
}
else if (hasChildren && _this.collapseByDefault && !_this.collapseByDefault(element)) {
asyncDataTreeNode.collapsedByDefault = false;
childrenToRefresh.push(asyncDataTreeNode);
}
return asyncDataTreeNode;
}
var childAsyncDataTreeNode = createAsyncDataTreeNode({ element: element, parent: node, id: id, hasChildren: hasChildren });
if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id) > -1) {
viewStateContext.focus.push(childAsyncDataTreeNode);
}
if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id) > -1) {
viewStateContext.selection.push(childAsyncDataTreeNode);
}
if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id) > -1) {
childrenToRefresh.push(childAsyncDataTreeNode);
}
else if (hasChildren && _this.collapseByDefault && !_this.collapseByDefault(element)) {
childAsyncDataTreeNode.collapsedByDefault = false;
childrenToRefresh.push(childAsyncDataTreeNode);
}
return childAsyncDataTreeNode;
});
for (var _c = 0, _d = map_1.values(nodesToForget); _c < _d.length; _c++) {
var node_1 = _d[_c];
dfs(node_1, function (node) { return _this.nodes.delete(node.element); });
}
for (var _e = 0, children_1 = children; _e < children_1.length; _e++) {
var child = children_1[_e];
this.nodes.set(child.element, child);
}
(_a = node.children).splice.apply(_a, __spreadArrays([0, node.children.length], children));
// TODO@joao this doesn't take filter into account
if (node !== this.root && this.autoExpandSingleChildren && children.length === 1 && childrenToRefresh.length === 0) {
children[0].collapsedByDefault = false;
childrenToRefresh.push(children[0]);
}
return childrenToRefresh;
};
AsyncDataTree.prototype.render = function (node, viewStateContext) {
var _this = this;
var children = node.children.map(function (node) { return _this.asTreeElement(node, viewStateContext); });
this.tree.setChildren(node === this.root ? null : node, children);
if (node !== this.root) {
this.tree.setCollapsible(node, node.hasChildren);
}
this._onDidRender.fire();
};
AsyncDataTree.prototype.asTreeElement = function (node, viewStateContext) {
var _this = this;
if (node.stale) {
return {
element: node,
collapsible: node.hasChildren,
collapsed: true
};
}
var collapsed;
if (viewStateContext && viewStateContext.viewState.expanded && node.id && viewStateContext.viewState.expanded.indexOf(node.id) > -1) {
collapsed = false;
}
else {
collapsed = node.collapsedByDefault;
}
node.collapsedByDefault = undefined;
return {
element: node,
children: node.hasChildren ? iterator_1.Iterator.map(iterator_1.Iterator.fromArray(node.children), function (child) { return _this.asTreeElement(child, viewStateContext); }) : [],
collapsible: node.hasChildren,
collapsed: collapsed
};
};
AsyncDataTree.prototype.processChildren = function (children) {
if (this.sorter) {
children.sort(this.sorter.compare.bind(this.sorter));
}
return children;
};
AsyncDataTree.prototype.dispose = function () {
this.disposables.dispose();
};
return AsyncDataTree;
}());
exports.AsyncDataTree = AsyncDataTree;
var CompressibleAsyncDataTreeNodeWrapper = /** @class */ (function () {
function CompressibleAsyncDataTreeNodeWrapper(node) {
this.node = node;
}
Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "element", {
get: function () {
return {
elements: this.node.element.elements.map(function (e) { return e.element; }),
incompressible: this.node.element.incompressible
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "children", {
get: function () { return this.node.children.map(function (node) { return new CompressibleAsyncDataTreeNodeWrapper(node); }); },
enumerable: true,
configurable: true
});
Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "depth", {
get: function () { return this.node.depth; },
enumerable: true,
configurable: true
});
Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "visibleChildrenCount", {
get: function () { return this.node.visibleChildrenCount; },
enumerable: true,
configurable: true
});
Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "visibleChildIndex", {
get: function () { return this.node.visibleChildIndex; },
enumerable: true,
configurable: true
});
Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "collapsible", {
get: function () { return this.node.collapsible; },
enumerable: true,
configurable: true
});
Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "collapsed", {
get: function () { return this.node.collapsed; },
enumerable: true,
configurable: true
});
Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "visible", {
get: function () { return this.node.visible; },
enumerable: true,
configurable: true
});
Object.defineProperty(CompressibleAsyncDataTreeNodeWrapper.prototype, "filterData", {
get: function () { return this.node.filterData; },
enumerable: true,
configurable: true
});
return CompressibleAsyncDataTreeNodeWrapper;
}());
var CompressibleAsyncDataTreeRenderer = /** @class */ (function () {
function CompressibleAsyncDataTreeRenderer(renderer, nodeMapper, compressibleNodeMapperProvider, onDidChangeTwistieState) {
this.renderer = renderer;
this.nodeMapper = nodeMapper;
this.compressibleNodeMapperProvider = compressibleNodeMapperProvider;
this.onDidChangeTwistieState = onDidChangeTwistieState;
this.renderedNodes = new Map();
this.disposables = [];
this.templateId = renderer.templateId;
}
CompressibleAsyncDataTreeRenderer.prototype.renderTemplate = function (container) {
var templateData = this.renderer.renderTemplate(container);
return { templateData: templateData };
};
CompressibleAsyncDataTreeRenderer.prototype.renderElement = function (node, index, templateData, height) {
this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height);
};
CompressibleAsyncDataTreeRenderer.prototype.renderCompressedElements = function (node, index, templateData, height) {
this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height);
};
CompressibleAsyncDataTreeRenderer.prototype.renderTwistie = function (element, twistieElement) {
dom_1.toggleClass(twistieElement, 'codicon-loading', element.slow);
return false;
};
CompressibleAsyncDataTreeRenderer.prototype.disposeElement = function (node, index, templateData, height) {
if (this.renderer.disposeElement) {
this.renderer.disposeElement(this.nodeMapper.map(node), index, templateData.templateData, height);
}
};
CompressibleAsyncDataTreeRenderer.prototype.disposeCompressedElements = function (node, index, templateData, height) {
if (this.renderer.disposeCompressedElements) {
this.renderer.disposeCompressedElements(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height);
}
};
CompressibleAsyncDataTreeRenderer.prototype.disposeTemplate = function (templateData) {
this.renderer.disposeTemplate(templateData.templateData);
};
CompressibleAsyncDataTreeRenderer.prototype.dispose = function () {
this.renderedNodes.clear();
this.disposables = lifecycle_1.dispose(this.disposables);
};
return CompressibleAsyncDataTreeRenderer;
}());
function asCompressibleObjectTreeOptions(options) {
var objectTreeOptions = options && asObjectTreeOptions(options);
return objectTreeOptions && __assign(__assign({}, objectTreeOptions), { keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && __assign(__assign({}, objectTreeOptions.keyboardNavigationLabelProvider), { getCompressedNodeKeyboardNavigationLabel: function (els) {
return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(els.map(function (e) { return e.element; }));
} }) });
}
var CompressibleAsyncDataTree = /** @class */ (function (_super) {
__extends(CompressibleAsyncDataTree, _super);
function CompressibleAsyncDataTree(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, user, container, virtualDelegate, renderers, dataSource, options) || this;
_this.compressionDelegate = compressionDelegate;
_this.compressibleNodeMapper = new tree_1.WeakMapper(function (node) { return new CompressibleAsyncDataTreeNodeWrapper(node); });
_this.filter = options.filter;
return _this;
}
CompressibleAsyncDataTree.prototype.createTree = function (user, container, delegate, renderers, options) {
var _this = this;
var objectTreeDelegate = new abstractTree_1.ComposedTreeDelegate(delegate);
var objectTreeRenderers = renderers.map(function (r) { return new CompressibleAsyncDataTreeRenderer(r, _this.nodeMapper, function () { return _this.compressibleNodeMapper; }, _this._onDidChangeNodeSlowState.event); });
var objectTreeOptions = asCompressibleObjectTreeOptions(options) || {};
return new objectTree_1.CompressibleObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
};
CompressibleAsyncDataTree.prototype.asTreeElement = function (node, viewStateContext) {
return __assign({ incompressible: this.compressionDelegate.isIncompressible(node.element) }, _super.prototype.asTreeElement.call(this, node, viewStateContext));
};
CompressibleAsyncDataTree.prototype.updateOptions = function (options) {
if (options === void 0) { options = {}; }
this.tree.updateOptions(options);
};
CompressibleAsyncDataTree.prototype.render = function (node, viewStateContext) {
var _this = this;
if (!this.identityProvider) {
return _super.prototype.render.call(this, node, viewStateContext);
}
// Preserve traits across compressions. Hacky but does the trick.
// This is hard to fix properly since it requires rewriting the traits
// across trees and lists. Let's just keep it this way for now.
var getId = function (element) { return _this.identityProvider.getId(element).toString(); };
var getUncompressedIds = function (nodes) {
var result = new Set();
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
var node_2 = nodes_1[_i];
var compressedNode = _this.tree.getCompressedTreeNode(node_2 === _this.root ? null : node_2);
if (!compressedNode.element) {
continue;
}
for (var _a = 0, _b = compressedNode.element.elements; _a < _b.length; _a++) {
var node_3 = _b[_a];
result.add(getId(node_3.element));
}
}
return result;
};
var oldSelection = getUncompressedIds(this.tree.getSelection());
var oldFocus = getUncompressedIds(this.tree.getFocus());
_super.prototype.render.call(this, node, viewStateContext);
var selection = this.getSelection();
var didChangeSelection = false;
var focus = this.getFocus();
var didChangeFocus = false;
var visit = function (node) {
var compressedNode = node.element;
if (compressedNode) {
for (var i = 0; i < compressedNode.elements.length; i++) {
var id = getId(compressedNode.elements[i].element);
var element = compressedNode.elements[compressedNode.elements.length - 1].element;
// github.com/microsoft/vscode/issues/85938
if (oldSelection.has(id) && selection.indexOf(element) === -1) {
selection.push(element);
didChangeSelection = true;
}
if (oldFocus.has(id) && focus.indexOf(element) === -1) {
focus.push(element);
didChangeFocus = true;
}
}
}
node.children.forEach(visit);
};
visit(this.tree.getCompressedTreeNode(node === this.root ? null : node));
if (didChangeSelection) {
this.setSelection(selection);
}
if (didChangeFocus) {
this.setFocus(focus);
}
};
// For compressed async data trees, `TreeVisibility.Recurse` doesn't currently work
// and we have to filter everything beforehand
// Related to #85193 and #85835
CompressibleAsyncDataTree.prototype.processChildren = function (children) {
var _this = this;
if (this.filter) {
children = children.filter(function (e) {
var result = _this.filter.filter(e, 1 /* Visible */);
var visibility = getVisibility(result);
if (visibility === 2 /* Recurse */) {
throw new Error('Recursive tree visibility not supported in async data compressed trees');
}
return visibility === 1 /* Visible */;
});
}
return _super.prototype.processChildren.call(this, children);
};
return CompressibleAsyncDataTree;
}(AsyncDataTree));
exports.CompressibleAsyncDataTree = CompressibleAsyncDataTree;
function getVisibility(filterResult) {
if (typeof filterResult === 'boolean') {
return filterResult ? 1 /* Visible */ : 0 /* Hidden */;
}
else if (indexTreeModel_1.isFilterResult(filterResult)) {
return indexTreeModel_1.getVisibleState(filterResult.visibility);
}
else {
return indexTreeModel_1.getVisibleState(filterResult);
}
}
});
define(__m[409/*vs/nls!vs/base/common/keybindingLabels*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/common/keybindingLabels", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[207/*vs/base/common/keybindingLabels*/], __M([0/*require*/,1/*exports*/,409/*vs/nls!vs/base/common/keybindingLabels*/]), function (require, exports, nls) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ModifierLabelProvider = /** @class */ (function () {
function ModifierLabelProvider(mac, windows, linux) {
if (linux === void 0) { linux = windows; }
this.modifierLabels = [null]; // index 0 will never me accessed.
this.modifierLabels[2 /* Macintosh */] = mac;
this.modifierLabels[1 /* Windows */] = windows;
this.modifierLabels[3 /* Linux */] = linux;
}
ModifierLabelProvider.prototype.toLabel = function (OS, parts, keyLabelProvider) {
if (parts.length === 0) {
return null;
}
var result = [];
for (var i = 0, len = parts.length; i < len; i++) {
var part = parts[i];
var keyLabel = keyLabelProvider(part);
if (keyLabel === null) {
// this keybinding cannot be expressed...
return null;
}
result[i] = _simpleAsString(part, keyLabel, this.modifierLabels[OS]);
}
return result.join(' ');
};
return ModifierLabelProvider;
}());
exports.ModifierLabelProvider = ModifierLabelProvider;
/**
* A label provider that prints modifiers in a suitable format for displaying in the UI.
*/
exports.UILabelProvider = new ModifierLabelProvider({
ctrlKey: '⌃',
shiftKey: '⇧',
altKey: '⌥',
metaKey: '⌘',
separator: '',
}, {
ctrlKey: nls.localize(0, null),
shiftKey: nls.localize(1, null),
altKey: nls.localize(2, null),
metaKey: nls.localize(3, null),
separator: '+',
}, {
ctrlKey: nls.localize(4, null),
shiftKey: nls.localize(5, null),
altKey: nls.localize(6, null),
metaKey: nls.localize(7, null),
separator: '+',
});
/**
* A label provider that prints modifiers in a suitable format for ARIA.
*/
exports.AriaLabelProvider = new ModifierLabelProvider({
ctrlKey: nls.localize(8, null),
shiftKey: nls.localize(9, null),
altKey: nls.localize(10, null),
metaKey: nls.localize(11, null),
separator: '+',
}, {
ctrlKey: nls.localize(12, null),
shiftKey: nls.localize(13, null),
altKey: nls.localize(14, null),
metaKey: nls.localize(15, null),
separator: '+',
}, {
ctrlKey: nls.localize(16, null),
shiftKey: nls.localize(17, null),
altKey: nls.localize(18, null),
metaKey: nls.localize(19, null),
separator: '+',
});
function _simpleAsString(modifiers, key, labels) {
if (key === null) {
return '';
}
var result = [];
// translate modifier keys: Ctrl-Shift-Alt-Meta
if (modifiers.ctrlKey) {
result.push(labels.ctrlKey);
}
if (modifiers.shiftKey) {
result.push(labels.shiftKey);
}
if (modifiers.altKey) {
result.push(labels.altKey);
}
if (modifiers.metaKey) {
result.push(labels.metaKey);
}
// the actual key
result.push(key);
return result.join(labels.separator);
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[410/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([0/*require*/,1/*exports*/,31/*vs/base/common/objects*/,207/*vs/base/common/keybindingLabels*/,6/*vs/base/browser/dom*/,402/*vs/nls!vs/base/browser/ui/keybindingLabel/keybindingLabel*/,270/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/]), function (require, exports, objects_1, keybindingLabels_1, dom, nls_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var $ = dom.$;
var KeybindingLabel = /** @class */ (function () {
function KeybindingLabel(container, os, options) {
this.os = os;
this.options = options;
this.domNode = dom.append(container, $('.monaco-keybinding'));
this.didEverRender = false;
container.appendChild(this.domNode);
}
KeybindingLabel.prototype.set = function (keybinding, matches) {
if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches)) {
return;
}
this.keybinding = keybinding;
this.matches = matches;
this.render();
};
KeybindingLabel.prototype.render = function () {
dom.clearNode(this.domNode);
if (this.keybinding) {
var _a = this.keybinding.getParts(), firstPart = _a[0], chordPart = _a[1];
if (firstPart) {
this.renderPart(this.domNode, firstPart, this.matches ? this.matches.firstPart : null);
}
if (chordPart) {
dom.append(this.domNode, $('span.monaco-keybinding-key-chord-separator', undefined, ' '));
this.renderPart(this.domNode, chordPart, this.matches ? this.matches.chordPart : null);
}
this.domNode.title = this.keybinding.getAriaLabel() || '';
}
else if (this.options && this.options.renderUnboundKeybindings) {
this.renderUnbound(this.domNode);
}
this.didEverRender = true;
};
KeybindingLabel.prototype.renderPart = function (parent, part, match) {
var modifierLabels = keybindingLabels_1.UILabelProvider.modifierLabels[this.os];
if (part.ctrlKey) {
this.renderKey(parent, modifierLabels.ctrlKey, Boolean(match === null || match === void 0 ? void 0 : match.ctrlKey), modifierLabels.separator);
}
if (part.shiftKey) {
this.renderKey(parent, modifierLabels.shiftKey, Boolean(match === null || match === void 0 ? void 0 : match.shiftKey), modifierLabels.separator);
}
if (part.altKey) {
this.renderKey(parent, modifierLabels.altKey, Boolean(match === null || match === void 0 ? void 0 : match.altKey), modifierLabels.separator);
}
if (part.metaKey) {
this.renderKey(parent, modifierLabels.metaKey, Boolean(match === null || match === void 0 ? void 0 : match.metaKey), modifierLabels.separator);
}
var keyLabel = part.keyLabel;
if (keyLabel) {
this.renderKey(parent, keyLabel, Boolean(match === null || match === void 0 ? void 0 : match.keyCode), '');
}
};
KeybindingLabel.prototype.renderKey = function (parent, label, highlight, separator) {
dom.append(parent, $('span.monaco-keybinding-key' + (highlight ? '.highlight' : ''), undefined, label));
if (separator) {
dom.append(parent, $('span.monaco-keybinding-key-separator', undefined, separator));
}
};
KeybindingLabel.prototype.renderUnbound = function (parent) {
dom.append(parent, $('span.monaco-keybinding-key', undefined, nls_1.localize(0, null)));
};
KeybindingLabel.areSame = function (a, b) {
if (a === b || (!a && !b)) {
return true;
}
return !!a && !!b && objects_1.equals(a.firstPart, b.firstPart) && objects_1.equals(a.chordPart, b.chordPart);
};
return KeybindingLabel;
}());
exports.KeybindingLabel = KeybindingLabel;
});
define(__m[411/*vs/nls!vs/base/common/severity*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/common/severity", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[112/*vs/base/common/severity*/], __M([0/*require*/,1/*exports*/,411/*vs/nls!vs/base/common/severity*/,5/*vs/base/common/strings*/]), function (require, exports, nls, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Severity;
(function (Severity) {
Severity[Severity["Ignore"] = 0] = "Ignore";
Severity[Severity["Info"] = 1] = "Info";
Severity[Severity["Warning"] = 2] = "Warning";
Severity[Severity["Error"] = 3] = "Error";
})(Severity || (Severity = {}));
(function (Severity) {
var _error = 'error';
var _warning = 'warning';
var _warn = 'warn';
var _info = 'info';
var _displayStrings = Object.create(null);
_displayStrings[Severity.Error] = nls.localize(0, null);
_displayStrings[Severity.Warning] = nls.localize(1, null);
_displayStrings[Severity.Info] = nls.localize(2, null);
/**
* Parses 'error', 'warning', 'warn', 'info' in call casings
* and falls back to ignore.
*/
function fromValue(value) {
if (!value) {
return Severity.Ignore;
}
if (strings.equalsIgnoreCase(_error, value)) {
return Severity.Error;
}
if (strings.equalsIgnoreCase(_warning, value) || strings.equalsIgnoreCase(_warn, value)) {
return Severity.Warning;
}
if (strings.equalsIgnoreCase(_info, value)) {
return Severity.Info;
}
return Severity.Ignore;
}
Severity.fromValue = fromValue;
})(Severity || (Severity = {}));
exports.default = Severity;
});
define(__m[412/*vs/nls!vs/base/parts/quickopen/browser/quickOpenModel*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/quickopen/browser/quickOpenModel", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[155/*vs/base/parts/quickopen/browser/quickOpenModel*/], __M([0/*require*/,1/*exports*/,412/*vs/nls!vs/base/parts/quickopen/browser/quickOpenModel*/,21/*vs/base/common/types*/,139/*vs/base/browser/ui/iconLabel/iconLabel*/,70/*vs/base/browser/ui/actionbar/actionbar*/,133/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,6/*vs/base/browser/dom*/,410/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,16/*vs/base/common/platform*/,19/*vs/base/common/arrays*/]), function (require, exports, nls, types, iconLabel_1, actionbar_1, highlightedLabel_1, DOM, keybindingLabel_1, platform_1, arrays_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var IDS = 0;
var QuickOpenEntry = /** @class */ (function () {
function QuickOpenEntry(highlights) {
if (highlights === void 0) { highlights = []; }
this.id = (IDS++).toString();
this.labelHighlights = highlights;
this.descriptionHighlights = [];
}
/**
* A unique identifier for the entry
*/
QuickOpenEntry.prototype.getId = function () {
return this.id;
};
/**
* The label of the entry to identify it from others in the list
*/
QuickOpenEntry.prototype.getLabel = function () {
return undefined;
};
/**
* The options for the label to use for this entry
*/
QuickOpenEntry.prototype.getLabelOptions = function () {
return undefined;
};
/**
* The label of the entry to use when a screen reader wants to read about the entry
*/
QuickOpenEntry.prototype.getAriaLabel = function () {
return arrays_1.coalesce([this.getLabel(), this.getDescription(), this.getDetail()])
.join(', ');
};
/**
* Detail information about the entry that is optional and can be shown below the label
*/
QuickOpenEntry.prototype.getDetail = function () {
return undefined;
};
/**
* The icon of the entry to identify it from others in the list
*/
QuickOpenEntry.prototype.getIcon = function () {
return undefined;
};
/**
* A secondary description that is optional and can be shown right to the label
*/
QuickOpenEntry.prototype.getDescription = function () {
return undefined;
};
/**
* A tooltip to show when hovering over the entry.
*/
QuickOpenEntry.prototype.getTooltip = function () {
return undefined;
};
/**
* A tooltip to show when hovering over the description portion of the entry.
*/
QuickOpenEntry.prototype.getDescriptionTooltip = function () {
return undefined;
};
/**
* An optional keybinding to show for an entry.
*/
QuickOpenEntry.prototype.getKeybinding = function () {
return undefined;
};
/**
* Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer.
*/
QuickOpenEntry.prototype.isHidden = function () {
return !!this.hidden;
};
/**
* Allows to set highlight ranges that should show up for the entry label and optionally description if set.
*/
QuickOpenEntry.prototype.setHighlights = function (labelHighlights, descriptionHighlights, detailHighlights) {
this.labelHighlights = labelHighlights;
this.descriptionHighlights = descriptionHighlights;
this.detailHighlights = detailHighlights;
};
/**
* Allows to return highlight ranges that should show up for the entry label and description.
*/
QuickOpenEntry.prototype.getHighlights = function () {
return [this.labelHighlights, this.descriptionHighlights, this.detailHighlights];
};
/**
* Called when the entry is selected for opening. Returns a boolean value indicating if an action was performed or not.
* The mode parameter gives an indication if the element is previewed (using arrow keys) or opened.
*
* The context parameter provides additional context information how the run was triggered.
*/
QuickOpenEntry.prototype.run = function (mode, context) {
return false;
};
return QuickOpenEntry;
}());
exports.QuickOpenEntry = QuickOpenEntry;
var QuickOpenEntryGroup = /** @class */ (function (_super) {
__extends(QuickOpenEntryGroup, _super);
function QuickOpenEntryGroup(entry, groupLabel, withBorder) {
var _this = _super.call(this) || this;
_this.entry = entry;
_this.groupLabel = groupLabel;
_this.withBorder = withBorder;
return _this;
}
/**
* The label of the group or null if none.
*/
QuickOpenEntryGroup.prototype.getGroupLabel = function () {
return this.groupLabel;
};
QuickOpenEntryGroup.prototype.setGroupLabel = function (groupLabel) {
this.groupLabel = groupLabel;
};
/**
* Whether to show a border on top of the group entry or not.
*/
QuickOpenEntryGroup.prototype.showBorder = function () {
return !!this.withBorder;
};
QuickOpenEntryGroup.prototype.setShowBorder = function (showBorder) {
this.withBorder = showBorder;
};
QuickOpenEntryGroup.prototype.getLabel = function () {
return this.entry ? this.entry.getLabel() : _super.prototype.getLabel.call(this);
};
QuickOpenEntryGroup.prototype.getLabelOptions = function () {
return this.entry ? this.entry.getLabelOptions() : _super.prototype.getLabelOptions.call(this);
};
QuickOpenEntryGroup.prototype.getAriaLabel = function () {
return this.entry ? this.entry.getAriaLabel() : _super.prototype.getAriaLabel.call(this);
};
QuickOpenEntryGroup.prototype.getDetail = function () {
return this.entry ? this.entry.getDetail() : _super.prototype.getDetail.call(this);
};
QuickOpenEntryGroup.prototype.getIcon = function () {
return this.entry ? this.entry.getIcon() : _super.prototype.getIcon.call(this);
};
QuickOpenEntryGroup.prototype.getDescription = function () {
return this.entry ? this.entry.getDescription() : _super.prototype.getDescription.call(this);
};
QuickOpenEntryGroup.prototype.getHighlights = function () {
return this.entry ? this.entry.getHighlights() : _super.prototype.getHighlights.call(this);
};
QuickOpenEntryGroup.prototype.isHidden = function () {
return this.entry ? this.entry.isHidden() : _super.prototype.isHidden.call(this);
};
QuickOpenEntryGroup.prototype.setHighlights = function (labelHighlights, descriptionHighlights, detailHighlights) {
this.entry ? this.entry.setHighlights(labelHighlights, descriptionHighlights, detailHighlights) : _super.prototype.setHighlights.call(this, labelHighlights, descriptionHighlights, detailHighlights);
};
QuickOpenEntryGroup.prototype.run = function (mode, context) {
return this.entry ? this.entry.run(mode, context) : _super.prototype.run.call(this, mode, context);
};
return QuickOpenEntryGroup;
}(QuickOpenEntry));
exports.QuickOpenEntryGroup = QuickOpenEntryGroup;
var NoActionProvider = /** @class */ (function () {
function NoActionProvider() {
}
NoActionProvider.prototype.hasActions = function (tree, element) {
return false;
};
NoActionProvider.prototype.getActions = function (tree, element) {
return null;
};
return NoActionProvider;
}());
var templateEntry = 'quickOpenEntry';
var templateEntryGroup = 'quickOpenEntryGroup';
var Renderer = /** @class */ (function () {
function Renderer(actionProvider, actionRunner) {
if (actionProvider === void 0) { actionProvider = new NoActionProvider(); }
this.actionProvider = actionProvider;
this.actionRunner = actionRunner;
}
Renderer.prototype.getHeight = function (entry) {
if (entry.getDetail()) {
return 44;
}
return 22;
};
Renderer.prototype.getTemplateId = function (entry) {
if (entry instanceof QuickOpenEntryGroup) {
return templateEntryGroup;
}
return templateEntry;
};
Renderer.prototype.renderTemplate = function (templateId, container, styles) {
var entryContainer = document.createElement('div');
DOM.addClass(entryContainer, 'sub-content');
container.appendChild(entryContainer);
// Entry
var row1 = DOM.$('.quick-open-row');
var row2 = DOM.$('.quick-open-row');
var entry = DOM.$('.quick-open-entry', undefined, row1, row2);
entryContainer.appendChild(entry);
// Icon
var icon = document.createElement('span');
row1.appendChild(icon);
// Label
var label = new iconLabel_1.IconLabel(row1, { supportHighlights: true, supportDescriptionHighlights: true, supportCodicons: true });
// Keybinding
var keybindingContainer = document.createElement('span');
row1.appendChild(keybindingContainer);
DOM.addClass(keybindingContainer, 'quick-open-entry-keybinding');
var keybinding = new keybindingLabel_1.KeybindingLabel(keybindingContainer, platform_1.OS);
// Detail
var detailContainer = document.createElement('div');
row2.appendChild(detailContainer);
DOM.addClass(detailContainer, 'quick-open-entry-meta');
var detail = new highlightedLabel_1.HighlightedLabel(detailContainer, true);
// Entry Group
var group;
if (templateId === templateEntryGroup) {
group = document.createElement('div');
DOM.addClass(group, 'results-group');
container.appendChild(group);
}
// Actions
DOM.addClass(container, 'actions');
var actionBarContainer = document.createElement('div');
DOM.addClass(actionBarContainer, 'primary-action-bar');
container.appendChild(actionBarContainer);
var actionBar = new actionbar_1.ActionBar(actionBarContainer, {
actionRunner: this.actionRunner
});
return {
container: container,
entry: entry,
icon: icon,
label: label,
detail: detail,
keybinding: keybinding,
group: group,
actionBar: actionBar
};
};
Renderer.prototype.renderElement = function (entry, templateId, data, styles) {
// Action Bar
if (this.actionProvider.hasActions(null, entry)) {
DOM.addClass(data.container, 'has-actions');
}
else {
DOM.removeClass(data.container, 'has-actions');
}
data.actionBar.context = entry; // make sure the context is the current element
var actions = this.actionProvider.getActions(null, entry);
if (data.actionBar.isEmpty() && actions && actions.length > 0) {
data.actionBar.push(actions, { icon: true, label: false });
}
else if (!data.actionBar.isEmpty() && (!actions || actions.length === 0)) {
data.actionBar.clear();
}
// Entry group class
if (entry instanceof QuickOpenEntryGroup && entry.getGroupLabel()) {
DOM.addClass(data.container, 'has-group-label');
}
else {
DOM.removeClass(data.container, 'has-group-label');
}
// Entry group
if (entry instanceof QuickOpenEntryGroup) {
var group = entry;
var groupData = data;
// Border
if (group.showBorder()) {
DOM.addClass(groupData.container, 'results-group-separator');
if (styles.pickerGroupBorder) {
groupData.container.style.borderTopColor = styles.pickerGroupBorder.toString();
}
}
else {
DOM.removeClass(groupData.container, 'results-group-separator');
groupData.container.style.borderTopColor = '';
}
// Group Label
var groupLabel = group.getGroupLabel() || '';
if (groupData.group) {
groupData.group.textContent = groupLabel;
if (styles.pickerGroupForeground) {
groupData.group.style.color = styles.pickerGroupForeground.toString();
}
}
}
// Normal Entry
if (entry instanceof QuickOpenEntry) {
var _a = entry.getHighlights(), labelHighlights = _a[0], descriptionHighlights = _a[1], detailHighlights = _a[2];
// Icon
var iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : '';
data.icon.className = iconClass;
// Label
var options = entry.getLabelOptions() || Object.create(null);
options.matches = labelHighlights || [];
options.title = entry.getTooltip();
options.descriptionTitle = entry.getDescriptionTooltip() || entry.getDescription(); // tooltip over description because it could overflow
options.descriptionMatches = descriptionHighlights || [];
data.label.setLabel(entry.getLabel() || '', entry.getDescription(), options);
// Meta
data.detail.set(entry.getDetail(), detailHighlights);
// Keybinding
data.keybinding.set(entry.getKeybinding());
}
};
Renderer.prototype.disposeTemplate = function (templateId, templateData) {
templateData.actionBar.dispose();
templateData.actionBar = null;
templateData.container = null;
templateData.entry = null;
templateData.keybinding = null;
templateData.detail = null;
templateData.group = null;
templateData.icon = null;
templateData.label.dispose();
templateData.label = null;
};
return Renderer;
}());
var QuickOpenModel = /** @class */ (function () {
function QuickOpenModel(entries, actionProvider) {
if (entries === void 0) { entries = []; }
if (actionProvider === void 0) { actionProvider = new NoActionProvider(); }
this._entries = entries;
this._dataSource = this;
this._renderer = new Renderer(actionProvider);
this._filter = this;
this._runner = this;
this._accessibilityProvider = this;
}
Object.defineProperty(QuickOpenModel.prototype, "entries", {
get: function () { return this._entries; },
set: function (entries) {
this._entries = entries;
},
enumerable: true,
configurable: true
});
Object.defineProperty(QuickOpenModel.prototype, "dataSource", {
get: function () { return this._dataSource; },
enumerable: true,
configurable: true
});
Object.defineProperty(QuickOpenModel.prototype, "renderer", {
get: function () { return this._renderer; },
enumerable: true,
configurable: true
});
Object.defineProperty(QuickOpenModel.prototype, "filter", {
get: function () { return this._filter; },
enumerable: true,
configurable: true
});
Object.defineProperty(QuickOpenModel.prototype, "runner", {
get: function () { return this._runner; },
enumerable: true,
configurable: true
});
Object.defineProperty(QuickOpenModel.prototype, "accessibilityProvider", {
get: function () { return this._accessibilityProvider; },
enumerable: true,
configurable: true
});
QuickOpenModel.prototype.getId = function (entry) {
return entry.getId();
};
QuickOpenModel.prototype.getLabel = function (entry) {
return types.withUndefinedAsNull(entry.getLabel());
};
QuickOpenModel.prototype.getAriaLabel = function (entry) {
var ariaLabel = entry.getAriaLabel();
if (ariaLabel) {
return nls.localize(0, null, entry.getAriaLabel());
}
return nls.localize(1, null);
};
QuickOpenModel.prototype.isVisible = function (entry) {
return !entry.isHidden();
};
QuickOpenModel.prototype.run = function (entry, mode, context) {
return entry.run(mode, context);
};
return QuickOpenModel;
}());
exports.QuickOpenModel = QuickOpenModel;
});
define(__m[413/*vs/nls!vs/base/parts/quickopen/browser/quickOpenWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/base/parts/quickopen/browser/quickOpenWidget", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[414/*vs/base/parts/quickopen/browser/quickOpenWidget*/], __M([0/*require*/,1/*exports*/,413/*vs/nls!vs/base/parts/quickopen/browser/quickOpenWidget*/,16/*vs/base/common/platform*/,21/*vs/base/common/types*/,253/*vs/base/parts/quickopen/browser/quickOpenViewer*/,152/*vs/base/browser/ui/inputbox/inputBox*/,283/*vs/base/parts/tree/browser/treeImpl*/,274/*vs/base/browser/ui/progressbar/progressbar*/,56/*vs/base/browser/keyboardEvent*/,137/*vs/base/parts/tree/browser/treeDefaults*/,6/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,27/*vs/base/common/color*/,31/*vs/base/common/objects*/,45/*vs/base/browser/mouseEvent*/,281/*vs/css!vs/base/parts/quickopen/browser/quickopen*/]), function (require, exports, nls, platform, types, quickOpenViewer_1, inputBox_1, treeImpl_1, progressbar_1, keyboardEvent_1, treeDefaults_1, DOM, lifecycle_1, color_1, objects_1, mouseEvent_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var QuickOpenController = /** @class */ (function (_super) {
__extends(QuickOpenController, _super);
function QuickOpenController() {
return _super !== null && _super.apply(this, arguments) || this;
}
QuickOpenController.prototype.onContextMenu = function (tree, element, event) {
if (platform.isMacintosh) {
return this.onLeftClick(tree, element, event); // https://github.com/Microsoft/vscode/issues/1011
}
return _super.prototype.onContextMenu.call(this, tree, element, event);
};
return QuickOpenController;
}(treeDefaults_1.DefaultController));
exports.QuickOpenController = QuickOpenController;
var defaultStyles = {
background: color_1.Color.fromHex('#1E1E1E'),
foreground: color_1.Color.fromHex('#CCCCCC'),
pickerGroupForeground: color_1.Color.fromHex('#0097FB'),
pickerGroupBorder: color_1.Color.fromHex('#3F3F46'),
widgetShadow: color_1.Color.fromHex('#000000'),
progressBarBackground: color_1.Color.fromHex('#0E70C0')
};
var DEFAULT_INPUT_ARIA_LABEL = nls.localize(0, null);
var QuickOpenWidget = /** @class */ (function (_super) {
__extends(QuickOpenWidget, _super);
function QuickOpenWidget(container, callbacks, options) {
var _this = _super.call(this) || this;
_this.isDisposed = false;
_this.container = container;
_this.callbacks = callbacks;
_this.options = options;
_this.styles = options || Object.create(null);
objects_1.mixin(_this.styles, defaultStyles, false);
_this.model = null;
return _this;
}
QuickOpenWidget.prototype.getModel = function () {
return this.model;
};
QuickOpenWidget.prototype.create = function () {
var _this = this;
// Container
this.element = document.createElement('div');
DOM.addClass(this.element, 'monaco-quick-open-widget');
this.container.appendChild(this.element);
this._register(DOM.addDisposableListener(this.element, DOM.EventType.CONTEXT_MENU, function (e) { return DOM.EventHelper.stop(e, true); })); // Do this to fix an issue on Mac where the menu goes into the way
this._register(DOM.addDisposableListener(this.element, DOM.EventType.FOCUS, function (e) { return _this.gainingFocus(); }, true));
this._register(DOM.addDisposableListener(this.element, DOM.EventType.BLUR, function (e) { return _this.loosingFocus(e); }, true));
this._register(DOM.addDisposableListener(this.element, DOM.EventType.KEY_DOWN, function (e) {
var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
if (keyboardEvent.keyCode === 9 /* Escape */) {
DOM.EventHelper.stop(e, true);
_this.hide(2 /* CANCELED */);
}
else if (keyboardEvent.keyCode === 2 /* Tab */ && !keyboardEvent.altKey && !keyboardEvent.ctrlKey && !keyboardEvent.metaKey) {
var stops = e.currentTarget.querySelectorAll('input, .monaco-tree, .monaco-tree-row.focused .action-label.icon');
if (keyboardEvent.shiftKey && keyboardEvent.target === stops[0]) {
DOM.EventHelper.stop(e, true);
stops[stops.length - 1].focus();
}
else if (!keyboardEvent.shiftKey && keyboardEvent.target === stops[stops.length - 1]) {
DOM.EventHelper.stop(e, true);
stops[0].focus();
}
}
}));
// Progress Bar
this.progressBar = this._register(new progressbar_1.ProgressBar(this.element, { progressBarBackground: this.styles.progressBarBackground }));
this.progressBar.hide();
// Input Field
this.inputContainer = document.createElement('div');
DOM.addClass(this.inputContainer, 'quick-open-input');
this.element.appendChild(this.inputContainer);
this.inputBox = this._register(new inputBox_1.InputBox(this.inputContainer, undefined, {
placeholder: this.options.inputPlaceHolder || '',
ariaLabel: DEFAULT_INPUT_ARIA_LABEL,
inputBackground: this.styles.inputBackground,
inputForeground: this.styles.inputForeground,
inputBorder: this.styles.inputBorder,
inputValidationInfoBackground: this.styles.inputValidationInfoBackground,
inputValidationInfoForeground: this.styles.inputValidationInfoForeground,
inputValidationInfoBorder: this.styles.inputValidationInfoBorder,
inputValidationWarningBackground: this.styles.inputValidationWarningBackground,
inputValidationWarningForeground: this.styles.inputValidationWarningForeground,
inputValidationWarningBorder: this.styles.inputValidationWarningBorder,
inputValidationErrorBackground: this.styles.inputValidationErrorBackground,
inputValidationErrorForeground: this.styles.inputValidationErrorForeground,
inputValidationErrorBorder: this.styles.inputValidationErrorBorder
}));
this.inputElement = this.inputBox.inputElement;
this.inputElement.setAttribute('role', 'combobox');
this.inputElement.setAttribute('aria-haspopup', 'false');
this.inputElement.setAttribute('aria-autocomplete', 'list');
this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, function (e) { return _this.onType(); }));
this._register(DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, function (e) {
var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
var shouldOpenInBackground = _this.shouldOpenInBackground(keyboardEvent);
// Do not handle Tab: It is used to navigate between elements without mouse
if (keyboardEvent.keyCode === 2 /* Tab */) {
return;
}
// Pass tree navigation keys to the tree but leave focus in input field
else if (keyboardEvent.keyCode === 18 /* DownArrow */ || keyboardEvent.keyCode === 16 /* UpArrow */ || keyboardEvent.keyCode === 12 /* PageDown */ || keyboardEvent.keyCode === 11 /* PageUp */) {
DOM.EventHelper.stop(e, true);
_this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey);
// Position cursor at the end of input to allow right arrow (open in background)
// to function immediately unless the user has made a selection
if (_this.inputBox.inputElement.selectionStart === _this.inputBox.inputElement.selectionEnd) {
_this.inputBox.inputElement.selectionStart = _this.inputBox.value.length;
}
}
// Select element on Enter or on Arrow-Right if we are at the end of the input
else if (keyboardEvent.keyCode === 3 /* Enter */ || shouldOpenInBackground) {
DOM.EventHelper.stop(e, true);
var focus_1 = _this.tree.getFocus();
if (focus_1) {
_this.elementSelected(focus_1, e, shouldOpenInBackground ? 2 /* OPEN_IN_BACKGROUND */ : 1 /* OPEN */);
}
}
}));
// Result count for screen readers
this.resultCount = document.createElement('div');
DOM.addClass(this.resultCount, 'quick-open-result-count');
this.resultCount.setAttribute('aria-live', 'polite');
this.resultCount.setAttribute('aria-atomic', 'true');
this.element.appendChild(this.resultCount);
// Tree
this.treeContainer = document.createElement('div');
DOM.addClass(this.treeContainer, 'quick-open-tree');
this.element.appendChild(this.treeContainer);
var createTree = this.options.treeCreator || (function (container, config, opts) { return new treeImpl_1.Tree(container, config, opts); });
this.tree = this._register(createTree(this.treeContainer, {
dataSource: new quickOpenViewer_1.DataSource(this),
controller: new QuickOpenController({ clickBehavior: 1 /* ON_MOUSE_UP */, keyboardSupport: this.options.keyboardSupport }),
renderer: (this.renderer = new quickOpenViewer_1.Renderer(this, this.styles)),
filter: new quickOpenViewer_1.Filter(this),
accessibilityProvider: new quickOpenViewer_1.AccessibilityProvider(this)
}, {
twistiePixels: 11,
indentPixels: 0,
alwaysFocused: true,
verticalScrollMode: 3 /* Visible */,
horizontalScrollMode: 2 /* Hidden */,
ariaLabel: nls.localize(1, null),
keyboardSupport: this.options.keyboardSupport,
preventRootFocus: false
}));
this.treeElement = this.tree.getHTMLElement();
// Handle Focus and Selection event
this._register(this.tree.onDidChangeFocus(function (event) {
_this.elementFocused(event.focus, event);
}));
this._register(this.tree.onDidChangeSelection(function (event) {
if (event.selection && event.selection.length > 0) {
var mouseEvent = event.payload && event.payload.originalEvent instanceof mouseEvent_1.StandardMouseEvent ? event.payload.originalEvent : undefined;
var shouldOpenInBackground = mouseEvent ? _this.shouldOpenInBackground(mouseEvent) : false;
_this.elementSelected(event.selection[0], event, shouldOpenInBackground ? 2 /* OPEN_IN_BACKGROUND */ : 1 /* OPEN */);
}
}));
this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, function (e) {
var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
// Only handle when in quick navigation mode
if (!_this.quickNavigateConfiguration) {
return;
}
// Support keyboard navigation in quick navigation mode
if (keyboardEvent.keyCode === 18 /* DownArrow */ || keyboardEvent.keyCode === 16 /* UpArrow */ || keyboardEvent.keyCode === 12 /* PageDown */ || keyboardEvent.keyCode === 11 /* PageUp */) {
DOM.EventHelper.stop(e, true);
_this.navigateInTree(keyboardEvent.keyCode);
}
// Support to open item with Enter still even in quick nav mode
else if (keyboardEvent.keyCode === 3 /* Enter */) {
DOM.EventHelper.stop(e, true);
var focus_2 = _this.tree.getFocus();
if (focus_2) {
_this.elementSelected(focus_2, e);
}
}
}));
this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_UP, function (e) {
var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
var keyCode = keyboardEvent.keyCode;
// Only handle when in quick navigation mode
if (!_this.quickNavigateConfiguration) {
return;
}
// Select element when keys are pressed that signal it
var quickNavKeys = _this.quickNavigateConfiguration.keybindings;
var wasTriggerKeyPressed = quickNavKeys.some(function (k) {
var _a = k.getParts(), firstPart = _a[0], chordPart = _a[1];
if (chordPart) {
return false;
}
if (firstPart.shiftKey && keyCode === 4 /* Shift */) {
if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) {
return false; // this is an optimistic check for the shift key being used to navigate back in quick open
}
return true;
}
if (firstPart.altKey && keyCode === 6 /* Alt */) {
return true;
}
if (firstPart.ctrlKey && keyCode === 5 /* Ctrl */) {
return true;
}
if (firstPart.metaKey && keyCode === 57 /* Meta */) {
return true;
}
return false;
});
if (wasTriggerKeyPressed) {
var focus_3 = _this.tree.getFocus();
if (focus_3) {
_this.elementSelected(focus_3, e);
}
}
}));
// Support layout
if (this.layoutDimensions) {
this.layout(this.layoutDimensions);
}
this.applyStyles();
// Allows focus to switch to next/previous entry after tab into an actionbar item
this._register(DOM.addDisposableListener(this.treeContainer, DOM.EventType.KEY_DOWN, function (e) {
var keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
// Only handle when not in quick navigation mode
if (_this.quickNavigateConfiguration) {
return;
}
if (keyboardEvent.keyCode === 18 /* DownArrow */ || keyboardEvent.keyCode === 16 /* UpArrow */ || keyboardEvent.keyCode === 12 /* PageDown */ || keyboardEvent.keyCode === 11 /* PageUp */) {
DOM.EventHelper.stop(e, true);
_this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey);
_this.treeElement.focus();
}
}));
return this.element;
};
QuickOpenWidget.prototype.style = function (styles) {
this.styles = styles;
this.applyStyles();
};
QuickOpenWidget.prototype.applyStyles = function () {
if (this.element) {
var foreground = this.styles.foreground ? this.styles.foreground.toString() : '';
var background = this.styles.background ? this.styles.background.toString() : '';
var borderColor = this.styles.borderColor ? this.styles.borderColor.toString() : '';
var widgetShadow = this.styles.widgetShadow ? this.styles.widgetShadow.toString() : '';
this.element.style.color = foreground;
this.element.style.backgroundColor = background;
this.element.style.borderColor = borderColor;
this.element.style.borderWidth = borderColor ? '1px' : '';
this.element.style.borderStyle = borderColor ? 'solid' : '';
this.element.style.boxShadow = widgetShadow ? "0 5px 8px " + widgetShadow : '';
}
if (this.progressBar) {
this.progressBar.style({
progressBarBackground: this.styles.progressBarBackground
});
}
if (this.inputBox) {
this.inputBox.style({
inputBackground: this.styles.inputBackground,
inputForeground: this.styles.inputForeground,
inputBorder: this.styles.inputBorder,
inputValidationInfoBackground: this.styles.inputValidationInfoBackground,
inputValidationInfoForeground: this.styles.inputValidationInfoForeground,
inputValidationInfoBorder: this.styles.inputValidationInfoBorder,
inputValidationWarningBackground: this.styles.inputValidationWarningBackground,
inputValidationWarningForeground: this.styles.inputValidationWarningForeground,
inputValidationWarningBorder: this.styles.inputValidationWarningBorder,
inputValidationErrorBackground: this.styles.inputValidationErrorBackground,
inputValidationErrorForeground: this.styles.inputValidationErrorForeground,
inputValidationErrorBorder: this.styles.inputValidationErrorBorder
});
}
if (this.tree && !this.options.treeCreator) {
this.tree.style(this.styles);
}
if (this.renderer) {
this.renderer.updateStyles(this.styles);
}
};
QuickOpenWidget.prototype.shouldOpenInBackground = function (e) {
// Keyboard
if (e instanceof keyboardEvent_1.StandardKeyboardEvent) {
if (e.keyCode !== 17 /* RightArrow */) {
return false; // only for right arrow
}
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
return false; // no modifiers allowed
}
// validate the cursor is at the end of the input and there is no selection,
// and if not prevent opening in the background such as the selection can be changed
var element = this.inputBox.inputElement;
return element.selectionEnd === this.inputBox.value.length && element.selectionStart === element.selectionEnd;
}
// Mouse
return e.middleButton;
};
QuickOpenWidget.prototype.onType = function () {
var value = this.inputBox.value;
// Adjust help text as needed if present
if (this.helpText) {
if (value) {
DOM.hide(this.helpText);
}
else {
DOM.show(this.helpText);
}
}
// Send to callbacks
this.callbacks.onType(value);
};
QuickOpenWidget.prototype.navigateInTree = function (keyCode, isShift) {
var model = this.tree.getInput();
var entries = model ? model.entries : [];
var oldFocus = this.tree.getFocus();
// Normal Navigation
switch (keyCode) {
case 18 /* DownArrow */:
this.tree.focusNext();
break;
case 16 /* UpArrow */:
this.tree.focusPrevious();
break;
case 12 /* PageDown */:
this.tree.focusNextPage();
break;
case 11 /* PageUp */:
this.tree.focusPreviousPage();
break;
case 2 /* Tab */:
if (isShift) {
this.tree.focusPrevious();
}
else {
this.tree.focusNext();
}
break;
}
var newFocus = this.tree.getFocus();
// Support cycle-through navigation if focus did not change
if (entries.length > 1 && oldFocus === newFocus) {
// Up from no entry or first entry goes down to last
if (keyCode === 16 /* UpArrow */ || (keyCode === 2 /* Tab */ && isShift)) {
this.tree.focusLast();
}
// Down from last entry goes to up to first
else if (keyCode === 18 /* DownArrow */ || keyCode === 2 /* Tab */ && !isShift) {
this.tree.focusFirst();
}
}
// Reveal
newFocus = this.tree.getFocus();
if (newFocus) {
this.tree.reveal(newFocus);
}
};
QuickOpenWidget.prototype.elementFocused = function (value, event) {
if (!value || !this.isVisible()) {
return;
}
// ARIA
var arivaActiveDescendant = this.treeElement.getAttribute('aria-activedescendant');
if (arivaActiveDescendant) {
this.inputElement.setAttribute('aria-activedescendant', arivaActiveDescendant);
}
else {
this.inputElement.removeAttribute('aria-activedescendant');
}
var context = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration };
this.model.runner.run(value, 0 /* PREVIEW */, context);
};
QuickOpenWidget.prototype.elementSelected = function (value, event, preferredMode) {
var hide = true;
// Trigger open of element on selection
if (this.isVisible()) {
var mode = preferredMode || 1 /* OPEN */;
var context = { event: event, keymods: this.extractKeyMods(event), quickNavigateConfiguration: this.quickNavigateConfiguration };
hide = this.model.runner.run(value, mode, context);
}
// Hide if command was run successfully
if (hide) {
this.hide(0 /* ELEMENT_SELECTED */);
}
};
QuickOpenWidget.prototype.extractKeyMods = function (event) {
return {
ctrlCmd: event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey))),
alt: event && (event.altKey || (event.payload && event.payload.originalEvent && event.payload.originalEvent.altKey))
};
};
QuickOpenWidget.prototype.show = function (param, options) {
this.visible = true;
this.isLoosingFocus = false;
this.quickNavigateConfiguration = options ? options.quickNavigateConfiguration : undefined;
// Adjust UI for quick navigate mode
if (this.quickNavigateConfiguration) {
DOM.hide(this.inputContainer);
DOM.show(this.element);
this.tree.domFocus();
}
// Otherwise use normal UI
else {
DOM.show(this.inputContainer);
DOM.show(this.element);
this.inputBox.focus();
}
// Adjust Help text for IE
if (this.helpText) {
if (this.quickNavigateConfiguration || types.isString(param)) {
DOM.hide(this.helpText);
}
else {
DOM.show(this.helpText);
}
}
// Show based on param
if (types.isString(param)) {
this.doShowWithPrefix(param);
}
else {
if (options && options.value) {
this.restoreLastInput(options.value);
}
this.doShowWithInput(param, options && options.autoFocus ? options.autoFocus : {});
}
// Respect selectAll option
if (options && options.inputSelection && !this.quickNavigateConfiguration) {
this.inputBox.select(options.inputSelection);
}
if (this.callbacks.onShow) {
this.callbacks.onShow();
}
};
QuickOpenWidget.prototype.restoreLastInput = function (lastInput) {
this.inputBox.value = lastInput;
this.inputBox.select();
this.callbacks.onType(lastInput);
};
QuickOpenWidget.prototype.doShowWithPrefix = function (prefix) {
this.inputBox.value = prefix;
this.callbacks.onType(prefix);
};
QuickOpenWidget.prototype.doShowWithInput = function (input, autoFocus) {
this.setInput(input, autoFocus);
};
QuickOpenWidget.prototype.setInputAndLayout = function (input, autoFocus) {
var _this = this;
this.treeContainer.style.height = this.getHeight(input) + "px";
this.tree.setInput(null).then(function () {
_this.model = input;
// ARIA
_this.inputElement.setAttribute('aria-haspopup', String(input && input.entries && input.entries.length > 0));
return _this.tree.setInput(input);
}).then(function () {
// Indicate entries to tree
_this.tree.layout();
var entries = input ? input.entries.filter(function (e) { return _this.isElementVisible(input, e); }) : [];
_this.updateResultCount(entries.length);
// Handle auto focus
if (entries.length) {
_this.autoFocus(input, entries, autoFocus);
}
});
};
QuickOpenWidget.prototype.isElementVisible = function (input, e) {
if (!input.filter) {
return true;
}
return input.filter.isVisible(e);
};
QuickOpenWidget.prototype.autoFocus = function (input, entries, autoFocus) {
if (autoFocus === void 0) { autoFocus = {}; }
// First check for auto focus of prefix matches
if (autoFocus.autoFocusPrefixMatch) {
var caseSensitiveMatch = void 0;
var caseInsensitiveMatch = void 0;
var prefix = autoFocus.autoFocusPrefixMatch;
var lowerCasePrefix = prefix.toLowerCase();
for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
var entry = entries_1[_i];
var label = input.dataSource.getLabel(entry) || '';
if (!caseSensitiveMatch && label.indexOf(prefix) === 0) {
caseSensitiveMatch = entry;
}
else if (!caseInsensitiveMatch && label.toLowerCase().indexOf(lowerCasePrefix) === 0) {
caseInsensitiveMatch = entry;
}
if (caseSensitiveMatch && caseInsensitiveMatch) {
break;
}
}
var entryToFocus = caseSensitiveMatch || caseInsensitiveMatch;
if (entryToFocus) {
this.tree.setFocus(entryToFocus);
this.tree.reveal(entryToFocus, 0.5);
return;
}
}
// Second check for auto focus of first entry
if (autoFocus.autoFocusFirstEntry) {
this.tree.focusFirst();
this.tree.reveal(this.tree.getFocus());
}
// Third check for specific index option
else if (typeof autoFocus.autoFocusIndex === 'number') {
if (entries.length > autoFocus.autoFocusIndex) {
this.tree.focusNth(autoFocus.autoFocusIndex);
this.tree.reveal(this.tree.getFocus());
}
}
// Check for auto focus of second entry
else if (autoFocus.autoFocusSecondEntry) {
if (entries.length > 1) {
this.tree.focusNth(1);
}
}
// Finally check for auto focus of last entry
else if (autoFocus.autoFocusLastEntry) {
if (entries.length > 1) {
this.tree.focusLast();
this.tree.reveal(this.tree.getFocus());
}
}
};
QuickOpenWidget.prototype.getHeight = function (input) {
var _this = this;
var renderer = input.renderer;
if (!input) {
var itemHeight = renderer.getHeight(null);
return this.options.minItemsToShow ? this.options.minItemsToShow * itemHeight : 0;
}
var height = 0;
var preferredItemsHeight;
if (this.layoutDimensions && this.layoutDimensions.height) {
preferredItemsHeight = (this.layoutDimensions.height - 50 /* subtract height of input field (30px) and some spacing (drop shadow) to fit */) * 0.4 /* max 40% of screen */;
}
if (!preferredItemsHeight || preferredItemsHeight > QuickOpenWidget.MAX_ITEMS_HEIGHT) {
preferredItemsHeight = QuickOpenWidget.MAX_ITEMS_HEIGHT;
}
var entries = input.entries.filter(function (e) { return _this.isElementVisible(input, e); });
var maxEntries = this.options.maxItemsToShow || entries.length;
for (var i = 0; i < maxEntries && i < entries.length; i++) {
var entryHeight = renderer.getHeight(entries[i]);
if (height + entryHeight <= preferredItemsHeight) {
height += entryHeight;
}
else {
break;
}
}
return height;
};
QuickOpenWidget.prototype.updateResultCount = function (count) {
this.resultCount.textContent = nls.localize(2, null, count);
};
QuickOpenWidget.prototype.hide = function (reason) {
if (!this.isVisible()) {
return;
}
this.visible = false;
DOM.hide(this.element);
this.element.blur();
// Clear input field and clear tree
this.inputBox.value = '';
this.tree.setInput(null);
// ARIA
this.inputElement.setAttribute('aria-haspopup', 'false');
// Reset Tree Height
this.treeContainer.style.height = (this.options.minItemsToShow ? this.options.minItemsToShow * 22 : 0) + "px";
// Clear any running Progress
this.progressBar.stop().hide();
// Clear Focus
if (this.tree.isDOMFocused()) {
this.tree.domBlur();
}
else if (this.inputBox.hasFocus()) {
this.inputBox.blur();
}
// Callbacks
if (reason === 0 /* ELEMENT_SELECTED */) {
this.callbacks.onOk();
}
else {
this.callbacks.onCancel();
}
if (this.callbacks.onHide) {
this.callbacks.onHide(reason);
}
};
QuickOpenWidget.prototype.setInput = function (input, autoFocus, ariaLabel) {
if (!this.isVisible()) {
return;
}
// If the input changes, indicate this to the tree
if (!!this.getInput()) {
this.onInputChanging();
}
// Adapt tree height to entries and apply input
this.setInputAndLayout(input, autoFocus);
// Apply ARIA
if (this.inputBox) {
this.inputBox.setAriaLabel(ariaLabel || DEFAULT_INPUT_ARIA_LABEL);
}
};
QuickOpenWidget.prototype.onInputChanging = function () {
var _this = this;
if (this.inputChangingTimeoutHandle) {
clearTimeout(this.inputChangingTimeoutHandle);
this.inputChangingTimeoutHandle = null;
}
// when the input is changing in quick open, we indicate this as CSS class to the widget
// for a certain timeout. this helps reducing some hectic UI updates when input changes quickly
DOM.addClass(this.element, 'content-changing');
this.inputChangingTimeoutHandle = setTimeout(function () {
DOM.removeClass(_this.element, 'content-changing');
}, 500);
};
QuickOpenWidget.prototype.getInput = function () {
return this.tree.getInput();
};
QuickOpenWidget.prototype.isVisible = function () {
return this.visible;
};
QuickOpenWidget.prototype.layout = function (dimension) {
this.layoutDimensions = dimension;
// Apply to quick open width (height is dynamic by number of items to show)
var quickOpenWidth = Math.min(this.layoutDimensions.width * 0.62 /* golden cut */, QuickOpenWidget.MAX_WIDTH);
if (this.element) {
// quick open
this.element.style.width = quickOpenWidth + "px";
this.element.style.marginLeft = "-" + quickOpenWidth / 2 + "px";
// input field
this.inputContainer.style.width = quickOpenWidth - 12 + "px";
}
};
QuickOpenWidget.prototype.gainingFocus = function () {
this.isLoosingFocus = false;
};
QuickOpenWidget.prototype.loosingFocus = function (e) {
var _this = this;
if (!this.isVisible()) {
return;
}
var relatedTarget = e.relatedTarget;
if (!this.quickNavigateConfiguration && DOM.isAncestor(relatedTarget, this.element)) {
return; // user clicked somewhere into quick open widget, do not close thereby
}
this.isLoosingFocus = true;
setTimeout(function () {
if (!_this.isLoosingFocus || _this.isDisposed) {
return;
}
var veto = _this.callbacks.onFocusLost && _this.callbacks.onFocusLost();
if (!veto) {
_this.hide(1 /* FOCUS_LOST */);
}
}, 0);
};
QuickOpenWidget.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.isDisposed = true;
};
QuickOpenWidget.MAX_WIDTH = 600; // Max total width of quick open widget
QuickOpenWidget.MAX_ITEMS_HEIGHT = 20 * 22; // Max height of item list below input field
return QuickOpenWidget;
}(lifecycle_1.Disposable));
exports.QuickOpenWidget = QuickOpenWidget;
});
define(__m[415/*vs/nls!vs/editor/browser/controller/coreCommands*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/coreCommands", data); });
define(__m[416/*vs/nls!vs/editor/browser/controller/textAreaHandler*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/controller/textAreaHandler", data); });
define(__m[417/*vs/nls!vs/editor/browser/widget/codeEditorWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/codeEditorWidget", data); });
define(__m[418/*vs/nls!vs/editor/browser/widget/diffEditorWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffEditorWidget", data); });
define(__m[419/*vs/nls!vs/editor/browser/widget/diffReview*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/diffReview", data); });
define(__m[420/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/browser/widget/inlineDiffMargin", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[421/*vs/editor/browser/widget/inlineDiffMargin*/], __M([0/*require*/,1/*exports*/,420/*vs/nls!vs/editor/browser/widget/inlineDiffMargin*/,6/*vs/base/browser/dom*/,55/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,3/*vs/editor/common/core/range*/]), function (require, exports, nls, dom, actions_1, lifecycle_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var InlineDiffMargin = /** @class */ (function (_super) {
__extends(InlineDiffMargin, _super);
function InlineDiffMargin(_viewZoneId, _marginDomNode, editor, diff, _contextMenuService, _clipboardService) {
var _this = _super.call(this) || this;
_this._viewZoneId = _viewZoneId;
_this._marginDomNode = _marginDomNode;
_this.editor = editor;
_this.diff = diff;
_this._contextMenuService = _contextMenuService;
_this._clipboardService = _clipboardService;
_this._visibility = false;
// make sure the diff margin shows above overlay.
_this._marginDomNode.style.zIndex = '10';
_this._diffActions = document.createElement('div');
_this._diffActions.className = 'codicon codicon-lightbulb lightbulb-glyph';
_this._diffActions.style.position = 'absolute';
var lineHeight = editor.getOption(49 /* lineHeight */);
var lineFeed = editor.getModel().getEOL();
_this._diffActions.style.right = '0px';
_this._diffActions.style.visibility = 'hidden';
_this._diffActions.style.height = lineHeight + "px";
_this._diffActions.style.lineHeight = lineHeight + "px";
_this._marginDomNode.appendChild(_this._diffActions);
var actions = [];
// default action
actions.push(new actions_1.Action('diff.clipboard.copyDeletedContent', diff.originalEndLineNumber > diff.modifiedStartLineNumber
? nls.localize(0, null)
: nls.localize(1, null), undefined, true, function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._clipboardService.writeText(diff.originalContent.join(lineFeed) + lineFeed)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); }));
var currentLineNumberOffset = 0;
var copyLineAction = undefined;
if (diff.originalEndLineNumber > diff.modifiedStartLineNumber) {
copyLineAction = new actions_1.Action('diff.clipboard.copyDeletedLineContent', nls.localize(2, null, diff.originalStartLineNumber), undefined, true, function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._clipboardService.writeText(diff.originalContent[currentLineNumberOffset])];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); });
actions.push(copyLineAction);
}
var readOnly = editor.getOption(68 /* readOnly */);
if (!readOnly) {
actions.push(new actions_1.Action('diff.inline.revertChange', nls.localize(3, null), undefined, true, function () { return __awaiter(_this, void 0, void 0, function () {
var column, column;
return __generator(this, function (_a) {
if (diff.modifiedEndLineNumber === 0) {
column = editor.getModel().getLineMaxColumn(diff.modifiedStartLineNumber);
editor.executeEdits('diffEditor', [
{
range: new range_1.Range(diff.modifiedStartLineNumber, column, diff.modifiedStartLineNumber, column),
text: lineFeed + diff.originalContent.join(lineFeed)
}
]);
}
else {
column = editor.getModel().getLineMaxColumn(diff.modifiedEndLineNumber);
editor.executeEdits('diffEditor', [
{
range: new range_1.Range(diff.modifiedStartLineNumber, 1, diff.modifiedEndLineNumber, column),
text: diff.originalContent.join(lineFeed)
}
]);
}
return [2 /*return*/];
});
}); }));
}
var showContextMenu = function (x, y) {
_this._contextMenuService.showContextMenu({
getAnchor: function () {
return {
x: x,
y: y
};
},
getActions: function () {
if (copyLineAction) {
copyLineAction.label = nls.localize(4, null, diff.originalStartLineNumber + currentLineNumberOffset);
}
return actions;
},
autoSelectFirstItem: true
});
};
_this._register(dom.addStandardDisposableListener(_this._diffActions, 'mousedown', function (e) {
var _a = dom.getDomNodePagePosition(_this._diffActions), top = _a.top, height = _a.height;
var pad = Math.floor(lineHeight / 3);
e.preventDefault();
showContextMenu(e.posx, top + height + pad);
}));
_this._register(editor.onMouseMove(function (e) {
if (e.target.type === 8 /* CONTENT_VIEW_ZONE */ || e.target.type === 5 /* GUTTER_VIEW_ZONE */) {
var viewZoneId = e.target.detail.viewZoneId;
if (viewZoneId === _this._viewZoneId) {
_this.visibility = true;
currentLineNumberOffset = _this._updateLightBulbPosition(_this._marginDomNode, e.event.browserEvent.y, lineHeight);
}
else {
_this.visibility = false;
}
}
else {
_this.visibility = false;
}
}));
_this._register(editor.onMouseDown(function (e) {
if (!e.event.rightButton) {
return;
}
if (e.target.type === 8 /* CONTENT_VIEW_ZONE */ || e.target.type === 5 /* GUTTER_VIEW_ZONE */) {
var viewZoneId = e.target.detail.viewZoneId;
if (viewZoneId === _this._viewZoneId) {
e.event.preventDefault();
currentLineNumberOffset = _this._updateLightBulbPosition(_this._marginDomNode, e.event.browserEvent.y, lineHeight);
showContextMenu(e.event.posx, e.event.posy + lineHeight);
}
}
}));
return _this;
}
Object.defineProperty(InlineDiffMargin.prototype, "visibility", {
get: function () {
return this._visibility;
},
set: function (_visibility) {
if (this._visibility !== _visibility) {
this._visibility = _visibility;
if (_visibility) {
this._diffActions.style.visibility = 'visible';
}
else {
this._diffActions.style.visibility = 'hidden';
}
}
},
enumerable: true,
configurable: true
});
InlineDiffMargin.prototype._updateLightBulbPosition = function (marginDomNode, y, lineHeight) {
var top = dom.getDomNodePagePosition(marginDomNode).top;
var offset = y - top;
var lineNumberOffset = Math.floor(offset / lineHeight);
var newTop = lineNumberOffset * lineHeight;
this._diffActions.style.top = newTop + "px";
return lineNumberOffset;
};
return InlineDiffMargin;
}(lifecycle_1.Disposable));
exports.InlineDiffMargin = InlineDiffMargin;
});
define(__m[422/*vs/nls!vs/editor/common/config/commonEditorConfig*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/config/commonEditorConfig", data); });
define(__m[423/*vs/nls!vs/editor/common/config/editorOptions*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/config/editorOptions", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[33/*vs/editor/common/config/editorOptions*/], __M([0/*require*/,1/*exports*/,423/*vs/nls!vs/editor/common/config/editorOptions*/,16/*vs/base/common/platform*/,109/*vs/editor/common/model/wordHelper*/]), function (require, exports, nls, platform, wordHelper_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @internal
* The width of the minimap gutter, in pixels.
*/
exports.MINIMAP_GUTTER_WIDTH = 8;
//#endregion
/**
* An event describing that the configuration of the editor has changed.
*/
var ConfigurationChangedEvent = /** @class */ (function () {
/**
* @internal
*/
function ConfigurationChangedEvent(values) {
this._values = values;
}
ConfigurationChangedEvent.prototype.hasChanged = function (id) {
return this._values[id];
};
return ConfigurationChangedEvent;
}());
exports.ConfigurationChangedEvent = ConfigurationChangedEvent;
/**
* @internal
*/
var ValidatedEditorOptions = /** @class */ (function () {
function ValidatedEditorOptions() {
this._values = [];
}
ValidatedEditorOptions.prototype._read = function (option) {
return this._values[option];
};
ValidatedEditorOptions.prototype.get = function (id) {
return this._values[id];
};
ValidatedEditorOptions.prototype._write = function (option, value) {
this._values[option] = value;
};
return ValidatedEditorOptions;
}());
exports.ValidatedEditorOptions = ValidatedEditorOptions;
/**
* @internal
*/
var BaseEditorOption = /** @class */ (function () {
function BaseEditorOption(id, name, defaultValue, schema) {
this.id = id;
this.name = name;
this.defaultValue = defaultValue;
this.schema = schema;
}
BaseEditorOption.prototype.compute = function (env, options, value) {
return value;
};
return BaseEditorOption;
}());
/**
* @internal
*/
var ComputedEditorOption = /** @class */ (function () {
function ComputedEditorOption(id, deps) {
if (deps === void 0) { deps = null; }
this.schema = undefined;
this.id = id;
this.name = '_never_';
this.defaultValue = undefined;
this.deps = deps;
}
ComputedEditorOption.prototype.validate = function (input) {
return this.defaultValue;
};
return ComputedEditorOption;
}());
var SimpleEditorOption = /** @class */ (function () {
function SimpleEditorOption(id, name, defaultValue, schema) {
this.id = id;
this.name = name;
this.defaultValue = defaultValue;
this.schema = schema;
}
SimpleEditorOption.prototype.validate = function (input) {
if (typeof input === 'undefined') {
return this.defaultValue;
}
return input;
};
SimpleEditorOption.prototype.compute = function (env, options, value) {
return value;
};
return SimpleEditorOption;
}());
var EditorBooleanOption = /** @class */ (function (_super) {
__extends(EditorBooleanOption, _super);
function EditorBooleanOption(id, name, defaultValue, schema) {
if (schema === void 0) { schema = undefined; }
var _this = this;
if (typeof schema !== 'undefined') {
schema.type = 'boolean';
schema.default = defaultValue;
}
_this = _super.call(this, id, name, defaultValue, schema) || this;
return _this;
}
EditorBooleanOption.boolean = function (value, defaultValue) {
if (typeof value === 'undefined') {
return defaultValue;
}
if (value === 'false') {
// treat the string 'false' as false
return false;
}
return Boolean(value);
};
EditorBooleanOption.prototype.validate = function (input) {
return EditorBooleanOption.boolean(input, this.defaultValue);
};
return EditorBooleanOption;
}(SimpleEditorOption));
var EditorIntOption = /** @class */ (function (_super) {
__extends(EditorIntOption, _super);
function EditorIntOption(id, name, defaultValue, minimum, maximum, schema) {
if (schema === void 0) { schema = undefined; }
var _this = this;
if (typeof schema !== 'undefined') {
schema.type = 'integer';
schema.default = defaultValue;
schema.minimum = minimum;
schema.maximum = maximum;
}
_this = _super.call(this, id, name, defaultValue, schema) || this;
_this.minimum = minimum;
_this.maximum = maximum;
return _this;
}
EditorIntOption.clampedInt = function (value, defaultValue, minimum, maximum) {
var r;
if (typeof value === 'undefined') {
r = defaultValue;
}
else {
r = parseInt(value, 10);
if (isNaN(r)) {
r = defaultValue;
}
}
r = Math.max(minimum, r);
r = Math.min(maximum, r);
return r | 0;
};
EditorIntOption.prototype.validate = function (input) {
return EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum);
};
return EditorIntOption;
}(SimpleEditorOption));
var EditorFloatOption = /** @class */ (function (_super) {
__extends(EditorFloatOption, _super);
function EditorFloatOption(id, name, defaultValue, validationFn, schema) {
var _this = this;
if (typeof schema !== 'undefined') {
schema.type = 'number';
schema.default = defaultValue;
}
_this = _super.call(this, id, name, defaultValue, schema) || this;
_this.validationFn = validationFn;
return _this;
}
EditorFloatOption.clamp = function (n, min, max) {
if (n < min) {
return min;
}
if (n > max) {
return max;
}
return n;
};
EditorFloatOption.float = function (value, defaultValue) {
if (typeof value === 'number') {
return value;
}
if (typeof value === 'undefined') {
return defaultValue;
}
var r = parseFloat(value);
return (isNaN(r) ? defaultValue : r);
};
EditorFloatOption.prototype.validate = function (input) {
return this.validationFn(EditorFloatOption.float(input, this.defaultValue));
};
return EditorFloatOption;
}(SimpleEditorOption));
var EditorStringOption = /** @class */ (function (_super) {
__extends(EditorStringOption, _super);
function EditorStringOption(id, name, defaultValue, schema) {
if (schema === void 0) { schema = undefined; }
var _this = this;
if (typeof schema !== 'undefined') {
schema.type = 'string';
schema.default = defaultValue;
}
_this = _super.call(this, id, name, defaultValue, schema) || this;
return _this;
}
EditorStringOption.string = function (value, defaultValue) {
if (typeof value !== 'string') {
return defaultValue;
}
return value;
};
EditorStringOption.prototype.validate = function (input) {
return EditorStringOption.string(input, this.defaultValue);
};
return EditorStringOption;
}(SimpleEditorOption));
var EditorStringEnumOption = /** @class */ (function (_super) {
__extends(EditorStringEnumOption, _super);
function EditorStringEnumOption(id, name, defaultValue, allowedValues, schema) {
if (schema === void 0) { schema = undefined; }
var _this = this;
if (typeof schema !== 'undefined') {
schema.type = 'string';
schema.enum = allowedValues;
schema.default = defaultValue;
}
_this = _super.call(this, id, name, defaultValue, schema) || this;
_this._allowedValues = allowedValues;
return _this;
}
EditorStringEnumOption.stringSet = function (value, defaultValue, allowedValues) {
if (typeof value !== 'string') {
return defaultValue;
}
if (allowedValues.indexOf(value) === -1) {
return defaultValue;
}
return value;
};
EditorStringEnumOption.prototype.validate = function (input) {
return EditorStringEnumOption.stringSet(input, this.defaultValue, this._allowedValues);
};
return EditorStringEnumOption;
}(SimpleEditorOption));
var EditorEnumOption = /** @class */ (function (_super) {
__extends(EditorEnumOption, _super);
function EditorEnumOption(id, name, defaultValue, defaultStringValue, allowedValues, convert, schema) {
if (schema === void 0) { schema = undefined; }
var _this = this;
if (typeof schema !== 'undefined') {
schema.type = 'string';
schema.enum = allowedValues;
schema.default = defaultStringValue;
}
_this = _super.call(this, id, name, defaultValue, schema) || this;
_this._allowedValues = allowedValues;
_this._convert = convert;
return _this;
}
EditorEnumOption.prototype.validate = function (input) {
if (typeof input !== 'string') {
return this.defaultValue;
}
if (this._allowedValues.indexOf(input) === -1) {
return this.defaultValue;
}
return this._convert(input);
};
return EditorEnumOption;
}(BaseEditorOption));
//#endregion
//#region autoIndent
function _autoIndentFromString(autoIndent) {
switch (autoIndent) {
case 'none': return 0 /* None */;
case 'keep': return 1 /* Keep */;
case 'brackets': return 2 /* Brackets */;
case 'advanced': return 3 /* Advanced */;
case 'full': return 4 /* Full */;
}
}
//#endregion
//#region accessibilitySupport
var EditorAccessibilitySupport = /** @class */ (function (_super) {
__extends(EditorAccessibilitySupport, _super);
function EditorAccessibilitySupport() {
return _super.call(this, 2 /* accessibilitySupport */, 'accessibilitySupport', 0 /* Unknown */, {
type: 'string',
enum: ['auto', 'on', 'off'],
enumDescriptions: [
nls.localize(0, null),
nls.localize(1, null),
nls.localize(2, null),
],
default: 'auto',
description: nls.localize(3, null)
}) || this;
}
EditorAccessibilitySupport.prototype.validate = function (input) {
switch (input) {
case 'auto': return 0 /* Unknown */;
case 'off': return 1 /* Disabled */;
case 'on': return 2 /* Enabled */;
}
return this.defaultValue;
};
EditorAccessibilitySupport.prototype.compute = function (env, options, value) {
if (value === 0 /* Unknown */) {
// The editor reads the `accessibilitySupport` from the environment
return env.accessibilitySupport;
}
return value;
};
return EditorAccessibilitySupport;
}(BaseEditorOption));
var EditorComments = /** @class */ (function (_super) {
__extends(EditorComments, _super);
function EditorComments() {
var _this = this;
var defaults = {
insertSpace: true,
};
_this = _super.call(this, 13 /* comments */, 'comments', defaults, {
'editor.comments.insertSpace': {
type: 'boolean',
default: defaults.insertSpace,
description: nls.localize(4, null)
},
}) || this;
return _this;
}
EditorComments.prototype.validate = function (_input) {
if (typeof _input !== 'object') {
return this.defaultValue;
}
var input = _input;
return {
insertSpace: EditorBooleanOption.boolean(input.insertSpace, this.defaultValue.insertSpace),
};
};
return EditorComments;
}(BaseEditorOption));
function _cursorBlinkingStyleFromString(cursorBlinkingStyle) {
switch (cursorBlinkingStyle) {
case 'blink': return 1 /* Blink */;
case 'smooth': return 2 /* Smooth */;
case 'phase': return 3 /* Phase */;
case 'expand': return 4 /* Expand */;
case 'solid': return 5 /* Solid */;
}
}
//#endregion
//#region cursorStyle
/**
* The style in which the editor's cursor should be rendered.
*/
var TextEditorCursorStyle;
(function (TextEditorCursorStyle) {
/**
* As a vertical line (sitting between two characters).
*/
TextEditorCursorStyle[TextEditorCursorStyle["Line"] = 1] = "Line";
/**
* As a block (sitting on top of a character).
*/
TextEditorCursorStyle[TextEditorCursorStyle["Block"] = 2] = "Block";
/**
* As a horizontal line (sitting under a character).
*/
TextEditorCursorStyle[TextEditorCursorStyle["Underline"] = 3] = "Underline";
/**
* As a thin vertical line (sitting between two characters).
*/
TextEditorCursorStyle[TextEditorCursorStyle["LineThin"] = 4] = "LineThin";
/**
* As an outlined block (sitting on top of a character).
*/
TextEditorCursorStyle[TextEditorCursorStyle["BlockOutline"] = 5] = "BlockOutline";
/**
* As a thin horizontal line (sitting under a character).
*/
TextEditorCursorStyle[TextEditorCursorStyle["UnderlineThin"] = 6] = "UnderlineThin";
})(TextEditorCursorStyle = exports.TextEditorCursorStyle || (exports.TextEditorCursorStyle = {}));
function _cursorStyleFromString(cursorStyle) {
switch (cursorStyle) {
case 'line': return TextEditorCursorStyle.Line;
case 'block': return TextEditorCursorStyle.Block;
case 'underline': return TextEditorCursorStyle.Underline;
case 'line-thin': return TextEditorCursorStyle.LineThin;
case 'block-outline': return TextEditorCursorStyle.BlockOutline;
case 'underline-thin': return TextEditorCursorStyle.UnderlineThin;
}
}
//#endregion
//#region editorClassName
var EditorClassName = /** @class */ (function (_super) {
__extends(EditorClassName, _super);
function EditorClassName() {
return _super.call(this, 104 /* editorClassName */, [55 /* mouseStyle */, 26 /* extraEditorClassName */]) || this;
}
EditorClassName.prototype.compute = function (env, options, _) {
var className = 'monaco-editor';
if (options.get(26 /* extraEditorClassName */)) {
className += ' ' + options.get(26 /* extraEditorClassName */);
}
if (env.extraEditorClassName) {
className += ' ' + env.extraEditorClassName;
}
if (options.get(55 /* mouseStyle */) === 'default') {
className += ' mouse-default';
}
else if (options.get(55 /* mouseStyle */) === 'copy') {
className += ' mouse-copy';
}
if (options.get(85 /* showUnused */)) {
className += ' showUnused';
}
return className;
};
return EditorClassName;
}(ComputedEditorOption));
//#endregion
//#region emptySelectionClipboard
var EditorEmptySelectionClipboard = /** @class */ (function (_super) {
__extends(EditorEmptySelectionClipboard, _super);
function EditorEmptySelectionClipboard() {
return _super.call(this, 25 /* emptySelectionClipboard */, 'emptySelectionClipboard', true, { description: nls.localize(5, null) }) || this;
}
EditorEmptySelectionClipboard.prototype.compute = function (env, options, value) {
return value && env.emptySelectionClipboard;
};
return EditorEmptySelectionClipboard;
}(EditorBooleanOption));
var EditorFind = /** @class */ (function (_super) {
__extends(EditorFind, _super);
function EditorFind() {
var _this = this;
var defaults = {
seedSearchStringFromSelection: true,
autoFindInSelection: 'never',
globalFindClipboard: false,
addExtraSpaceOnTop: true
};
_this = _super.call(this, 28 /* find */, 'find', defaults, {
'editor.find.seedSearchStringFromSelection': {
type: 'boolean',
default: defaults.seedSearchStringFromSelection,
description: nls.localize(6, null)
},
'editor.find.autoFindInSelection': {
type: 'string',
enum: ['never', 'always', 'multiline'],
default: defaults.autoFindInSelection,
enumDescriptions: [
nls.localize(7, null),
nls.localize(8, null),
nls.localize(9, null)
],
description: nls.localize(10, null)
},
'editor.find.globalFindClipboard': {
type: 'boolean',
default: defaults.globalFindClipboard,
description: nls.localize(11, null),
included: platform.isMacintosh
},
'editor.find.addExtraSpaceOnTop': {
type: 'boolean',
default: defaults.addExtraSpaceOnTop,
description: nls.localize(12, null)
}
}) || this;
return _this;
}
EditorFind.prototype.validate = function (_input) {
if (typeof _input !== 'object') {
return this.defaultValue;
}
var input = _input;
return {
seedSearchStringFromSelection: EditorBooleanOption.boolean(input.seedSearchStringFromSelection, this.defaultValue.seedSearchStringFromSelection),
autoFindInSelection: typeof _input.autoFindInSelection === 'boolean'
? (_input.autoFindInSelection ? 'always' : 'never')
: EditorStringEnumOption.stringSet(input.autoFindInSelection, this.defaultValue.autoFindInSelection, ['never', 'always', 'multiline']),
globalFindClipboard: EditorBooleanOption.boolean(input.globalFindClipboard, this.defaultValue.globalFindClipboard),
addExtraSpaceOnTop: EditorBooleanOption.boolean(input.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop)
};
};
return EditorFind;
}(BaseEditorOption));
//#endregion
//#region fontLigatures
/**
* @internal
*/
var EditorFontLigatures = /** @class */ (function (_super) {
__extends(EditorFontLigatures, _super);
function EditorFontLigatures() {
return _super.call(this, 35 /* fontLigatures */, 'fontLigatures', EditorFontLigatures.OFF, {
anyOf: [
{
type: 'boolean',
description: nls.localize(13, null),
},
{
type: 'string',
description: nls.localize(14, null)
}
],
description: nls.localize(15, null),
default: false
}) || this;
}
EditorFontLigatures.prototype.validate = function (input) {
if (typeof input === 'undefined') {
return this.defaultValue;
}
if (typeof input === 'string') {
if (input === 'false') {
return EditorFontLigatures.OFF;
}
if (input === 'true') {
return EditorFontLigatures.ON;
}
return input;
}
if (Boolean(input)) {
return EditorFontLigatures.ON;
}
return EditorFontLigatures.OFF;
};
EditorFontLigatures.OFF = '"liga" off, "calt" off';
EditorFontLigatures.ON = '"liga" on, "calt" on';
return EditorFontLigatures;
}(BaseEditorOption));
exports.EditorFontLigatures = EditorFontLigatures;
//#endregion
//#region fontInfo
var EditorFontInfo = /** @class */ (function (_super) {
__extends(EditorFontInfo, _super);
function EditorFontInfo() {
return _super.call(this, 34 /* fontInfo */) || this;
}
EditorFontInfo.prototype.compute = function (env, options, _) {
return env.fontInfo;
};
return EditorFontInfo;
}(ComputedEditorOption));
//#endregion
//#region fontSize
var EditorFontSize = /** @class */ (function (_super) {
__extends(EditorFontSize, _super);
function EditorFontSize() {
return _super.call(this, 36 /* fontSize */, 'fontSize', exports.EDITOR_FONT_DEFAULTS.fontSize, {
type: 'number',
minimum: 6,
maximum: 100,
default: exports.EDITOR_FONT_DEFAULTS.fontSize,
description: nls.localize(16, null)
}) || this;
}
EditorFontSize.prototype.validate = function (input) {
var r = EditorFloatOption.float(input, this.defaultValue);
if (r === 0) {
return exports.EDITOR_FONT_DEFAULTS.fontSize;
}
return EditorFloatOption.clamp(r, 6, 100);
};
EditorFontSize.prototype.compute = function (env, options, value) {
// The final fontSize respects the editor zoom level.
// So take the result from env.fontInfo
return env.fontInfo.fontSize;
};
return EditorFontSize;
}(SimpleEditorOption));
var EditorGoToLocation = /** @class */ (function (_super) {
__extends(EditorGoToLocation, _super);
function EditorGoToLocation() {
var _this = this;
var defaults = {
multiple: 'peek',
multipleDefinitions: 'peek',
multipleTypeDefinitions: 'peek',
multipleDeclarations: 'peek',
multipleImplementations: 'peek',
multipleReferences: 'peek',
alternativeDefinitionCommand: 'editor.action.goToReferences',
alternativeTypeDefinitionCommand: 'editor.action.goToReferences',
alternativeDeclarationCommand: 'editor.action.goToReferences',
alternativeImplementationCommand: '',
alternativeReferenceCommand: '',
};
var jsonSubset = {
type: 'string',
enum: ['peek', 'gotoAndPeek', 'goto'],
default: defaults.multiple,
enumDescriptions: [
nls.localize(17, null),
nls.localize(18, null),
nls.localize(19, null)
]
};
_this = _super.call(this, 41 /* gotoLocation */, 'gotoLocation', defaults, {
'editor.gotoLocation.multiple': {
deprecationMessage: nls.localize(20, null),
},
'editor.gotoLocation.multipleDefinitions': __assign({ description: nls.localize(21, null) }, jsonSubset),
'editor.gotoLocation.multipleTypeDefinitions': __assign({ description: nls.localize(22, null) }, jsonSubset),
'editor.gotoLocation.multipleDeclarations': __assign({ description: nls.localize(23, null) }, jsonSubset),
'editor.gotoLocation.multipleImplementations': __assign({ description: nls.localize(24, null) }, jsonSubset),
'editor.gotoLocation.multipleReferences': __assign({ description: nls.localize(25, null) }, jsonSubset),
'editor.gotoLocation.alternativeDefinitionCommand': {
type: 'string',
default: defaults.alternativeDefinitionCommand,
description: nls.localize(26, null)
},
'editor.gotoLocation.alternativeTypeDefinitionCommand': {
type: 'string',
default: defaults.alternativeTypeDefinitionCommand,
description: nls.localize(27, null)
},
'editor.gotoLocation.alternativeDeclarationCommand': {
type: 'string',
default: defaults.alternativeDeclarationCommand,
description: nls.localize(28, null)
},
'editor.gotoLocation.alternativeImplementationCommand': {
type: 'string',
default: defaults.alternativeImplementationCommand,
description: nls.localize(29, null)
},
'editor.gotoLocation.alternativeReferenceCommand': {
type: 'string',
default: defaults.alternativeReferenceCommand,
description: nls.localize(30, null)
},
}) || this;
return _this;
}
EditorGoToLocation.prototype.validate = function (_input) {
var _a, _b, _c, _d, _e;
if (typeof _input !== 'object') {
return this.defaultValue;
}
var input = _input;
return {
multiple: EditorStringEnumOption.stringSet(input.multiple, this.defaultValue.multiple, ['peek', 'gotoAndPeek', 'goto']),
multipleDefinitions: (_a = input.multipleDefinitions) !== null && _a !== void 0 ? _a : EditorStringEnumOption.stringSet(input.multipleDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']),
multipleTypeDefinitions: (_b = input.multipleTypeDefinitions) !== null && _b !== void 0 ? _b : EditorStringEnumOption.stringSet(input.multipleTypeDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']),
multipleDeclarations: (_c = input.multipleDeclarations) !== null && _c !== void 0 ? _c : EditorStringEnumOption.stringSet(input.multipleDeclarations, 'peek', ['peek', 'gotoAndPeek', 'goto']),
multipleImplementations: (_d = input.multipleImplementations) !== null && _d !== void 0 ? _d : EditorStringEnumOption.stringSet(input.multipleImplementations, 'peek', ['peek', 'gotoAndPeek', 'goto']),
multipleReferences: (_e = input.multipleReferences) !== null && _e !== void 0 ? _e : EditorStringEnumOption.stringSet(input.multipleReferences, 'peek', ['peek', 'gotoAndPeek', 'goto']),
alternativeDefinitionCommand: EditorStringOption.string(input.alternativeDefinitionCommand, this.defaultValue.alternativeDefinitionCommand),
alternativeTypeDefinitionCommand: EditorStringOption.string(input.alternativeTypeDefinitionCommand, this.defaultValue.alternativeTypeDefinitionCommand),
alternativeDeclarationCommand: EditorStringOption.string(input.alternativeDeclarationCommand, this.defaultValue.alternativeDeclarationCommand),
alternativeImplementationCommand: EditorStringOption.string(input.alternativeImplementationCommand, this.defaultValue.alternativeImplementationCommand),
alternativeReferenceCommand: EditorStringOption.string(input.alternativeReferenceCommand, this.defaultValue.alternativeReferenceCommand),
};
};
return EditorGoToLocation;
}(BaseEditorOption));
var EditorHover = /** @class */ (function (_super) {
__extends(EditorHover, _super);
function EditorHover() {
var _this = this;
var defaults = {
enabled: true,
delay: 300,
sticky: true
};
_this = _super.call(this, 44 /* hover */, 'hover', defaults, {
'editor.hover.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(31, null)
},
'editor.hover.delay': {
type: 'number',
default: defaults.delay,
description: nls.localize(32, null)
},
'editor.hover.sticky': {
type: 'boolean',
default: defaults.sticky,
description: nls.localize(33, null)
},
}) || this;
return _this;
}
EditorHover.prototype.validate = function (_input) {
if (typeof _input !== 'object') {
return this.defaultValue;
}
var input = _input;
return {
enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled),
delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 10000),
sticky: EditorBooleanOption.boolean(input.sticky, this.defaultValue.sticky)
};
};
return EditorHover;
}(BaseEditorOption));
/**
* @internal
*/
var EditorLayoutInfoComputer = /** @class */ (function (_super) {
__extends(EditorLayoutInfoComputer, _super);
function EditorLayoutInfoComputer() {
return _super.call(this, 107 /* layoutInfo */, [40 /* glyphMargin */, 48 /* lineDecorationsWidth */, 30 /* folding */, 54 /* minimap */, 78 /* scrollbar */, 50 /* lineNumbers */]) || this;
}
EditorLayoutInfoComputer.prototype.compute = function (env, options, _) {
return EditorLayoutInfoComputer.computeLayout(options, {
outerWidth: env.outerWidth,
outerHeight: env.outerHeight,
lineHeight: env.fontInfo.lineHeight,
lineNumbersDigitCount: env.lineNumbersDigitCount,
typicalHalfwidthCharacterWidth: env.fontInfo.typicalHalfwidthCharacterWidth,
maxDigitWidth: env.fontInfo.maxDigitWidth,
pixelRatio: env.pixelRatio
});
};
EditorLayoutInfoComputer.computeLayout = function (options, env) {
var outerWidth = env.outerWidth | 0;
var outerHeight = env.outerHeight | 0;
var lineHeight = env.lineHeight | 0;
var lineNumbersDigitCount = env.lineNumbersDigitCount | 0;
var typicalHalfwidthCharacterWidth = env.typicalHalfwidthCharacterWidth;
var maxDigitWidth = env.maxDigitWidth;
var pixelRatio = env.pixelRatio;
var showGlyphMargin = options.get(40 /* glyphMargin */);
var showLineNumbers = (options.get(50 /* lineNumbers */).renderType !== 0 /* Off */);
var lineNumbersMinChars = options.get(51 /* lineNumbersMinChars */) | 0;
var minimap = options.get(54 /* minimap */);
var minimapEnabled = minimap.enabled;
var minimapSide = minimap.side;
var minimapRenderCharacters = minimap.renderCharacters;
var minimapScale = (pixelRatio >= 2 ? Math.round(minimap.scale * 2) : minimap.scale);
var minimapMaxColumn = minimap.maxColumn | 0;
var scrollbar = options.get(78 /* scrollbar */);
var verticalScrollbarWidth = scrollbar.verticalScrollbarSize | 0;
var verticalScrollbarHasArrows = scrollbar.verticalHasArrows;
var scrollbarArrowSize = scrollbar.arrowSize | 0;
var horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize | 0;
var rawLineDecorationsWidth = options.get(48 /* lineDecorationsWidth */);
var folding = options.get(30 /* folding */);
var lineDecorationsWidth;
if (typeof rawLineDecorationsWidth === 'string' && /^\d+(\.\d+)?ch$/.test(rawLineDecorationsWidth)) {
var multiple = parseFloat(rawLineDecorationsWidth.substr(0, rawLineDecorationsWidth.length - 2));
lineDecorationsWidth = EditorIntOption.clampedInt(multiple * typicalHalfwidthCharacterWidth, 0, 0, 1000);
}
else {
lineDecorationsWidth = EditorIntOption.clampedInt(rawLineDecorationsWidth, 0, 0, 1000);
}
if (folding) {
lineDecorationsWidth += 16;
}
var lineNumbersWidth = 0;
if (showLineNumbers) {
var digitCount = Math.max(lineNumbersDigitCount, lineNumbersMinChars);
lineNumbersWidth = Math.round(digitCount * maxDigitWidth);
}
var glyphMarginWidth = 0;
if (showGlyphMargin) {
glyphMarginWidth = lineHeight;
}
var glyphMarginLeft = 0;
var lineNumbersLeft = glyphMarginLeft + glyphMarginWidth;
var decorationsLeft = lineNumbersLeft + lineNumbersWidth;
var contentLeft = decorationsLeft + lineDecorationsWidth;
var remainingWidth = outerWidth - glyphMarginWidth - lineNumbersWidth - lineDecorationsWidth;
var renderMinimap;
var minimapLeft;
var minimapWidth;
var contentWidth;
if (!minimapEnabled) {
minimapLeft = 0;
minimapWidth = 0;
renderMinimap = 0 /* None */;
contentWidth = remainingWidth;
}
else {
// The minimapScale is also the pixel width of each character. Adjust
// for the pixel ratio of the screen.
var minimapCharWidth = minimapScale / pixelRatio;
renderMinimap = minimapRenderCharacters ? 1 /* Text */ : 2 /* Blocks */;
// Given:
// (leaving 2px for the cursor to have space after the last character)
// viewportColumn = (contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth
// minimapWidth = viewportColumn * minimapCharWidth
// contentWidth = remainingWidth - minimapWidth
// What are good values for contentWidth and minimapWidth ?
// minimapWidth = ((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth) * minimapCharWidth
// typicalHalfwidthCharacterWidth * minimapWidth = (contentWidth - verticalScrollbarWidth - 2) * minimapCharWidth
// typicalHalfwidthCharacterWidth * minimapWidth = (remainingWidth - minimapWidth - verticalScrollbarWidth - 2) * minimapCharWidth
// (typicalHalfwidthCharacterWidth + minimapCharWidth) * minimapWidth = (remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth
// minimapWidth = ((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth) / (typicalHalfwidthCharacterWidth + minimapCharWidth)
minimapWidth = Math.max(0, Math.floor(((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth) / (typicalHalfwidthCharacterWidth + minimapCharWidth))) + exports.MINIMAP_GUTTER_WIDTH;
var minimapColumns = minimapWidth / minimapCharWidth;
if (minimapColumns > minimapMaxColumn) {
minimapWidth = Math.floor(minimapMaxColumn * minimapCharWidth);
}
contentWidth = remainingWidth - minimapWidth;
if (minimapSide === 'left') {
minimapLeft = 0;
glyphMarginLeft += minimapWidth;
lineNumbersLeft += minimapWidth;
decorationsLeft += minimapWidth;
contentLeft += minimapWidth;
}
else {
minimapLeft = outerWidth - minimapWidth - verticalScrollbarWidth;
}
}
// (leaving 2px for the cursor to have space after the last character)
var viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth));
var verticalArrowSize = (verticalScrollbarHasArrows ? scrollbarArrowSize : 0);
return {
width: outerWidth,
height: outerHeight,
glyphMarginLeft: glyphMarginLeft,
glyphMarginWidth: glyphMarginWidth,
lineNumbersLeft: lineNumbersLeft,
lineNumbersWidth: lineNumbersWidth,
decorationsLeft: decorationsLeft,
decorationsWidth: lineDecorationsWidth,
contentLeft: contentLeft,
contentWidth: contentWidth,
renderMinimap: renderMinimap,
minimapLeft: minimapLeft,
minimapWidth: minimapWidth,
viewportColumn: viewportColumn,
verticalScrollbarWidth: verticalScrollbarWidth,
horizontalScrollbarHeight: horizontalScrollbarHeight,
overviewRuler: {
top: verticalArrowSize,
width: verticalScrollbarWidth,
height: (outerHeight - 2 * verticalArrowSize),
right: 0
}
};
};
return EditorLayoutInfoComputer;
}(ComputedEditorOption));
exports.EditorLayoutInfoComputer = EditorLayoutInfoComputer;
var EditorLightbulb = /** @class */ (function (_super) {
__extends(EditorLightbulb, _super);
function EditorLightbulb() {
var _this = this;
var defaults = { enabled: true };
_this = _super.call(this, 47 /* lightbulb */, 'lightbulb', defaults, {
'editor.lightbulb.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(34, null)
},
}) || this;
return _this;
}
EditorLightbulb.prototype.validate = function (_input) {
if (typeof _input !== 'object') {
return this.defaultValue;
}
var input = _input;
return {
enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled)
};
};
return EditorLightbulb;
}(BaseEditorOption));
//#endregion
//#region lineHeight
var EditorLineHeight = /** @class */ (function (_super) {
__extends(EditorLineHeight, _super);
function EditorLineHeight() {
return _super.call(this, 49 /* lineHeight */, 'lineHeight', exports.EDITOR_FONT_DEFAULTS.lineHeight, 0, 150, { description: nls.localize(35, null) }) || this;
}
EditorLineHeight.prototype.compute = function (env, options, value) {
// The lineHeight is computed from the fontSize if it is 0.
// Moreover, the final lineHeight respects the editor zoom level.
// So take the result from env.fontInfo
return env.fontInfo.lineHeight;
};
return EditorLineHeight;
}(EditorIntOption));
var EditorMinimap = /** @class */ (function (_super) {
__extends(EditorMinimap, _super);
function EditorMinimap() {
var _this = this;
var defaults = {
enabled: true,
side: 'right',
showSlider: 'mouseover',
renderCharacters: true,
maxColumn: 120,
scale: 1,
};
_this = _super.call(this, 54 /* minimap */, 'minimap', defaults, {
'editor.minimap.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(36, null)
},
'editor.minimap.side': {
type: 'string',
enum: ['left', 'right'],
default: defaults.side,
description: nls.localize(37, null)
},
'editor.minimap.showSlider': {
type: 'string',
enum: ['always', 'mouseover'],
default: defaults.showSlider,
description: nls.localize(38, null)
},
'editor.minimap.scale': {
type: 'number',
default: defaults.scale,
minimum: 1,
maximum: 3,
description: nls.localize(39, null)
},
'editor.minimap.renderCharacters': {
type: 'boolean',
default: defaults.renderCharacters,
description: nls.localize(40, null)
},
'editor.minimap.maxColumn': {
type: 'number',
default: defaults.maxColumn,
description: nls.localize(41, null)
},
}) || this;
return _this;
}
EditorMinimap.prototype.validate = function (_input) {
if (typeof _input !== 'object') {
return this.defaultValue;
}
var input = _input;
return {
enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled),
side: EditorStringEnumOption.stringSet(input.side, this.defaultValue.side, ['right', 'left']),
showSlider: EditorStringEnumOption.stringSet(input.showSlider, this.defaultValue.showSlider, ['always', 'mouseover']),
renderCharacters: EditorBooleanOption.boolean(input.renderCharacters, this.defaultValue.renderCharacters),
scale: EditorIntOption.clampedInt(input.scale, 1, 1, 3),
maxColumn: EditorIntOption.clampedInt(input.maxColumn, this.defaultValue.maxColumn, 1, 10000),
};
};
return EditorMinimap;
}(BaseEditorOption));
//#endregion
//#region multiCursorModifier
function _multiCursorModifierFromString(multiCursorModifier) {
if (multiCursorModifier === 'ctrlCmd') {
return (platform.isMacintosh ? 'metaKey' : 'ctrlKey');
}
return 'altKey';
}
var EditorParameterHints = /** @class */ (function (_super) {
__extends(EditorParameterHints, _super);
function EditorParameterHints() {
var _this = this;
var defaults = {
enabled: true,
cycle: false
};
_this = _super.call(this, 64 /* parameterHints */, 'parameterHints', defaults, {
'editor.parameterHints.enabled': {
type: 'boolean',
default: defaults.enabled,
description: nls.localize(42, null)
},
'editor.parameterHints.cycle': {
type: 'boolean',
default: defaults.cycle,
description: nls.localize(43, null)
},
}) || this;
return _this;
}
EditorParameterHints.prototype.validate = function (_input) {
if (typeof _input !== 'object') {
return this.defaultValue;
}
var input = _input;
return {
enabled: EditorBooleanOption.boolean(input.enabled, this.defaultValue.enabled),
cycle: EditorBooleanOption.boolean(input.cycle, this.defaultValue.cycle)
};
};
return EditorParameterHints;
}(BaseEditorOption));
//#endregion
//#region pixelRatio
var EditorPixelRatio = /** @class */ (function (_super) {
__extends(EditorPixelRatio, _super);
function EditorPixelRatio() {
return _super.call(this, 105 /* pixelRatio */) || this;
}
EditorPixelRatio.prototype.compute = function (env, options, _) {
return env.pixelRatio;
};
return EditorPixelRatio;
}(ComputedEditorOption));
var EditorQuickSuggestions = /** @class */ (function (_super) {
__extends(EditorQuickSuggestions, _super);
function EditorQuickSuggestions() {
var _this = this;
var defaults = {
other: true,
comments: false,
strings: false
};
_this = _super.call(this, 66 /* quickSuggestions */, 'quickSuggestions', defaults, {
anyOf: [
{
type: 'boolean',
},
{
type: 'object',
properties: {
strings: {
type: 'boolean',
default: defaults.strings,
description: nls.localize(44, null)
},
comments: {
type: 'boolean',
default: defaults.comments,
description: nls.localize(45, null)
},
other: {
type: 'boolean',
default: defaults.other,
description: nls.localize(46, null)
},
}
}
],
default: defaults,
description: nls.localize(47, null)
}) || this;
_this.defaultValue = defaults;
return _this;
}
EditorQuickSuggestions.prototype.validate = function (_input) {
if (typeof _input === 'boolean') {
return _input;
}
if (typeof _input === 'object') {
var input = _input;
var opts = {
other: EditorBooleanOption.boolean(input.other, this.defaultValue.other),
comments: EditorBooleanOption.boolean(input.comments, this.defaultValue.comments),
strings: EditorBooleanOption.boolean(input.strings, this.defaultValue.strings),
};
if (opts.other && opts.comments && opts.strings) {
return true; // all on
}
else if (!opts.other && !opts.comments && !opts.strings) {
return false; // all off
}
else {
return opts;
}
}
return this.defaultValue;
};
return EditorQuickSuggestions;
}(BaseEditorOption));
var EditorRenderLineNumbersOption = /** @class */ (function (_super) {
__extends(EditorRenderLineNumbersOption, _super);
function EditorRenderLineNumbersOption() {
return _super.call(this, 50 /* lineNumbers */, 'lineNumbers', { renderType: 1 /* On */, renderFn: null }, {
type: 'string',
enum: ['off', 'on', 'relative', 'interval'],
enumDescriptions: [
nls.localize(48, null),
nls.localize(49, null),
nls.localize(50, null),
nls.localize(51, null)
],
default: 'on',
description: nls.localize(52, null)
}) || this;
}
EditorRenderLineNumbersOption.prototype.validate = function (lineNumbers) {
var renderType = this.defaultValue.renderType;
var renderFn = this.defaultValue.renderFn;
if (typeof lineNumbers !== 'undefined') {
if (typeof lineNumbers === 'function') {
renderType = 4 /* Custom */;
renderFn = lineNumbers;
}
else if (lineNumbers === 'interval') {
renderType = 3 /* Interval */;
}
else if (lineNumbers === 'relative') {
renderType = 2 /* Relative */;
}
else if (lineNumbers === 'on') {
renderType = 1 /* On */;
}
else {
renderType = 0 /* Off */;
}
}
return {
renderType: renderType,
renderFn: renderFn
};
};
return EditorRenderLineNumbersOption;
}(BaseEditorOption));
//#endregion
//#region renderValidationDecorations
/**
* @internal
*/
function filterValidationDecorations(options) {
var renderValidationDecorations = options.get(73 /* renderValidationDecorations */);
if (renderValidationDecorations === 'editable') {
return options.get(68 /* readOnly */);
}
return renderValidationDecorations === 'on' ? false : true;
}
exports.filterValidationDecorations = filterValidationDecorations;
//#endregion
//#region rulers
var EditorRulers = /** @class */ (function (_super) {
__extends(EditorRulers, _super);
function EditorRulers() {
var _this = this;
var defaults = [];
_this = _super.call(this, 77 /* rulers */, 'rulers', defaults, {
type: 'array',
items: {
type: 'number'
},
default: defaults,
description: nls.localize(53, null)
}) || this;
return _this;
}
EditorRulers.prototype.validate = function (input) {
if (Array.isArray(input)) {
var rulers = [];
for (var _i = 0, input_1 = input; _i < input_1.length; _i++) {
var value = input_1[_i];
rulers.push(EditorIntOption.clampedInt(value, 0, 0, 10000));
}
rulers.sort(function (a, b) { return a - b; });
return rulers;
}
return this.defaultValue;
};
return EditorRulers;
}(SimpleEditorOption));
function _scrollbarVisibilityFromString(visibility, defaultValue) {
if (typeof visibility !== 'string') {
return defaultValue;
}
switch (visibility) {
case 'hidden': return 2 /* Hidden */;
case 'visible': return 3 /* Visible */;
default: return 1 /* Auto */;
}
}
var EditorScrollbar = /** @class */ (function (_super) {
__extends(EditorScrollbar, _super);
function EditorScrollbar() {
return _super.call(this, 78 /* scrollbar */, 'scrollbar', {
vertical: 1 /* Auto */,
horizontal: 1 /* Auto */,
arrowSize: 11,
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
horizontalScrollbarSize: 10,
horizontalSliderSize: 10,
verticalScrollbarSize: 14,
verticalSliderSize: 14,
handleMouseWheel: true,
alwaysConsumeMouseWheel: true
}) || this;
}
EditorScrollbar.prototype.validate = function (_input) {
if (typeof _input !== 'object') {
return this.defaultValue;
}
var input = _input;
var horizontalScrollbarSize = EditorIntOption.clampedInt(input.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1000);
var verticalScrollbarSize = EditorIntOption.clampedInt(input.verticalScrollbarSize, this.defaultValue.verticalScrollbarSize, 0, 1000);
return {
arrowSize: EditorIntOption.clampedInt(input.arrowSize, this.defaultValue.arrowSize, 0, 1000),
vertical: _scrollbarVisibilityFromString(input.vertical, this.defaultValue.vertical),
horizontal: _scrollbarVisibilityFromString(input.horizontal, this.defaultValue.horizontal),
useShadows: EditorBooleanOption.boolean(input.useShadows, this.defaultValue.useShadows),
verticalHasArrows: EditorBooleanOption.boolean(input.verticalHasArrows, this.defaultValue.verticalHasArrows),
horizontalHasArrows: EditorBooleanOption.boolean(input.horizontalHasArrows, this.defaultValue.horizontalHasArrows),
handleMouseWheel: EditorBooleanOption.boolean(input.handleMouseWheel, this.defaultValue.handleMouseWheel),
alwaysConsumeMouseWheel: EditorBooleanOption.boolean(input.alwaysConsumeMouseWheel, this.defaultValue.alwaysConsumeMouseWheel),
horizontalScrollbarSize: horizontalScrollbarSize,
horizontalSliderSize: EditorIntOption.clampedInt(input.horizontalSliderSize, horizontalScrollbarSize, 0, 1000),
verticalScrollbarSize: verticalScrollbarSize,
verticalSliderSize: EditorIntOption.clampedInt(input.verticalSliderSize, verticalScrollbarSize, 0, 1000),
};
};
return EditorScrollbar;
}(BaseEditorOption));
var EditorSuggest = /** @class */ (function (_super) {
__extends(EditorSuggest, _super);
function EditorSuggest() {
var _this = this;
var defaults = {
insertMode: 'insert',
insertHighlight: false,
filterGraceful: true,
snippetsPreventQuickSuggestions: true,
localityBonus: false,
shareSuggestSelections: false,
showIcons: true,
maxVisibleSuggestions: 12,
showMethods: true,
showFunctions: true,
showConstructors: true,
showFields: true,
showVariables: true,
showClasses: true,
showStructs: true,
showInterfaces: true,
showModules: true,
showProperties: true,
showEvents: true,
showOperators: true,
showUnits: true,
showValues: true,
showConstants: true,
showEnums: true,
showEnumMembers: true,
showKeywords: true,
showWords: true,
showColors: true,
showFiles: true,
showReferences: true,
showFolders: true,
showTypeParameters: true,
showSnippets: true,
hideStatusBar: true
};
_this = _super.call(this, 89 /* suggest */, 'suggest', defaults, {
'editor.suggest.insertMode': {
type: 'string',
enum: ['insert', 'replace'],
enumDescriptions: [
nls.localize(54, null),
nls.localize(55, null),
],
default: defaults.insertMode,
description: nls.localize(56, null)
},
'editor.suggest.insertHighlight': {
type: 'boolean',
default: defaults.insertHighlight,
description: nls.localize(57, null)
},
'editor.suggest.filterGraceful': {
type: 'boolean',
default: defaults.filterGraceful,
description: nls.localize(58, null)
},
'editor.suggest.localityBonus': {
type: 'boolean',
default: defaults.localityBonus,
description: nls.localize(59, null)
},
'editor.suggest.shareSuggestSelections': {
type: 'boolean',
default: defaults.shareSuggestSelections,
markdownDescription: nls.localize(60, null)
},
'editor.suggest.snippetsPreventQuickSuggestions': {
type: 'boolean',
default: defaults.snippetsPreventQuickSuggestions,
description: nls.localize(61, null)
},
'editor.suggest.showIcons': {
type: 'boolean',
default: defaults.showIcons,
description: nls.localize(62, null)
},
'editor.suggest.maxVisibleSuggestions': {
type: 'number',
default: defaults.maxVisibleSuggestions,
minimum: 1,
maximum: 15,
description: nls.localize(63, null)
},
'editor.suggest.filteredTypes': {
type: 'object',
deprecationMessage: nls.localize(64, null)
},
'editor.suggest.showMethods': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(65, null)
},
'editor.suggest.showFunctions': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(66, null)
},
'editor.suggest.showConstructors': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(67, null)
},
'editor.suggest.showFields': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(68, null)
},
'editor.suggest.showVariables': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(69, null)
},
'editor.suggest.showClasses': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(70, null)
},
'editor.suggest.showStructs': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(71, null)
},
'editor.suggest.showInterfaces': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(72, null)
},
'editor.suggest.showModules': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(73, null)
},
'editor.suggest.showProperties': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(74, null)
},
'editor.suggest.showEvents': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(75, null)
},
'editor.suggest.showOperators': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(76, null)
},
'editor.suggest.showUnits': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(77, null)
},
'editor.suggest.showValues': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(78, null)
},
'editor.suggest.showConstants': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(79, null)
},
'editor.suggest.showEnums': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(80, null)
},
'editor.suggest.showEnumMembers': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(81, null)
},
'editor.suggest.showKeywords': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(82, null)
},
'editor.suggest.showWords': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(83, null)
},
'editor.suggest.showColors': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(84, null)
},
'editor.suggest.showFiles': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(85, null)
},
'editor.suggest.showReferences': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(86, null)
},
'editor.suggest.showCustomcolors': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(87, null)
},
'editor.suggest.showFolders': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(88, null)
},
'editor.suggest.showTypeParameters': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(89, null)
},
'editor.suggest.showSnippets': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(90, null)
},
'editor.suggest.hideStatusBar': {
type: 'boolean',
default: true,
markdownDescription: nls.localize(91, null)
}
}) || this;
return _this;
}
EditorSuggest.prototype.validate = function (_input) {
if (typeof _input !== 'object') {
return this.defaultValue;
}
var input = _input;
return {
insertMode: EditorStringEnumOption.stringSet(input.insertMode, this.defaultValue.insertMode, ['insert', 'replace']),
insertHighlight: EditorBooleanOption.boolean(input.insertHighlight, this.defaultValue.insertHighlight),
filterGraceful: EditorBooleanOption.boolean(input.filterGraceful, this.defaultValue.filterGraceful),
snippetsPreventQuickSuggestions: EditorBooleanOption.boolean(input.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful),
localityBonus: EditorBooleanOption.boolean(input.localityBonus, this.defaultValue.localityBonus),
shareSuggestSelections: EditorBooleanOption.boolean(input.shareSuggestSelections, this.defaultValue.shareSuggestSelections),
showIcons: EditorBooleanOption.boolean(input.showIcons, this.defaultValue.showIcons),
maxVisibleSuggestions: EditorIntOption.clampedInt(input.maxVisibleSuggestions, this.defaultValue.maxVisibleSuggestions, 1, 15),
showMethods: EditorBooleanOption.boolean(input.showMethods, this.defaultValue.showMethods),
showFunctions: EditorBooleanOption.boolean(input.showFunctions, this.defaultValue.showFunctions),
showConstructors: EditorBooleanOption.boolean(input.showConstructors, this.defaultValue.showConstructors),
showFields: EditorBooleanOption.boolean(input.showFields, this.defaultValue.showFields),
showVariables: EditorBooleanOption.boolean(input.showVariables, this.defaultValue.showVariables),
showClasses: EditorBooleanOption.boolean(input.showClasses, this.defaultValue.showClasses),
showStructs: EditorBooleanOption.boolean(input.showStructs, this.defaultValue.showStructs),
showInterfaces: EditorBooleanOption.boolean(input.showInterfaces, this.defaultValue.showInterfaces),
showModules: EditorBooleanOption.boolean(input.showModules, this.defaultValue.showModules),
showProperties: EditorBooleanOption.boolean(input.showProperties, this.defaultValue.showProperties),
showEvents: EditorBooleanOption.boolean(input.showEvents, this.defaultValue.showEvents),
showOperators: EditorBooleanOption.boolean(input.showOperators, this.defaultValue.showOperators),
showUnits: EditorBooleanOption.boolean(input.showUnits, this.defaultValue.showUnits),
showValues: EditorBooleanOption.boolean(input.showValues, this.defaultValue.showValues),
showConstants: EditorBooleanOption.boolean(input.showConstants, this.defaultValue.showConstants),
showEnums: EditorBooleanOption.boolean(input.showEnums, this.defaultValue.showEnums),
showEnumMembers: EditorBooleanOption.boolean(input.showEnumMembers, this.defaultValue.showEnumMembers),
showKeywords: EditorBooleanOption.boolean(input.showKeywords, this.defaultValue.showKeywords),
showWords: EditorBooleanOption.boolean(input.showWords, this.defaultValue.showWords),
showColors: EditorBooleanOption.boolean(input.showColors, this.defaultValue.showColors),
showFiles: EditorBooleanOption.boolean(input.showFiles, this.defaultValue.showFiles),
showReferences: EditorBooleanOption.boolean(input.showReferences, this.defaultValue.showReferences),
showFolders: EditorBooleanOption.boolean(input.showFolders, this.defaultValue.showFolders),
showTypeParameters: EditorBooleanOption.boolean(input.showTypeParameters, this.defaultValue.showTypeParameters),
showSnippets: EditorBooleanOption.boolean(input.showSnippets, this.defaultValue.showSnippets),
hideStatusBar: EditorBooleanOption.boolean(input.hideStatusBar, this.defaultValue.hideStatusBar),
};
};
return EditorSuggest;
}(BaseEditorOption));
//#endregion
//#region tabFocusMode
var EditorTabFocusMode = /** @class */ (function (_super) {
__extends(EditorTabFocusMode, _super);
function EditorTabFocusMode() {
return _super.call(this, 106 /* tabFocusMode */, [68 /* readOnly */]) || this;
}
EditorTabFocusMode.prototype.compute = function (env, options, _) {
var readOnly = options.get(68 /* readOnly */);
return (readOnly ? true : env.tabFocusMode);
};
return EditorTabFocusMode;
}(ComputedEditorOption));
function _wrappingIndentFromString(wrappingIndent) {
switch (wrappingIndent) {
case 'none': return 0 /* None */;
case 'same': return 1 /* Same */;
case 'indent': return 2 /* Indent */;
case 'deepIndent': return 3 /* DeepIndent */;
}
}
var EditorWrappingInfoComputer = /** @class */ (function (_super) {
__extends(EditorWrappingInfoComputer, _super);
function EditorWrappingInfoComputer() {
return _super.call(this, 108 /* wrappingInfo */, [97 /* wordWrap */, 100 /* wordWrapColumn */, 101 /* wordWrapMinified */, 107 /* layoutInfo */, 2 /* accessibilitySupport */]) || this;
}
EditorWrappingInfoComputer.prototype.compute = function (env, options, _) {
var wordWrap = options.get(97 /* wordWrap */);
var wordWrapColumn = options.get(100 /* wordWrapColumn */);
var wordWrapMinified = options.get(101 /* wordWrapMinified */);
var layoutInfo = options.get(107 /* layoutInfo */);
var accessibilitySupport = options.get(2 /* accessibilitySupport */);
var bareWrappingInfo = null;
{
if (accessibilitySupport === 2 /* Enabled */) {
// See https://github.com/Microsoft/vscode/issues/27766
// Never enable wrapping when a screen reader is attached
// because arrow down etc. will not move the cursor in the way
// a screen reader expects.
bareWrappingInfo = {
isWordWrapMinified: false,
isViewportWrapping: false,
wrappingColumn: -1
};
}
else if (wordWrapMinified && env.isDominatedByLongLines) {
// Force viewport width wrapping if model is dominated by long lines
bareWrappingInfo = {
isWordWrapMinified: true,
isViewportWrapping: true,
wrappingColumn: Math.max(1, layoutInfo.viewportColumn)
};
}
else if (wordWrap === 'on') {
bareWrappingInfo = {
isWordWrapMinified: false,
isViewportWrapping: true,
wrappingColumn: Math.max(1, layoutInfo.viewportColumn)
};
}
else if (wordWrap === 'bounded') {
bareWrappingInfo = {
isWordWrapMinified: false,
isViewportWrapping: true,
wrappingColumn: Math.min(Math.max(1, layoutInfo.viewportColumn), wordWrapColumn)
};
}
else if (wordWrap === 'wordWrapColumn') {
bareWrappingInfo = {
isWordWrapMinified: false,
isViewportWrapping: false,
wrappingColumn: wordWrapColumn
};
}
else {
bareWrappingInfo = {
isWordWrapMinified: false,
isViewportWrapping: false,
wrappingColumn: -1
};
}
}
return {
isDominatedByLongLines: env.isDominatedByLongLines,
isWordWrapMinified: bareWrappingInfo.isWordWrapMinified,
isViewportWrapping: bareWrappingInfo.isViewportWrapping,
wrappingColumn: bareWrappingInfo.wrappingColumn,
};
};
return EditorWrappingInfoComputer;
}(ComputedEditorOption));
//#endregion
var DEFAULT_WINDOWS_FONT_FAMILY = 'Consolas, \'Courier New\', monospace';
var DEFAULT_MAC_FONT_FAMILY = 'Menlo, Monaco, \'Courier New\', monospace';
var DEFAULT_LINUX_FONT_FAMILY = '\'Droid Sans Mono\', \'monospace\', monospace, \'Droid Sans Fallback\'';
/**
* @internal
*/
exports.EDITOR_FONT_DEFAULTS = {
fontFamily: (platform.isMacintosh ? DEFAULT_MAC_FONT_FAMILY : (platform.isLinux ? DEFAULT_LINUX_FONT_FAMILY : DEFAULT_WINDOWS_FONT_FAMILY)),
fontWeight: 'normal',
fontSize: (platform.isMacintosh ? 12 : 14),
lineHeight: 0,
letterSpacing: 0,
};
/**
* @internal
*/
exports.EDITOR_MODEL_DEFAULTS = {
tabSize: 4,
indentSize: 4,
insertSpaces: true,
detectIndentation: true,
trimAutoWhitespace: true,
largeFileOptimizations: true
};
/**
* @internal
*/
exports.editorOptionsRegistry = [];
function register(option) {
exports.editorOptionsRegistry[option.id] = option;
return option;
}
/**
* WORKAROUND: TS emits "any" for complex editor options values (anything except string, bool, enum, etc. ends up being "any")
* @monacodtsreplace
* /accessibilitySupport, any/accessibilitySupport, AccessibilitySupport/
* /comments, any/comments, EditorCommentsOptions/
* /find, any/find, EditorFindOptions/
* /fontInfo, any/fontInfo, FontInfo/
* /gotoLocation, any/gotoLocation, GoToLocationOptions/
* /hover, any/hover, EditorHoverOptions/
* /lightbulb, any/lightbulb, EditorLightbulbOptions/
* /minimap, any/minimap, EditorMinimapOptions/
* /parameterHints, any/parameterHints, InternalParameterHintOptions/
* /quickSuggestions, any/quickSuggestions, ValidQuickSuggestionsOptions/
* /suggest, any/suggest, InternalSuggestOptions/
*/
exports.EditorOptions = {
acceptSuggestionOnCommitCharacter: register(new EditorBooleanOption(0 /* acceptSuggestionOnCommitCharacter */, 'acceptSuggestionOnCommitCharacter', true, { markdownDescription: nls.localize(92, null) })),
acceptSuggestionOnEnter: register(new EditorStringEnumOption(1 /* acceptSuggestionOnEnter */, 'acceptSuggestionOnEnter', 'on', ['on', 'smart', 'off'], {
markdownEnumDescriptions: [
'',
nls.localize(93, null),
''
],
markdownDescription: nls.localize(94, null)
})),
accessibilitySupport: register(new EditorAccessibilitySupport()),
accessibilityPageSize: register(new EditorIntOption(3 /* accessibilityPageSize */, 'accessibilityPageSize', 10, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(95, null) })),
ariaLabel: register(new EditorStringOption(4 /* ariaLabel */, 'ariaLabel', nls.localize(96, null))),
autoClosingBrackets: register(new EditorStringEnumOption(5 /* autoClosingBrackets */, 'autoClosingBrackets', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], {
enumDescriptions: [
'',
nls.localize(97, null),
nls.localize(98, null),
'',
],
description: nls.localize(99, null)
})),
autoClosingOvertype: register(new EditorStringEnumOption(6 /* autoClosingOvertype */, 'autoClosingOvertype', 'auto', ['always', 'auto', 'never'], {
enumDescriptions: [
'',
nls.localize(100, null),
'',
],
description: nls.localize(101, null)
})),
autoClosingQuotes: register(new EditorStringEnumOption(7 /* autoClosingQuotes */, 'autoClosingQuotes', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], {
enumDescriptions: [
'',
nls.localize(102, null),
nls.localize(103, null),
'',
],
description: nls.localize(104, null)
})),
autoIndent: register(new EditorEnumOption(8 /* autoIndent */, 'autoIndent', 4 /* Full */, 'full', ['none', 'keep', 'brackets', 'advanced', 'full'], _autoIndentFromString, {
enumDescriptions: [
nls.localize(105, null),
nls.localize(106, null),
nls.localize(107, null),
nls.localize(108, null),
nls.localize(109, null),
],
description: nls.localize(110, null)
})),
automaticLayout: register(new EditorBooleanOption(9 /* automaticLayout */, 'automaticLayout', false)),
autoSurround: register(new EditorStringEnumOption(10 /* autoSurround */, 'autoSurround', 'languageDefined', ['languageDefined', 'quotes', 'brackets', 'never'], {
enumDescriptions: [
nls.localize(111, null),
nls.localize(112, null),
nls.localize(113, null),
''
],
description: nls.localize(114, null)
})),
codeLens: register(new EditorBooleanOption(11 /* codeLens */, 'codeLens', true, { description: nls.localize(115, null) })),
colorDecorators: register(new EditorBooleanOption(12 /* colorDecorators */, 'colorDecorators', true, { description: nls.localize(116, null) })),
comments: register(new EditorComments()),
contextmenu: register(new EditorBooleanOption(14 /* contextmenu */, 'contextmenu', true)),
copyWithSyntaxHighlighting: register(new EditorBooleanOption(15 /* copyWithSyntaxHighlighting */, 'copyWithSyntaxHighlighting', true, { description: nls.localize(117, null) })),
cursorBlinking: register(new EditorEnumOption(16 /* cursorBlinking */, 'cursorBlinking', 1 /* Blink */, 'blink', ['blink', 'smooth', 'phase', 'expand', 'solid'], _cursorBlinkingStyleFromString, { description: nls.localize(118, null) })),
cursorSmoothCaretAnimation: register(new EditorBooleanOption(17 /* cursorSmoothCaretAnimation */, 'cursorSmoothCaretAnimation', false, { description: nls.localize(119, null) })),
cursorStyle: register(new EditorEnumOption(18 /* cursorStyle */, 'cursorStyle', TextEditorCursorStyle.Line, 'line', ['line', 'block', 'underline', 'line-thin', 'block-outline', 'underline-thin'], _cursorStyleFromString, { description: nls.localize(120, null) })),
cursorSurroundingLines: register(new EditorIntOption(19 /* cursorSurroundingLines */, 'cursorSurroundingLines', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(121, null) })),
cursorSurroundingLinesStyle: register(new EditorStringEnumOption(20 /* cursorSurroundingLinesStyle */, 'cursorSurroundingLinesStyle', 'default', ['default', 'all'], {
enumDescriptions: [
nls.localize(122, null),
nls.localize(123, null)
],
description: nls.localize(124, null)
})),
cursorWidth: register(new EditorIntOption(21 /* cursorWidth */, 'cursorWidth', 0, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { markdownDescription: nls.localize(125, null) })),
disableLayerHinting: register(new EditorBooleanOption(22 /* disableLayerHinting */, 'disableLayerHinting', false)),
disableMonospaceOptimizations: register(new EditorBooleanOption(23 /* disableMonospaceOptimizations */, 'disableMonospaceOptimizations', false)),
dragAndDrop: register(new EditorBooleanOption(24 /* dragAndDrop */, 'dragAndDrop', true, { description: nls.localize(126, null) })),
emptySelectionClipboard: register(new EditorEmptySelectionClipboard()),
extraEditorClassName: register(new EditorStringOption(26 /* extraEditorClassName */, 'extraEditorClassName', '')),
fastScrollSensitivity: register(new EditorFloatOption(27 /* fastScrollSensitivity */, 'fastScrollSensitivity', 5, function (x) { return (x <= 0 ? 5 : x); }, { markdownDescription: nls.localize(127, null) })),
find: register(new EditorFind()),
fixedOverflowWidgets: register(new EditorBooleanOption(29 /* fixedOverflowWidgets */, 'fixedOverflowWidgets', false)),
folding: register(new EditorBooleanOption(30 /* folding */, 'folding', true, { description: nls.localize(128, null) })),
foldingStrategy: register(new EditorStringEnumOption(31 /* foldingStrategy */, 'foldingStrategy', 'auto', ['auto', 'indentation'], { markdownDescription: nls.localize(129, null) })),
foldingHighlight: register(new EditorBooleanOption(32 /* foldingHighlight */, 'foldingHighlight', true, { description: nls.localize(130, null) })),
fontFamily: register(new EditorStringOption(33 /* fontFamily */, 'fontFamily', exports.EDITOR_FONT_DEFAULTS.fontFamily, { description: nls.localize(131, null) })),
fontInfo: register(new EditorFontInfo()),
fontLigatures2: register(new EditorFontLigatures()),
fontSize: register(new EditorFontSize()),
fontWeight: register(new EditorStringOption(37 /* fontWeight */, 'fontWeight', exports.EDITOR_FONT_DEFAULTS.fontWeight, {
enum: ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'],
description: nls.localize(132, null)
})),
formatOnPaste: register(new EditorBooleanOption(38 /* formatOnPaste */, 'formatOnPaste', false, { description: nls.localize(133, null) })),
formatOnType: register(new EditorBooleanOption(39 /* formatOnType */, 'formatOnType', false, { description: nls.localize(134, null) })),
glyphMargin: register(new EditorBooleanOption(40 /* glyphMargin */, 'glyphMargin', true, { description: nls.localize(135, null) })),
gotoLocation: register(new EditorGoToLocation()),
hideCursorInOverviewRuler: register(new EditorBooleanOption(42 /* hideCursorInOverviewRuler */, 'hideCursorInOverviewRuler', false, { description: nls.localize(136, null) })),
highlightActiveIndentGuide: register(new EditorBooleanOption(43 /* highlightActiveIndentGuide */, 'highlightActiveIndentGuide', true, { description: nls.localize(137, null) })),
hover: register(new EditorHover()),
inDiffEditor: register(new EditorBooleanOption(45 /* inDiffEditor */, 'inDiffEditor', false)),
letterSpacing: register(new EditorFloatOption(46 /* letterSpacing */, 'letterSpacing', exports.EDITOR_FONT_DEFAULTS.letterSpacing, function (x) { return EditorFloatOption.clamp(x, -5, 20); }, { description: nls.localize(138, null) })),
lightbulb: register(new EditorLightbulb()),
lineDecorationsWidth: register(new SimpleEditorOption(48 /* lineDecorationsWidth */, 'lineDecorationsWidth', 10)),
lineHeight: register(new EditorLineHeight()),
lineNumbers: register(new EditorRenderLineNumbersOption()),
lineNumbersMinChars: register(new EditorIntOption(51 /* lineNumbersMinChars */, 'lineNumbersMinChars', 5, 1, 300)),
links: register(new EditorBooleanOption(52 /* links */, 'links', true, { description: nls.localize(139, null) })),
matchBrackets: register(new EditorStringEnumOption(53 /* matchBrackets */, 'matchBrackets', 'always', ['always', 'near', 'never'], { description: nls.localize(140, null) })),
minimap: register(new EditorMinimap()),
mouseStyle: register(new EditorStringEnumOption(55 /* mouseStyle */, 'mouseStyle', 'text', ['text', 'default', 'copy'])),
mouseWheelScrollSensitivity: register(new EditorFloatOption(56 /* mouseWheelScrollSensitivity */, 'mouseWheelScrollSensitivity', 1, function (x) { return (x === 0 ? 1 : x); }, { markdownDescription: nls.localize(141, null) })),
mouseWheelZoom: register(new EditorBooleanOption(57 /* mouseWheelZoom */, 'mouseWheelZoom', false, { markdownDescription: nls.localize(142, null) })),
multiCursorMergeOverlapping: register(new EditorBooleanOption(58 /* multiCursorMergeOverlapping */, 'multiCursorMergeOverlapping', true, { description: nls.localize(143, null) })),
multiCursorModifier: register(new EditorEnumOption(59 /* multiCursorModifier */, 'multiCursorModifier', 'altKey', 'alt', ['ctrlCmd', 'alt'], _multiCursorModifierFromString, {
markdownEnumDescriptions: [
nls.localize(144, null),
nls.localize(145, null)
],
markdownDescription: nls.localize(146, null)
})),
multiCursorPaste: register(new EditorStringEnumOption(60 /* multiCursorPaste */, 'multiCursorPaste', 'spread', ['spread', 'full'], {
markdownEnumDescriptions: [
nls.localize(147, null),
nls.localize(148, null)
],
markdownDescription: nls.localize(149, null)
})),
occurrencesHighlight: register(new EditorBooleanOption(61 /* occurrencesHighlight */, 'occurrencesHighlight', true, { description: nls.localize(150, null) })),
overviewRulerBorder: register(new EditorBooleanOption(62 /* overviewRulerBorder */, 'overviewRulerBorder', true, { description: nls.localize(151, null) })),
overviewRulerLanes: register(new EditorIntOption(63 /* overviewRulerLanes */, 'overviewRulerLanes', 3, 0, 3)),
parameterHints: register(new EditorParameterHints()),
peekWidgetDefaultFocus: register(new EditorStringEnumOption(65 /* peekWidgetDefaultFocus */, 'peekWidgetDefaultFocus', 'tree', ['tree', 'editor'], {
enumDescriptions: [
nls.localize(152, null),
nls.localize(153, null)
],
description: nls.localize(154, null)
})),
quickSuggestions: register(new EditorQuickSuggestions()),
quickSuggestionsDelay: register(new EditorIntOption(67 /* quickSuggestionsDelay */, 'quickSuggestionsDelay', 10, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(155, null) })),
readOnly: register(new EditorBooleanOption(68 /* readOnly */, 'readOnly', false)),
renderControlCharacters: register(new EditorBooleanOption(69 /* renderControlCharacters */, 'renderControlCharacters', false, { description: nls.localize(156, null) })),
renderIndentGuides: register(new EditorBooleanOption(70 /* renderIndentGuides */, 'renderIndentGuides', true, { description: nls.localize(157, null) })),
renderFinalNewline: register(new EditorBooleanOption(71 /* renderFinalNewline */, 'renderFinalNewline', true, { description: nls.localize(158, null) })),
renderLineHighlight: register(new EditorStringEnumOption(72 /* renderLineHighlight */, 'renderLineHighlight', 'line', ['none', 'gutter', 'line', 'all'], {
enumDescriptions: [
'',
'',
'',
nls.localize(159, null),
],
description: nls.localize(160, null)
})),
renderValidationDecorations: register(new EditorStringEnumOption(73 /* renderValidationDecorations */, 'renderValidationDecorations', 'editable', ['editable', 'on', 'off'])),
renderWhitespace: register(new EditorStringEnumOption(74 /* renderWhitespace */, 'renderWhitespace', 'none', ['none', 'boundary', 'selection', 'all'], {
enumDescriptions: [
'',
nls.localize(161, null),
nls.localize(162, null),
''
],
description: nls.localize(163, null)
})),
revealHorizontalRightPadding: register(new EditorIntOption(75 /* revealHorizontalRightPadding */, 'revealHorizontalRightPadding', 30, 0, 1000)),
roundedSelection: register(new EditorBooleanOption(76 /* roundedSelection */, 'roundedSelection', true, { description: nls.localize(164, null) })),
rulers: register(new EditorRulers()),
scrollbar: register(new EditorScrollbar()),
scrollBeyondLastColumn: register(new EditorIntOption(79 /* scrollBeyondLastColumn */, 'scrollBeyondLastColumn', 5, 0, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(165, null) })),
scrollBeyondLastLine: register(new EditorBooleanOption(80 /* scrollBeyondLastLine */, 'scrollBeyondLastLine', true, { description: nls.localize(166, null) })),
selectionClipboard: register(new EditorBooleanOption(81 /* selectionClipboard */, 'selectionClipboard', true, {
description: nls.localize(167, null),
included: platform.isLinux
})),
selectionHighlight: register(new EditorBooleanOption(82 /* selectionHighlight */, 'selectionHighlight', true, { description: nls.localize(168, null) })),
selectOnLineNumbers: register(new EditorBooleanOption(83 /* selectOnLineNumbers */, 'selectOnLineNumbers', true)),
showFoldingControls: register(new EditorStringEnumOption(84 /* showFoldingControls */, 'showFoldingControls', 'mouseover', ['always', 'mouseover'], { description: nls.localize(169, null) })),
showUnused: register(new EditorBooleanOption(85 /* showUnused */, 'showUnused', true, { description: nls.localize(170, null) })),
snippetSuggestions: register(new EditorStringEnumOption(86 /* snippetSuggestions */, 'snippetSuggestions', 'inline', ['top', 'bottom', 'inline', 'none'], {
enumDescriptions: [
nls.localize(171, null),
nls.localize(172, null),
nls.localize(173, null),
nls.localize(174, null),
],
description: nls.localize(175, null)
})),
smoothScrolling: register(new EditorBooleanOption(87 /* smoothScrolling */, 'smoothScrolling', false, { description: nls.localize(176, null) })),
stopRenderingLineAfter: register(new EditorIntOption(88 /* stopRenderingLineAfter */, 'stopRenderingLineAfter', 10000, -1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */)),
suggest: register(new EditorSuggest()),
suggestFontSize: register(new EditorIntOption(90 /* suggestFontSize */, 'suggestFontSize', 0, 0, 1000, { markdownDescription: nls.localize(177, null) })),
suggestLineHeight: register(new EditorIntOption(91 /* suggestLineHeight */, 'suggestLineHeight', 0, 0, 1000, { markdownDescription: nls.localize(178, null) })),
suggestOnTriggerCharacters: register(new EditorBooleanOption(92 /* suggestOnTriggerCharacters */, 'suggestOnTriggerCharacters', true, { description: nls.localize(179, null) })),
suggestSelection: register(new EditorStringEnumOption(93 /* suggestSelection */, 'suggestSelection', 'recentlyUsed', ['first', 'recentlyUsed', 'recentlyUsedByPrefix'], {
markdownEnumDescriptions: [
nls.localize(180, null),
nls.localize(181, null),
nls.localize(182, null),
],
description: nls.localize(183, null)
})),
tabCompletion: register(new EditorStringEnumOption(94 /* tabCompletion */, 'tabCompletion', 'off', ['on', 'off', 'onlySnippets'], {
enumDescriptions: [
nls.localize(184, null),
nls.localize(185, null),
nls.localize(186, null),
],
description: nls.localize(187, null)
})),
useTabStops: register(new EditorBooleanOption(95 /* useTabStops */, 'useTabStops', true, { description: nls.localize(188, null) })),
wordSeparators: register(new EditorStringOption(96 /* wordSeparators */, 'wordSeparators', wordHelper_1.USUAL_WORD_SEPARATORS, { description: nls.localize(189, null) })),
wordWrap: register(new EditorStringEnumOption(97 /* wordWrap */, 'wordWrap', 'off', ['off', 'on', 'wordWrapColumn', 'bounded'], {
markdownEnumDescriptions: [
nls.localize(190, null),
nls.localize(191, null),
nls.localize(192, null),
nls.localize(193, null),
],
description: nls.localize(194, null)
})),
wordWrapBreakAfterCharacters: register(new EditorStringOption(98 /* wordWrapBreakAfterCharacters */, 'wordWrapBreakAfterCharacters', ' \t})]?|/&.,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」')),
wordWrapBreakBeforeCharacters: register(new EditorStringOption(99 /* wordWrapBreakBeforeCharacters */, 'wordWrapBreakBeforeCharacters', '([{‘“〈《「『【〔([{「£¥$£¥++')),
wordWrapColumn: register(new EditorIntOption(100 /* wordWrapColumn */, 'wordWrapColumn', 80, 1, 1073741824 /* MAX_SAFE_SMALL_INTEGER */, {
markdownDescription: nls.localize(195, null)
})),
wordWrapMinified: register(new EditorBooleanOption(101 /* wordWrapMinified */, 'wordWrapMinified', true)),
wrappingIndent: register(new EditorEnumOption(102 /* wrappingIndent */, 'wrappingIndent', 1 /* Same */, 'same', ['none', 'same', 'indent', 'deepIndent'], _wrappingIndentFromString, {
enumDescriptions: [
nls.localize(196, null),
nls.localize(197, null),
nls.localize(198, null),
nls.localize(199, null),
],
description: nls.localize(200, null),
})),
wrappingStrategy: register(new EditorStringEnumOption(103 /* wrappingStrategy */, 'wrappingStrategy', 'simple', ['simple', 'advanced'], {
enumDescriptions: [
nls.localize(201, null),
nls.localize(202, null)
],
description: nls.localize(203, null)
})),
// Leave these at the end (because they have dependencies!)
editorClassName: register(new EditorClassName()),
pixelRatio: register(new EditorPixelRatio()),
tabFocusMode: register(new EditorTabFocusMode()),
layoutInfo: register(new EditorLayoutInfoComputer()),
wrappingInfo: register(new EditorWrappingInfoComputer())
};
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[424/*vs/editor/common/viewModel/viewModelDecorations*/], __M([0/*require*/,1/*exports*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,69/*vs/editor/common/viewModel/viewModel*/,33/*vs/editor/common/config/editorOptions*/]), function (require, exports, position_1, range_1, viewModel_1, editorOptions_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ViewModelDecorations = /** @class */ (function () {
function ViewModelDecorations(editorId, model, configuration, linesCollection, coordinatesConverter) {
this.editorId = editorId;
this.model = model;
this.configuration = configuration;
this._linesCollection = linesCollection;
this._coordinatesConverter = coordinatesConverter;
this._decorationsCache = Object.create(null);
this._cachedModelDecorationsResolver = null;
this._cachedModelDecorationsResolverViewRange = null;
}
ViewModelDecorations.prototype._clearCachedModelDecorationsResolver = function () {
this._cachedModelDecorationsResolver = null;
this._cachedModelDecorationsResolverViewRange = null;
};
ViewModelDecorations.prototype.dispose = function () {
this._decorationsCache = Object.create(null);
this._clearCachedModelDecorationsResolver();
};
ViewModelDecorations.prototype.reset = function () {
this._decorationsCache = Object.create(null);
this._clearCachedModelDecorationsResolver();
};
ViewModelDecorations.prototype.onModelDecorationsChanged = function () {
this._decorationsCache = Object.create(null);
this._clearCachedModelDecorationsResolver();
};
ViewModelDecorations.prototype.onLineMappingChanged = function () {
this._decorationsCache = Object.create(null);
this._clearCachedModelDecorationsResolver();
};
ViewModelDecorations.prototype._getOrCreateViewModelDecoration = function (modelDecoration) {
var id = modelDecoration.id;
var r = this._decorationsCache[id];
if (!r) {
var modelRange = modelDecoration.range;
var options = modelDecoration.options;
var viewRange = void 0;
if (options.isWholeLine) {
var start = this._coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.startLineNumber, 1));
var end = this._coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)));
viewRange = new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column);
}
else {
viewRange = this._coordinatesConverter.convertModelRangeToViewRange(modelRange);
}
r = new viewModel_1.ViewModelDecoration(viewRange, options);
this._decorationsCache[id] = r;
}
return r;
};
ViewModelDecorations.prototype.getDecorationsViewportData = function (viewRange) {
var cacheIsValid = (this._cachedModelDecorationsResolver !== null);
cacheIsValid = cacheIsValid && (viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange));
if (!cacheIsValid) {
this._cachedModelDecorationsResolver = this._getDecorationsViewportData(viewRange);
this._cachedModelDecorationsResolverViewRange = viewRange;
}
return this._cachedModelDecorationsResolver;
};
ViewModelDecorations.prototype._getDecorationsViewportData = function (viewportRange) {
var modelDecorations = this._linesCollection.getDecorationsInRange(viewportRange, this.editorId, editorOptions_1.filterValidationDecorations(this.configuration.options));
var startLineNumber = viewportRange.startLineNumber;
var endLineNumber = viewportRange.endLineNumber;
var decorationsInViewport = [], decorationsInViewportLen = 0;
var inlineDecorations = [];
for (var j = startLineNumber; j <= endLineNumber; j++) {
inlineDecorations[j - startLineNumber] = [];
}
for (var i = 0, len = modelDecorations.length; i < len; i++) {
var modelDecoration = modelDecorations[i];
var decorationOptions = modelDecoration.options;
var viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);
var viewRange = viewModelDecoration.range;
decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;
if (decorationOptions.inlineClassName) {
var inlineDecoration = new viewModel_1.InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */);
var intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber);
var intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber);
for (var j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) {
inlineDecorations[j - startLineNumber].push(inlineDecoration);
}
}
if (decorationOptions.beforeContentClassName) {
if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) {
var inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn), decorationOptions.beforeContentClassName, 1 /* Before */);
inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration);
}
}
if (decorationOptions.afterContentClassName) {
if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber) {
var inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.endLineNumber, viewRange.endColumn, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, 2 /* After */);
inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration);
}
}
}
return {
decorations: decorationsInViewport,
inlineDecorations: inlineDecorations
};
};
return ViewModelDecorations;
}());
exports.ViewModelDecorations = ViewModelDecorations;
});
define(__m[425/*vs/nls!vs/editor/common/modes/modesRegistry*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/modes/modesRegistry", data); });
define(__m[426/*vs/nls!vs/editor/common/standaloneStrings*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/standaloneStrings", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[59/*vs/editor/common/standaloneStrings*/], __M([0/*require*/,1/*exports*/,426/*vs/nls!vs/editor/common/standaloneStrings*/]), function (require, exports, nls) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var AccessibilityHelpNLS;
(function (AccessibilityHelpNLS) {
AccessibilityHelpNLS.noSelection = nls.localize(0, null);
AccessibilityHelpNLS.singleSelectionRange = nls.localize(1, null);
AccessibilityHelpNLS.singleSelection = nls.localize(2, null);
AccessibilityHelpNLS.multiSelectionRange = nls.localize(3, null);
AccessibilityHelpNLS.multiSelection = nls.localize(4, null);
AccessibilityHelpNLS.emergencyConfOn = nls.localize(5, null);
AccessibilityHelpNLS.openingDocs = nls.localize(6, null);
AccessibilityHelpNLS.readonlyDiffEditor = nls.localize(7, null);
AccessibilityHelpNLS.editableDiffEditor = nls.localize(8, null);
AccessibilityHelpNLS.readonlyEditor = nls.localize(9, null);
AccessibilityHelpNLS.editableEditor = nls.localize(10, null);
AccessibilityHelpNLS.changeConfigToOnMac = nls.localize(11, null);
AccessibilityHelpNLS.changeConfigToOnWinLinux = nls.localize(12, null);
AccessibilityHelpNLS.auto_on = nls.localize(13, null);
AccessibilityHelpNLS.auto_off = nls.localize(14, null);
AccessibilityHelpNLS.tabFocusModeOnMsg = nls.localize(15, null);
AccessibilityHelpNLS.tabFocusModeOnMsgNoKb = nls.localize(16, null);
AccessibilityHelpNLS.tabFocusModeOffMsg = nls.localize(17, null);
AccessibilityHelpNLS.tabFocusModeOffMsgNoKb = nls.localize(18, null);
AccessibilityHelpNLS.openDocMac = nls.localize(19, null);
AccessibilityHelpNLS.openDocWinLinux = nls.localize(20, null);
AccessibilityHelpNLS.outroMsg = nls.localize(21, null);
AccessibilityHelpNLS.showAccessibilityHelpAction = nls.localize(22, null);
})(AccessibilityHelpNLS = exports.AccessibilityHelpNLS || (exports.AccessibilityHelpNLS = {}));
var InspectTokensNLS;
(function (InspectTokensNLS) {
InspectTokensNLS.inspectTokensAction = nls.localize(23, null);
})(InspectTokensNLS = exports.InspectTokensNLS || (exports.InspectTokensNLS = {}));
var GoToLineNLS;
(function (GoToLineNLS) {
GoToLineNLS.gotoLineLabelValidLineAndColumn = nls.localize(24, null);
GoToLineNLS.gotoLineLabelValidLine = nls.localize(25, null);
GoToLineNLS.gotoLineLabelEmptyWithLineLimit = nls.localize(26, null);
GoToLineNLS.gotoLineLabelEmptyWithLineAndColumnLimit = nls.localize(27, null);
GoToLineNLS.gotoLineAriaLabel = nls.localize(28, null);
GoToLineNLS.gotoLineActionInput = nls.localize(29, null);
GoToLineNLS.gotoLineActionLabel = nls.localize(30, null);
})(GoToLineNLS = exports.GoToLineNLS || (exports.GoToLineNLS = {}));
var QuickCommandNLS;
(function (QuickCommandNLS) {
QuickCommandNLS.ariaLabelEntryWithKey = nls.localize(31, null);
QuickCommandNLS.ariaLabelEntry = nls.localize(32, null);
QuickCommandNLS.quickCommandActionInput = nls.localize(33, null);
QuickCommandNLS.quickCommandActionLabel = nls.localize(34, null);
})(QuickCommandNLS = exports.QuickCommandNLS || (exports.QuickCommandNLS = {}));
var QuickOutlineNLS;
(function (QuickOutlineNLS) {
QuickOutlineNLS.entryAriaLabel = nls.localize(35, null);
QuickOutlineNLS.quickOutlineActionInput = nls.localize(36, null);
QuickOutlineNLS.quickOutlineActionLabel = nls.localize(37, null);
QuickOutlineNLS._symbols_ = nls.localize(38, null);
QuickOutlineNLS._modules_ = nls.localize(39, null);
QuickOutlineNLS._class_ = nls.localize(40, null);
QuickOutlineNLS._interface_ = nls.localize(41, null);
QuickOutlineNLS._method_ = nls.localize(42, null);
QuickOutlineNLS._function_ = nls.localize(43, null);
QuickOutlineNLS._property_ = nls.localize(44, null);
QuickOutlineNLS._variable_ = nls.localize(45, null);
QuickOutlineNLS._variable2_ = nls.localize(46, null);
QuickOutlineNLS._constructor_ = nls.localize(47, null);
QuickOutlineNLS._call_ = nls.localize(48, null);
})(QuickOutlineNLS = exports.QuickOutlineNLS || (exports.QuickOutlineNLS = {}));
var StandaloneCodeEditorNLS;
(function (StandaloneCodeEditorNLS) {
StandaloneCodeEditorNLS.editorViewAccessibleLabel = nls.localize(49, null);
StandaloneCodeEditorNLS.accessibilityHelpMessageIE = nls.localize(50, null);
StandaloneCodeEditorNLS.accessibilityHelpMessage = nls.localize(51, null);
})(StandaloneCodeEditorNLS = exports.StandaloneCodeEditorNLS || (exports.StandaloneCodeEditorNLS = {}));
var ToggleHighContrastNLS;
(function (ToggleHighContrastNLS) {
ToggleHighContrastNLS.toggleHighContrast = nls.localize(52, null);
})(ToggleHighContrastNLS = exports.ToggleHighContrastNLS || (exports.ToggleHighContrastNLS = {}));
var SimpleServicesNLS;
(function (SimpleServicesNLS) {
SimpleServicesNLS.bulkEditServiceSummary = nls.localize(53, null);
})(SimpleServicesNLS = exports.SimpleServicesNLS || (exports.SimpleServicesNLS = {}));
});
define(__m[427/*vs/nls!vs/editor/common/view/editorColorRegistry*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/common/view/editorColorRegistry", data); });
define(__m[428/*vs/nls!vs/editor/contrib/bracketMatching/bracketMatching*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/bracketMatching/bracketMatching", data); });
define(__m[429/*vs/nls!vs/editor/contrib/caretOperations/caretOperations*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/caretOperations", data); });
define(__m[430/*vs/nls!vs/editor/contrib/caretOperations/transpose*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/caretOperations/transpose", data); });
define(__m[431/*vs/nls!vs/editor/contrib/clipboard/clipboard*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/clipboard/clipboard", data); });
define(__m[432/*vs/nls!vs/editor/contrib/codeAction/codeActionCommands*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/codeActionCommands", data); });
define(__m[433/*vs/nls!vs/editor/contrib/codeAction/lightBulbWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/codeAction/lightBulbWidget", data); });
define(__m[434/*vs/nls!vs/editor/contrib/comment/comment*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/comment/comment", data); });
define(__m[435/*vs/nls!vs/editor/contrib/contextmenu/contextmenu*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/contextmenu/contextmenu", data); });
define(__m[436/*vs/nls!vs/editor/contrib/cursorUndo/cursorUndo*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/cursorUndo/cursorUndo", data); });
define(__m[437/*vs/nls!vs/editor/contrib/documentSymbols/outlineTree*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/documentSymbols/outlineTree", data); });
define(__m[438/*vs/nls!vs/editor/contrib/find/findController*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findController", data); });
define(__m[439/*vs/nls!vs/editor/contrib/find/findWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/find/findWidget", data); });
define(__m[440/*vs/nls!vs/editor/contrib/folding/folding*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/folding/folding", data); });
define(__m[441/*vs/nls!vs/editor/contrib/fontZoom/fontZoom*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/fontZoom/fontZoom", data); });
define(__m[442/*vs/nls!vs/editor/contrib/format/format*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/format", data); });
define(__m[443/*vs/nls!vs/editor/contrib/format/formatActions*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/format/formatActions", data); });
define(__m[444/*vs/nls!vs/editor/contrib/gotoError/gotoError*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoError", data); });
define(__m[445/*vs/nls!vs/editor/contrib/gotoError/gotoErrorWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoError/gotoErrorWidget", data); });
define(__m[446/*vs/nls!vs/editor/contrib/gotoSymbol/goToCommands*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/goToCommands", data); });
define(__m[447/*vs/nls!vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition", data); });
define(__m[448/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesController*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesController", data); });
define(__m[449/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesTree*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesTree", data); });
define(__m[450/*vs/nls!vs/editor/contrib/gotoSymbol/peek/referencesWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/peek/referencesWidget", data); });
define(__m[451/*vs/nls!vs/editor/contrib/gotoSymbol/referencesModel*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/referencesModel", data); });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[113/*vs/editor/contrib/gotoSymbol/referencesModel*/], __M([0/*require*/,1/*exports*/,451/*vs/nls!vs/editor/contrib/gotoSymbol/referencesModel*/,4/*vs/base/common/event*/,39/*vs/base/common/resources*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,127/*vs/base/common/idGenerator*/,3/*vs/editor/common/core/range*/]), function (require, exports, nls_1, event_1, resources_1, lifecycle_1, strings, idGenerator_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var OneReference = /** @class */ (function () {
function OneReference(isProviderFirst, parent, _range, _rangeCallback) {
this.isProviderFirst = isProviderFirst;
this.parent = parent;
this._range = _range;
this._rangeCallback = _rangeCallback;
this.id = idGenerator_1.defaultGenerator.nextId();
}
Object.defineProperty(OneReference.prototype, "uri", {
get: function () {
return this.parent.uri;
},
enumerable: true,
configurable: true
});
Object.defineProperty(OneReference.prototype, "range", {
get: function () {
return this._range;
},
set: function (value) {
this._range = value;
this._rangeCallback(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(OneReference.prototype, "ariaMessage", {
get: function () {
return nls_1.localize(0, null, resources_1.basename(this.uri), this.range.startLineNumber, this.range.startColumn);
},
enumerable: true,
configurable: true
});
return OneReference;
}());
exports.OneReference = OneReference;
var FilePreview = /** @class */ (function () {
function FilePreview(_modelReference) {
this._modelReference = _modelReference;
}
FilePreview.prototype.dispose = function () {
this._modelReference.dispose();
};
FilePreview.prototype.preview = function (range, n) {
if (n === void 0) { n = 8; }
var model = this._modelReference.object.textEditorModel;
if (!model) {
return undefined;
}
var startLineNumber = range.startLineNumber, startColumn = range.startColumn, endLineNumber = range.endLineNumber, endColumn = range.endColumn;
var word = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n });
var beforeRange = new range_1.Range(startLineNumber, word.startColumn, startLineNumber, startColumn);
var afterRange = new range_1.Range(endLineNumber, endColumn, endLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */);
var before = model.getValueInRange(beforeRange).replace(/^\s+/, '');
var inside = model.getValueInRange(range);
var after = model.getValueInRange(afterRange).replace(/\s+$/, '');
return {
value: before + inside + after,
highlight: { start: before.length, end: before.length + inside.length }
};
};
return FilePreview;
}());
exports.FilePreview = FilePreview;
var FileReferences = /** @class */ (function () {
function FileReferences(parent, uri) {
this.parent = parent;
this.uri = uri;
this.children = [];
}
FileReferences.prototype.dispose = function () {
lifecycle_1.dispose(this._preview);
this._preview = undefined;
};
Object.defineProperty(FileReferences.prototype, "preview", {
get: function () {
return this._preview;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FileReferences.prototype, "failure", {
get: function () {
return this._loadFailure;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FileReferences.prototype, "ariaMessage", {
get: function () {
var len = this.children.length;
if (len === 1) {
return nls_1.localize(1, null, resources_1.basename(this.uri), this.uri.fsPath);
}
else {
return nls_1.localize(2, null, len, resources_1.basename(this.uri), this.uri.fsPath);
}
},
enumerable: true,
configurable: true
});
FileReferences.prototype.resolve = function (textModelResolverService) {
var _this = this;
if (this._resolved) {
return Promise.resolve(this);
}
return Promise.resolve(textModelResolverService.createModelReference(this.uri).then(function (modelReference) {
var model = modelReference.object;
if (!model) {
modelReference.dispose();
throw new Error();
}
_this._preview = new FilePreview(modelReference);
_this._resolved = true;
return _this;
}, function (err) {
// something wrong here
_this.children.length = 0;
_this._resolved = true;
_this._loadFailure = err;
return _this;
}));
};
return FileReferences;
}());
exports.FileReferences = FileReferences;
var ReferencesModel = /** @class */ (function () {
function ReferencesModel(links, title) {
var _this = this;
this._disposables = new lifecycle_1.DisposableStore();
this.groups = [];
this.references = [];
this._onDidChangeReferenceRange = new event_1.Emitter();
this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event;
this._links = links;
this._title = title;
// grouping and sorting
var providersFirst = links[0];
links.sort(ReferencesModel._compareReferences);
var current;
for (var _i = 0, links_1 = links; _i < links_1.length; _i++) {
var link = links_1[_i];
if (!current || current.uri.toString() !== link.uri.toString()) {
// new group
current = new FileReferences(this, link.uri);
this.groups.push(current);
}
// append, check for equality first!
if (current.children.length === 0 || !range_1.Range.equalsRange(link.range, current.children[current.children.length - 1].range)) {
var oneRef = new OneReference(providersFirst === link, current, link.targetSelectionRange || link.range, function (ref) { return _this._onDidChangeReferenceRange.fire(ref); });
this.references.push(oneRef);
current.children.push(oneRef);
}
}
}
ReferencesModel.prototype.dispose = function () {
lifecycle_1.dispose(this.groups);
this._disposables.dispose();
this._onDidChangeReferenceRange.dispose();
this.groups.length = 0;
};
ReferencesModel.prototype.clone = function () {
return new ReferencesModel(this._links, this._title);
};
Object.defineProperty(ReferencesModel.prototype, "title", {
get: function () {
return this._title;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ReferencesModel.prototype, "isEmpty", {
get: function () {
return this.groups.length === 0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ReferencesModel.prototype, "ariaMessage", {
get: function () {
if (this.isEmpty) {
return nls_1.localize(3, null);
}
else if (this.references.length === 1) {
return nls_1.localize(4, null, this.references[0].uri.fsPath);
}
else if (this.groups.length === 1) {
return nls_1.localize(5, null, this.references.length, this.groups[0].uri.fsPath);
}
else {
return nls_1.localize(6, null, this.references.length, this.groups.length);
}
},
enumerable: true,
configurable: true
});
ReferencesModel.prototype.nextOrPreviousReference = function (reference, next) {
var parent = reference.parent;
var idx = parent.children.indexOf(reference);
var childCount = parent.children.length;
var groupCount = parent.parent.groups.length;
if (groupCount === 1 || next && idx + 1 < childCount || !next && idx > 0) {
// cycling within one file
if (next) {
idx = (idx + 1) % childCount;
}
else {
idx = (idx + childCount - 1) % childCount;
}
return parent.children[idx];
}
idx = parent.parent.groups.indexOf(parent);
if (next) {
idx = (idx + 1) % groupCount;
return parent.parent.groups[idx].children[0];
}
else {
idx = (idx + groupCount - 1) % groupCount;
return parent.parent.groups[idx].children[parent.parent.groups[idx].children.length - 1];
}
};
ReferencesModel.prototype.nearestReference = function (resource, position) {
var nearest = this.references.map(function (ref, idx) {
return {
idx: idx,
prefixLen: strings.commonPrefixLength(ref.uri.toString(), resource.toString()),
offsetDist: Math.abs(ref.range.startLineNumber - position.lineNumber) * 100 + Math.abs(ref.range.startColumn - position.column)
};
}).sort(function (a, b) {
if (a.prefixLen > b.prefixLen) {
return -1;
}
else if (a.prefixLen < b.prefixLen) {
return 1;
}
else if (a.offsetDist < b.offsetDist) {
return -1;
}
else if (a.offsetDist > b.offsetDist) {
return 1;
}
else {
return 0;
}
})[0];
if (nearest) {
return this.references[nearest.idx];
}
return undefined;
};
ReferencesModel.prototype.referenceAt = function (resource, position) {
for (var _i = 0, _a = this.references; _i < _a.length; _i++) {
var ref = _a[_i];
if (ref.uri.toString() === resource.toString()) {
if (range_1.Range.containsPosition(ref.range, position)) {
return ref;
}
}
}
return undefined;
};
ReferencesModel.prototype.firstReference = function () {
for (var _i = 0, _a = this.references; _i < _a.length; _i++) {
var ref = _a[_i];
if (ref.isProviderFirst) {
return ref;
}
}
return this.references[0];
};
ReferencesModel._compareReferences = function (a, b) {
return strings.compare(a.uri.toString(), b.uri.toString()) || range_1.Range.compareRangesUsingStarts(a.range, b.range);
};
return ReferencesModel;
}());
exports.ReferencesModel = ReferencesModel;
});
define(__m[452/*vs/nls!vs/editor/contrib/gotoSymbol/symbolNavigation*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/gotoSymbol/symbolNavigation", data); });
define(__m[453/*vs/nls!vs/editor/contrib/hover/hover*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/hover", data); });
define(__m[454/*vs/nls!vs/editor/contrib/hover/modesContentHover*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/hover/modesContentHover", data); });
define(__m[455/*vs/nls!vs/editor/contrib/inPlaceReplace/inPlaceReplace*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/inPlaceReplace/inPlaceReplace", data); });
define(__m[456/*vs/nls!vs/editor/contrib/linesOperations/linesOperations*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/linesOperations/linesOperations", data); });
define(__m[457/*vs/nls!vs/editor/contrib/links/links*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/links/links", data); });
define(__m[458/*vs/nls!vs/editor/contrib/message/messageController*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/message/messageController", data); });
define(__m[459/*vs/nls!vs/editor/contrib/multicursor/multicursor*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/multicursor/multicursor", data); });
define(__m[460/*vs/nls!vs/editor/contrib/parameterHints/parameterHints*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHints", data); });
define(__m[461/*vs/nls!vs/editor/contrib/parameterHints/parameterHintsWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/parameterHints/parameterHintsWidget", data); });
define(__m[462/*vs/nls!vs/editor/contrib/peekView/peekView*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/peekView/peekView", data); });
define(__m[463/*vs/nls!vs/editor/contrib/rename/rename*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/rename", data); });
define(__m[464/*vs/nls!vs/editor/contrib/rename/renameInputField*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/rename/renameInputField", data); });
define(__m[465/*vs/nls!vs/editor/contrib/smartSelect/smartSelect*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/smartSelect/smartSelect", data); });
define(__m[466/*vs/nls!vs/editor/contrib/snippet/snippetVariables*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/snippet/snippetVariables", data); });
define(__m[467/*vs/nls!vs/editor/contrib/suggest/suggestController*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestController", data); });
define(__m[468/*vs/nls!vs/editor/contrib/suggest/suggestWidget*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/suggest/suggestWidget", data); });
define(__m[469/*vs/nls!vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode", data); });
define(__m[470/*vs/nls!vs/editor/contrib/tokenization/tokenization*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/tokenization/tokenization", data); });
define(__m[471/*vs/nls!vs/editor/contrib/wordHighlighter/wordHighlighter*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/editor/contrib/wordHighlighter/wordHighlighter", data); });
define(__m[472/*vs/nls!vs/platform/configuration/common/configurationRegistry*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/configuration/common/configurationRegistry", data); });
define(__m[473/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/keybinding/common/abstractKeybindingService", data); });
define(__m[474/*vs/nls!vs/platform/list/browser/listService*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/list/browser/listService", data); });
define(__m[475/*vs/nls!vs/platform/markers/common/markers*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/markers/common/markers", data); });
define(__m[476/*vs/nls!vs/platform/theme/common/colorRegistry*/], __M([7/*vs/nls*/,8/*vs/nls!vs/editor/editor.main*/]), function(nls, data) { return nls.create("vs/platform/theme/common/colorRegistry", data); });
define(__m[477/*vs/platform/contextkey/common/contextkeys*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InputFocusedContextKey = 'inputFocus';
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[478/*vs/platform/editor/common/editor*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var EditorOpenContext;
(function (EditorOpenContext) {
/**
* Default: the editor is opening via a programmatic call
* to the editor service API.
*/
EditorOpenContext[EditorOpenContext["API"] = 0] = "API";
/**
* Indicates that a user action triggered the opening, e.g.
* via mouse or keyboard use.
*/
EditorOpenContext[EditorOpenContext["USER"] = 1] = "USER";
})(EditorOpenContext = exports.EditorOpenContext || (exports.EditorOpenContext = {}));
});
define(__m[479/*vs/platform/extensions/common/extensions*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* **!Do not construct directly!**
*
* **!Only static methods because it gets serialized!**
*
* This represents the "canonical" version for an extension identifier. Extension ids
* have to be case-insensitive (due to the marketplace), but we must ensure case
* preservation because the extension API is already public at this time.
*
* For example, given an extension with the publisher `"Hello"` and the name `"World"`,
* its canonical extension identifier is `"Hello.World"`. This extension could be
* referenced in some other extension's dependencies using the string `"hello.world"`.
*
* To make matters more complicated, an extension can optionally have an UUID. When two
* extensions have the same UUID, they are considered equal even if their identifier is different.
*/
var ExtensionIdentifier = /** @class */ (function () {
function ExtensionIdentifier(value) {
this.value = value;
this._lower = value.toLowerCase();
}
/**
* Gives the value by which to index (for equality).
*/
ExtensionIdentifier.toKey = function (id) {
if (typeof id === 'string') {
return id.toLowerCase();
}
return id._lower;
};
return ExtensionIdentifier;
}());
exports.ExtensionIdentifier = ExtensionIdentifier;
});
define(__m[208/*vs/platform/files/common/files*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FileKind;
(function (FileKind) {
FileKind[FileKind["FILE"] = 0] = "FILE";
FileKind[FileKind["FOLDER"] = 1] = "FOLDER";
FileKind[FileKind["ROOT_FOLDER"] = 2] = "ROOT_FOLDER";
})(FileKind = exports.FileKind || (exports.FileKind = {}));
});
define(__m[209/*vs/platform/instantiation/common/descriptors*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SyncDescriptor = /** @class */ (function () {
function SyncDescriptor(ctor, staticArguments, supportsDelayedInstantiation) {
if (staticArguments === void 0) { staticArguments = []; }
if (supportsDelayedInstantiation === void 0) { supportsDelayedInstantiation = false; }
this.ctor = ctor;
this.staticArguments = staticArguments;
this.supportsDelayedInstantiation = supportsDelayedInstantiation;
}
return SyncDescriptor;
}());
exports.SyncDescriptor = SyncDescriptor;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[83/*vs/platform/instantiation/common/extensions*/], __M([0/*require*/,1/*exports*/,209/*vs/platform/instantiation/common/descriptors*/]), function (require, exports, descriptors_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var _registry = [];
function registerSingleton(id, ctor, supportsDelayedInstantiation) {
_registry.push([id, new descriptors_1.SyncDescriptor(ctor, [], supportsDelayedInstantiation)]);
}
exports.registerSingleton = registerSingleton;
function getSingletonServiceDescriptors() {
return _registry;
}
exports.getSingletonServiceDescriptors = getSingletonServiceDescriptors;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[480/*vs/platform/instantiation/common/graph*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/,87/*vs/base/common/collections*/]), function (require, exports, types_1, collections_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function newNode(data) {
return {
data: data,
incoming: Object.create(null),
outgoing: Object.create(null)
};
}
var Graph = /** @class */ (function () {
function Graph(_hashFn) {
this._hashFn = _hashFn;
this._nodes = Object.create(null);
// empty
}
Graph.prototype.roots = function () {
var ret = [];
collections_1.forEach(this._nodes, function (entry) {
if (types_1.isEmptyObject(entry.value.outgoing)) {
ret.push(entry.value);
}
});
return ret;
};
Graph.prototype.insertEdge = function (from, to) {
var fromNode = this.lookupOrInsertNode(from), toNode = this.lookupOrInsertNode(to);
fromNode.outgoing[this._hashFn(to)] = toNode;
toNode.incoming[this._hashFn(from)] = fromNode;
};
Graph.prototype.removeNode = function (data) {
var key = this._hashFn(data);
delete this._nodes[key];
collections_1.forEach(this._nodes, function (entry) {
delete entry.value.outgoing[key];
delete entry.value.incoming[key];
});
};
Graph.prototype.lookupOrInsertNode = function (data) {
var key = this._hashFn(data);
var node = this._nodes[key];
if (!node) {
node = newNode(data);
this._nodes[key] = node;
}
return node;
};
Graph.prototype.isEmpty = function () {
for (var _key in this._nodes) {
return false;
}
return true;
};
Graph.prototype.toString = function () {
var data = [];
collections_1.forEach(this._nodes, function (entry) {
data.push(entry.key + ", (incoming)[" + Object.keys(entry.value.incoming).join(', ') + "], (outgoing)[" + Object.keys(entry.value.outgoing).join(',') + "]");
});
return data.join('\n');
};
return Graph;
}());
exports.Graph = Graph;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[11/*vs/platform/instantiation/common/instantiation*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// ------ internal util
var _util;
(function (_util) {
_util.serviceIds = new Map();
_util.DI_TARGET = '$di$target';
_util.DI_DEPENDENCIES = '$di$dependencies';
function getServiceDependencies(ctor) {
return ctor[_util.DI_DEPENDENCIES] || [];
}
_util.getServiceDependencies = getServiceDependencies;
})(_util = exports._util || (exports._util = {}));
exports.IInstantiationService = createDecorator('instantiationService');
function storeServiceDependency(id, target, index, optional) {
if (target[_util.DI_TARGET] === target) {
target[_util.DI_DEPENDENCIES].push({ id: id, index: index, optional: optional });
}
else {
target[_util.DI_DEPENDENCIES] = [{ id: id, index: index, optional: optional }];
target[_util.DI_TARGET] = target;
}
}
/**
* A *only* valid way to create a {{ServiceIdentifier}}.
*/
function createDecorator(serviceId) {
if (_util.serviceIds.has(serviceId)) {
return _util.serviceIds.get(serviceId);
}
var id = function (target, key, index) {
if (arguments.length !== 3) {
throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
}
storeServiceDependency(id, target, index, false);
};
id.toString = function () { return serviceId; };
_util.serviceIds.set(serviceId, id);
return id;
}
exports.createDecorator = createDecorator;
/**
* Mark a service dependency as optional.
*/
function optional(serviceIdentifier) {
return function (target, key, index) {
if (arguments.length !== 3) {
throw new Error('@optional-decorator can only be used to decorate a parameter');
}
storeServiceDependency(serviceIdentifier, target, index, true);
};
}
exports.optional = optional;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[156/*vs/editor/browser/services/bulkEditService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IBulkEditService = instantiation_1.createDecorator('IWorkspaceEditService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[32/*vs/editor/browser/services/codeEditorService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ICodeEditorService = instantiation_1.createDecorator('codeEditorService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[62/*vs/editor/common/services/editorWorkerService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ID_EDITOR_WORKER_SERVICE = 'editorWorkerService';
exports.IEditorWorkerService = instantiation_1.createDecorator(exports.ID_EDITOR_WORKER_SERVICE);
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[210/*vs/editor/common/services/markersDecorationService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IMarkerDecorationsService = instantiation_1.createDecorator('markerDecorationsService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[71/*vs/editor/common/services/modeService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IModeService = instantiation_1.createDecorator('modeService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[49/*vs/editor/common/services/modelService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IModelService = instantiation_1.createDecorator('modelService');
function shouldSynchronizeModel(model) {
return (!model.isTooLargeForSyncing() && !model.isForSimpleWidget);
}
exports.shouldSynchronizeModel = shouldSynchronizeModel;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[481/*vs/editor/common/modes/languageFeatureRegistry*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,350/*vs/editor/common/modes/languageSelector*/,49/*vs/editor/common/services/modelService*/]), function (require, exports, event_1, lifecycle_1, languageSelector_1, modelService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function isExclusive(selector) {
if (typeof selector === 'string') {
return false;
}
else if (Array.isArray(selector)) {
return selector.every(isExclusive);
}
else {
return !!selector.exclusive;
}
}
var LanguageFeatureRegistry = /** @class */ (function () {
function LanguageFeatureRegistry() {
this._clock = 0;
this._entries = [];
this._onDidChange = new event_1.Emitter();
}
Object.defineProperty(LanguageFeatureRegistry.prototype, "onDidChange", {
get: function () {
return this._onDidChange.event;
},
enumerable: true,
configurable: true
});
LanguageFeatureRegistry.prototype.register = function (selector, provider) {
var _this = this;
var entry = {
selector: selector,
provider: provider,
_score: -1,
_time: this._clock++
};
this._entries.push(entry);
this._lastCandidate = undefined;
this._onDidChange.fire(this._entries.length);
return lifecycle_1.toDisposable(function () {
if (entry) {
var idx = _this._entries.indexOf(entry);
if (idx >= 0) {
_this._entries.splice(idx, 1);
_this._lastCandidate = undefined;
_this._onDidChange.fire(_this._entries.length);
entry = undefined;
}
}
});
};
LanguageFeatureRegistry.prototype.has = function (model) {
return this.all(model).length > 0;
};
LanguageFeatureRegistry.prototype.all = function (model) {
if (!model) {
return [];
}
this._updateScores(model);
var result = [];
// from registry
for (var _i = 0, _a = this._entries; _i < _a.length; _i++) {
var entry = _a[_i];
if (entry._score > 0) {
result.push(entry.provider);
}
}
return result;
};
LanguageFeatureRegistry.prototype.ordered = function (model) {
var result = [];
this._orderedForEach(model, function (entry) { return result.push(entry.provider); });
return result;
};
LanguageFeatureRegistry.prototype.orderedGroups = function (model) {
var result = [];
var lastBucket;
var lastBucketScore;
this._orderedForEach(model, function (entry) {
if (lastBucket && lastBucketScore === entry._score) {
lastBucket.push(entry.provider);
}
else {
lastBucketScore = entry._score;
lastBucket = [entry.provider];
result.push(lastBucket);
}
});
return result;
};
LanguageFeatureRegistry.prototype._orderedForEach = function (model, callback) {
if (!model) {
return;
}
this._updateScores(model);
for (var _i = 0, _a = this._entries; _i < _a.length; _i++) {
var entry = _a[_i];
if (entry._score > 0) {
callback(entry);
}
}
};
LanguageFeatureRegistry.prototype._updateScores = function (model) {
var candidate = {
uri: model.uri.toString(),
language: model.getLanguageIdentifier().language
};
if (this._lastCandidate
&& this._lastCandidate.language === candidate.language
&& this._lastCandidate.uri === candidate.uri) {
// nothing has changed
return;
}
this._lastCandidate = candidate;
for (var _i = 0, _a = this._entries; _i < _a.length; _i++) {
var entry = _a[_i];
entry._score = languageSelector_1.score(entry.selector, model.uri, model.getLanguageIdentifier().language, modelService_1.shouldSynchronizeModel(model));
if (isExclusive(entry.selector) && entry._score > 0) {
// support for one exclusive selector that overwrites
// any other selector
for (var _b = 0, _c = this._entries; _b < _c.length; _b++) {
var entry_1 = _c[_b];
entry_1._score = 0;
}
entry._score = 1000;
break;
}
}
// needs sorting
this._entries.sort(LanguageFeatureRegistry._compareByScoreAndTime);
};
LanguageFeatureRegistry._compareByScoreAndTime = function (a, b) {
if (a._score < b._score) {
return 1;
}
else if (a._score > b._score) {
return -1;
}
else if (a._time < b._time) {
return 1;
}
else if (a._time > b._time) {
return -1;
}
else {
return 0;
}
};
return LanguageFeatureRegistry;
}());
exports.LanguageFeatureRegistry = LanguageFeatureRegistry;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[17/*vs/editor/common/modes*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,481/*vs/editor/common/modes/languageFeatureRegistry*/,358/*vs/editor/common/modes/tokenizationRegistry*/]), function (require, exports, types_1, uri_1, range_1, languageFeatureRegistry_1, tokenizationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @internal
*/
var LanguageIdentifier = /** @class */ (function () {
function LanguageIdentifier(language, id) {
this.language = language;
this.id = id;
}
return LanguageIdentifier;
}());
exports.LanguageIdentifier = LanguageIdentifier;
/**
* @internal
*/
var TokenMetadata = /** @class */ (function () {
function TokenMetadata() {
}
TokenMetadata.getLanguageId = function (metadata) {
return (metadata & 255 /* LANGUAGEID_MASK */) >>> 0 /* LANGUAGEID_OFFSET */;
};
TokenMetadata.getTokenType = function (metadata) {
return (metadata & 1792 /* TOKEN_TYPE_MASK */) >>> 8 /* TOKEN_TYPE_OFFSET */;
};
TokenMetadata.getFontStyle = function (metadata) {
return (metadata & 14336 /* FONT_STYLE_MASK */) >>> 11 /* FONT_STYLE_OFFSET */;
};
TokenMetadata.getForeground = function (metadata) {
return (metadata & 8372224 /* FOREGROUND_MASK */) >>> 14 /* FOREGROUND_OFFSET */;
};
TokenMetadata.getBackground = function (metadata) {
return (metadata & 4286578688 /* BACKGROUND_MASK */) >>> 23 /* BACKGROUND_OFFSET */;
};
TokenMetadata.getClassNameFromMetadata = function (metadata) {
var foreground = this.getForeground(metadata);
var className = 'mtk' + foreground;
var fontStyle = this.getFontStyle(metadata);
if (fontStyle & 1 /* Italic */) {
className += ' mtki';
}
if (fontStyle & 2 /* Bold */) {
className += ' mtkb';
}
if (fontStyle & 4 /* Underline */) {
className += ' mtku';
}
return className;
};
TokenMetadata.getInlineStyleFromMetadata = function (metadata, colorMap) {
var foreground = this.getForeground(metadata);
var fontStyle = this.getFontStyle(metadata);
var result = "color: " + colorMap[foreground] + ";";
if (fontStyle & 1 /* Italic */) {
result += 'font-style: italic;';
}
if (fontStyle & 2 /* Bold */) {
result += 'font-weight: bold;';
}
if (fontStyle & 4 /* Underline */) {
result += 'text-decoration: underline;';
}
return result;
};
return TokenMetadata;
}());
exports.TokenMetadata = TokenMetadata;
/**
* @internal
*/
exports.completionKindToCssClass = (function () {
var data = Object.create(null);
data[0 /* Method */] = 'method';
data[1 /* Function */] = 'function';
data[2 /* Constructor */] = 'constructor';
data[3 /* Field */] = 'field';
data[4 /* Variable */] = 'variable';
data[5 /* Class */] = 'class';
data[6 /* Struct */] = 'struct';
data[7 /* Interface */] = 'interface';
data[8 /* Module */] = 'module';
data[9 /* Property */] = 'property';
data[10 /* Event */] = 'event';
data[11 /* Operator */] = 'operator';
data[12 /* Unit */] = 'unit';
data[13 /* Value */] = 'value';
data[14 /* Constant */] = 'constant';
data[15 /* Enum */] = 'enum';
data[16 /* EnumMember */] = 'enum-member';
data[17 /* Keyword */] = 'keyword';
data[25 /* Snippet */] = 'snippet';
data[18 /* Text */] = 'text';
data[19 /* Color */] = 'color';
data[20 /* File */] = 'file';
data[21 /* Reference */] = 'reference';
data[22 /* Customcolor */] = 'customcolor';
data[23 /* Folder */] = 'folder';
data[24 /* TypeParameter */] = 'type-parameter';
return function (kind) {
return data[kind] || 'property';
};
})();
/**
* @internal
*/
exports.completionKindFromString = (function () {
var data = Object.create(null);
data['method'] = 0 /* Method */;
data['function'] = 1 /* Function */;
data['constructor'] = 2 /* Constructor */;
data['field'] = 3 /* Field */;
data['variable'] = 4 /* Variable */;
data['class'] = 5 /* Class */;
data['struct'] = 6 /* Struct */;
data['interface'] = 7 /* Interface */;
data['module'] = 8 /* Module */;
data['property'] = 9 /* Property */;
data['event'] = 10 /* Event */;
data['operator'] = 11 /* Operator */;
data['unit'] = 12 /* Unit */;
data['value'] = 13 /* Value */;
data['constant'] = 14 /* Constant */;
data['enum'] = 15 /* Enum */;
data['enum-member'] = 16 /* EnumMember */;
data['enumMember'] = 16 /* EnumMember */;
data['keyword'] = 17 /* Keyword */;
data['snippet'] = 25 /* Snippet */;
data['text'] = 18 /* Text */;
data['color'] = 19 /* Color */;
data['file'] = 20 /* File */;
data['reference'] = 21 /* Reference */;
data['customcolor'] = 22 /* Customcolor */;
data['folder'] = 23 /* Folder */;
data['type-parameter'] = 24 /* TypeParameter */;
data['typeParameter'] = 24 /* TypeParameter */;
return function (value, strict) {
var res = data[value];
if (typeof res === 'undefined' && !strict) {
res = 9 /* Property */;
}
return res;
};
})();
var SignatureHelpTriggerKind;
(function (SignatureHelpTriggerKind) {
SignatureHelpTriggerKind[SignatureHelpTriggerKind["Invoke"] = 1] = "Invoke";
SignatureHelpTriggerKind[SignatureHelpTriggerKind["TriggerCharacter"] = 2] = "TriggerCharacter";
SignatureHelpTriggerKind[SignatureHelpTriggerKind["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
/**
* A document highlight kind.
*/
var DocumentHighlightKind;
(function (DocumentHighlightKind) {
/**
* A textual occurrence.
*/
DocumentHighlightKind[DocumentHighlightKind["Text"] = 0] = "Text";
/**
* Read-access of a symbol, like reading a variable.
*/
DocumentHighlightKind[DocumentHighlightKind["Read"] = 1] = "Read";
/**
* Write-access of a symbol, like writing to a variable.
*/
DocumentHighlightKind[DocumentHighlightKind["Write"] = 2] = "Write";
})(DocumentHighlightKind = exports.DocumentHighlightKind || (exports.DocumentHighlightKind = {}));
/**
* @internal
*/
function isLocationLink(thing) {
return thing
&& uri_1.URI.isUri(thing.uri)
&& range_1.Range.isIRange(thing.range)
&& (range_1.Range.isIRange(thing.originSelectionRange) || range_1.Range.isIRange(thing.targetSelectionRange));
}
exports.isLocationLink = isLocationLink;
/**
* @internal
*/
var SymbolKinds;
(function (SymbolKinds) {
var byName = new Map();
byName.set('file', 0 /* File */);
byName.set('module', 1 /* Module */);
byName.set('namespace', 2 /* Namespace */);
byName.set('package', 3 /* Package */);
byName.set('class', 4 /* Class */);
byName.set('method', 5 /* Method */);
byName.set('property', 6 /* Property */);
byName.set('field', 7 /* Field */);
byName.set('constructor', 8 /* Constructor */);
byName.set('enum', 9 /* Enum */);
byName.set('interface', 10 /* Interface */);
byName.set('function', 11 /* Function */);
byName.set('variable', 12 /* Variable */);
byName.set('constant', 13 /* Constant */);
byName.set('string', 14 /* String */);
byName.set('number', 15 /* Number */);
byName.set('boolean', 16 /* Boolean */);
byName.set('array', 17 /* Array */);
byName.set('object', 18 /* Object */);
byName.set('key', 19 /* Key */);
byName.set('null', 20 /* Null */);
byName.set('enum-member', 21 /* EnumMember */);
byName.set('struct', 22 /* Struct */);
byName.set('event', 23 /* Event */);
byName.set('operator', 24 /* Operator */);
byName.set('type-parameter', 25 /* TypeParameter */);
var byKind = new Map();
byKind.set(0 /* File */, 'file');
byKind.set(1 /* Module */, 'module');
byKind.set(2 /* Namespace */, 'namespace');
byKind.set(3 /* Package */, 'package');
byKind.set(4 /* Class */, 'class');
byKind.set(5 /* Method */, 'method');
byKind.set(6 /* Property */, 'property');
byKind.set(7 /* Field */, 'field');
byKind.set(8 /* Constructor */, 'constructor');
byKind.set(9 /* Enum */, 'enum');
byKind.set(10 /* Interface */, 'interface');
byKind.set(11 /* Function */, 'function');
byKind.set(12 /* Variable */, 'variable');
byKind.set(13 /* Constant */, 'constant');
byKind.set(14 /* String */, 'string');
byKind.set(15 /* Number */, 'number');
byKind.set(16 /* Boolean */, 'boolean');
byKind.set(17 /* Array */, 'array');
byKind.set(18 /* Object */, 'object');
byKind.set(19 /* Key */, 'key');
byKind.set(20 /* Null */, 'null');
byKind.set(21 /* EnumMember */, 'enum-member');
byKind.set(22 /* Struct */, 'struct');
byKind.set(23 /* Event */, 'event');
byKind.set(24 /* Operator */, 'operator');
byKind.set(25 /* TypeParameter */, 'type-parameter');
/**
* @internal
*/
function fromString(value) {
return byName.get(value);
}
SymbolKinds.fromString = fromString;
/**
* @internal
*/
function toString(kind) {
return byKind.get(kind);
}
SymbolKinds.toString = toString;
/**
* @internal
*/
function toCssClassName(kind, inline) {
return "codicon " + (inline ? 'inline' : 'block') + " codicon-symbol-" + (byKind.get(kind) || 'property');
}
SymbolKinds.toCssClassName = toCssClassName;
})(SymbolKinds = exports.SymbolKinds || (exports.SymbolKinds = {}));
var FoldingRangeKind = /** @class */ (function () {
/**
* Creates a new [FoldingRangeKind](#FoldingRangeKind).
*
* @param value of the kind.
*/
function FoldingRangeKind(value) {
this.value = value;
}
/**
* Kind for folding range representing a comment. The value of the kind is 'comment'.
*/
FoldingRangeKind.Comment = new FoldingRangeKind('comment');
/**
* Kind for folding range representing a import. The value of the kind is 'imports'.
*/
FoldingRangeKind.Imports = new FoldingRangeKind('imports');
/**
* Kind for folding range representing regions (for example marked by `#region`, `#endregion`).
* The value of the kind is 'region'.
*/
FoldingRangeKind.Region = new FoldingRangeKind('region');
return FoldingRangeKind;
}());
exports.FoldingRangeKind = FoldingRangeKind;
/**
* @internal
*/
var WorkspaceFileEdit;
(function (WorkspaceFileEdit) {
/**
* @internal
*/
function is(thing) {
return types_1.isObject(thing) && (Boolean(thing.newUri) || Boolean(thing.oldUri));
}
WorkspaceFileEdit.is = is;
})(WorkspaceFileEdit = exports.WorkspaceFileEdit || (exports.WorkspaceFileEdit = {}));
/**
* @internal
*/
var WorkspaceTextEdit;
(function (WorkspaceTextEdit) {
/**
* @internal
*/
function is(thing) {
return types_1.isObject(thing) && uri_1.URI.isUri(thing.resource) && types_1.isObject(thing.edit);
}
WorkspaceTextEdit.is = is;
})(WorkspaceTextEdit = exports.WorkspaceTextEdit || (exports.WorkspaceTextEdit = {}));
// --- feature registries ------
/**
* @internal
*/
exports.ReferenceProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.RenameProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.CompletionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.SignatureHelpProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.HoverProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentSymbolProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentHighlightProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DefinitionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DeclarationProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.ImplementationProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.TypeDefinitionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.CodeLensProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.CodeActionProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentFormattingEditProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentRangeFormattingEditProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.OnTypeFormattingEditProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.LinkProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.ColorProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.SelectionRangeRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.FoldingRangeProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentSemanticTokensProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.DocumentRangeSemanticTokensProviderRegistry = new languageFeatureRegistry_1.LanguageFeatureRegistry();
/**
* @internal
*/
exports.TokenizationRegistry = new tokenizationRegistry_1.TokenizationRegistryImpl();
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[93/*vs/editor/common/core/lineTokens*/], __M([0/*require*/,1/*exports*/,17/*vs/editor/common/modes*/]), function (require, exports, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LineTokens = /** @class */ (function () {
function LineTokens(tokens, text) {
this._tokens = tokens;
this._tokensCount = (this._tokens.length >>> 1);
this._text = text;
}
LineTokens.prototype.equals = function (other) {
if (other instanceof LineTokens) {
return this.slicedEquals(other, 0, this._tokensCount);
}
return false;
};
LineTokens.prototype.slicedEquals = function (other, sliceFromTokenIndex, sliceTokenCount) {
if (this._text !== other._text) {
return false;
}
if (this._tokensCount !== other._tokensCount) {
return false;
}
var from = (sliceFromTokenIndex << 1);
var to = from + (sliceTokenCount << 1);
for (var i = from; i < to; i++) {
if (this._tokens[i] !== other._tokens[i]) {
return false;
}
}
return true;
};
LineTokens.prototype.getLineContent = function () {
return this._text;
};
LineTokens.prototype.getCount = function () {
return this._tokensCount;
};
LineTokens.prototype.getStartOffset = function (tokenIndex) {
if (tokenIndex > 0) {
return this._tokens[(tokenIndex - 1) << 1];
}
return 0;
};
LineTokens.prototype.getMetadata = function (tokenIndex) {
var metadata = this._tokens[(tokenIndex << 1) + 1];
return metadata;
};
LineTokens.prototype.getLanguageId = function (tokenIndex) {
var metadata = this._tokens[(tokenIndex << 1) + 1];
return modes_1.TokenMetadata.getLanguageId(metadata);
};
LineTokens.prototype.getStandardTokenType = function (tokenIndex) {
var metadata = this._tokens[(tokenIndex << 1) + 1];
return modes_1.TokenMetadata.getTokenType(metadata);
};
LineTokens.prototype.getForeground = function (tokenIndex) {
var metadata = this._tokens[(tokenIndex << 1) + 1];
return modes_1.TokenMetadata.getForeground(metadata);
};
LineTokens.prototype.getClassName = function (tokenIndex) {
var metadata = this._tokens[(tokenIndex << 1) + 1];
return modes_1.TokenMetadata.getClassNameFromMetadata(metadata);
};
LineTokens.prototype.getInlineStyle = function (tokenIndex, colorMap) {
var metadata = this._tokens[(tokenIndex << 1) + 1];
return modes_1.TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap);
};
LineTokens.prototype.getEndOffset = function (tokenIndex) {
return this._tokens[tokenIndex << 1];
};
/**
* Find the token containing offset `offset`.
* @param offset The search offset
* @return The index of the token containing the offset.
*/
LineTokens.prototype.findTokenIndexAtOffset = function (offset) {
return LineTokens.findIndexInTokensArray(this._tokens, offset);
};
LineTokens.prototype.inflate = function () {
return this;
};
LineTokens.prototype.sliceAndInflate = function (startOffset, endOffset, deltaOffset) {
return new SlicedLineTokens(this, startOffset, endOffset, deltaOffset);
};
LineTokens.convertToEndOffset = function (tokens, lineTextLength) {
var tokenCount = (tokens.length >>> 1);
var lastTokenIndex = tokenCount - 1;
for (var tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) {
tokens[tokenIndex << 1] = tokens[(tokenIndex + 1) << 1];
}
tokens[lastTokenIndex << 1] = lineTextLength;
};
LineTokens.findIndexInTokensArray = function (tokens, desiredIndex) {
if (tokens.length <= 2) {
return 0;
}
var low = 0;
var high = (tokens.length >>> 1) - 1;
while (low < high) {
var mid = low + Math.floor((high - low) / 2);
var endOffset = tokens[(mid << 1)];
if (endOffset === desiredIndex) {
return mid + 1;
}
else if (endOffset < desiredIndex) {
low = mid + 1;
}
else if (endOffset > desiredIndex) {
high = mid;
}
}
return low;
};
return LineTokens;
}());
exports.LineTokens = LineTokens;
var SlicedLineTokens = /** @class */ (function () {
function SlicedLineTokens(source, startOffset, endOffset, deltaOffset) {
this._source = source;
this._startOffset = startOffset;
this._endOffset = endOffset;
this._deltaOffset = deltaOffset;
this._firstTokenIndex = source.findTokenIndexAtOffset(startOffset);
this._tokensCount = 0;
for (var i = this._firstTokenIndex, len = source.getCount(); i < len; i++) {
var tokenStartOffset = source.getStartOffset(i);
if (tokenStartOffset >= endOffset) {
break;
}
this._tokensCount++;
}
}
SlicedLineTokens.prototype.equals = function (other) {
if (other instanceof SlicedLineTokens) {
return (this._startOffset === other._startOffset
&& this._endOffset === other._endOffset
&& this._deltaOffset === other._deltaOffset
&& this._source.slicedEquals(other._source, this._firstTokenIndex, this._tokensCount));
}
return false;
};
SlicedLineTokens.prototype.getCount = function () {
return this._tokensCount;
};
SlicedLineTokens.prototype.getForeground = function (tokenIndex) {
return this._source.getForeground(this._firstTokenIndex + tokenIndex);
};
SlicedLineTokens.prototype.getEndOffset = function (tokenIndex) {
var tokenEndOffset = this._source.getEndOffset(this._firstTokenIndex + tokenIndex);
return Math.min(this._endOffset, tokenEndOffset) - this._startOffset + this._deltaOffset;
};
SlicedLineTokens.prototype.getClassName = function (tokenIndex) {
return this._source.getClassName(this._firstTokenIndex + tokenIndex);
};
SlicedLineTokens.prototype.getInlineStyle = function (tokenIndex, colorMap) {
return this._source.getInlineStyle(this._firstTokenIndex + tokenIndex, colorMap);
};
SlicedLineTokens.prototype.findTokenIndexAtOffset = function (offset) {
return this._source.findTokenIndexAtOffset(offset + this._startOffset - this._deltaOffset) - this._firstTokenIndex;
};
return SlicedLineTokens;
}());
exports.SlicedLineTokens = SlicedLineTokens;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[157/*vs/editor/common/model/tokensStore*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,93/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,17/*vs/editor/common/modes*/]), function (require, exports, arrays, lineTokens_1, position_1, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function countEOL(text) {
var eolCount = 0;
var firstLineLength = 0;
var lastLineStart = 0;
for (var i = 0, len = text.length; i < len; i++) {
var chr = text.charCodeAt(i);
if (chr === 13 /* CarriageReturn */) {
if (eolCount === 0) {
firstLineLength = i;
}
eolCount++;
if (i + 1 < len && text.charCodeAt(i + 1) === 10 /* LineFeed */) {
// \r\n... case
i++; // skip \n
}
else {
// \r... case
}
lastLineStart = i + 1;
}
else if (chr === 10 /* LineFeed */) {
if (eolCount === 0) {
firstLineLength = i;
}
eolCount++;
lastLineStart = i + 1;
}
}
if (eolCount === 0) {
firstLineLength = text.length;
}
return [eolCount, firstLineLength, text.length - lastLineStart];
}
exports.countEOL = countEOL;
function getDefaultMetadata(topLevelLanguageId) {
return ((topLevelLanguageId << 0 /* LANGUAGEID_OFFSET */)
| (0 /* Other */ << 8 /* TOKEN_TYPE_OFFSET */)
| (0 /* None */ << 11 /* FONT_STYLE_OFFSET */)
| (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */)
| (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0;
}
var EMPTY_LINE_TOKENS = (new Uint32Array(0)).buffer;
var MultilineTokensBuilder = /** @class */ (function () {
function MultilineTokensBuilder() {
this.tokens = [];
}
MultilineTokensBuilder.prototype.add = function (lineNumber, lineTokens) {
if (this.tokens.length > 0) {
var last = this.tokens[this.tokens.length - 1];
var lastLineNumber = last.startLineNumber + last.tokens.length - 1;
if (lastLineNumber + 1 === lineNumber) {
// append
last.tokens.push(lineTokens);
return;
}
}
this.tokens.push(new MultilineTokens(lineNumber, [lineTokens]));
};
return MultilineTokensBuilder;
}());
exports.MultilineTokensBuilder = MultilineTokensBuilder;
var SparseEncodedTokens = /** @class */ (function () {
function SparseEncodedTokens(tokens) {
this._tokens = tokens;
this._tokenCount = tokens.length / 4;
}
SparseEncodedTokens.prototype.getMaxDeltaLine = function () {
var tokenCount = this.getTokenCount();
if (tokenCount === 0) {
return -1;
}
return this.getDeltaLine(tokenCount - 1);
};
SparseEncodedTokens.prototype.getTokenCount = function () {
return this._tokenCount;
};
SparseEncodedTokens.prototype.getDeltaLine = function (tokenIndex) {
return this._tokens[4 * tokenIndex];
};
SparseEncodedTokens.prototype.getStartCharacter = function (tokenIndex) {
return this._tokens[4 * tokenIndex + 1];
};
SparseEncodedTokens.prototype.getEndCharacter = function (tokenIndex) {
return this._tokens[4 * tokenIndex + 2];
};
SparseEncodedTokens.prototype.getMetadata = function (tokenIndex) {
return this._tokens[4 * tokenIndex + 3];
};
SparseEncodedTokens.prototype.clear = function () {
this._tokenCount = 0;
};
SparseEncodedTokens.prototype.acceptDeleteRange = function (horizontalShiftForFirstLineTokens, startDeltaLine, startCharacter, endDeltaLine, endCharacter) {
// This is a bit complex, here are the cases I used to think about this:
//
// 1. The token starts before the deletion range
// 1a. The token is completely before the deletion range
// -----------
// xxxxxxxxxxx
// 1b. The token starts before, the deletion range ends after the token
// -----------
// xxxxxxxxxxx
// 1c. The token starts before, the deletion range ends precisely with the token
// ---------------
// xxxxxxxx
// 1d. The token starts before, the deletion range is inside the token
// ---------------
// xxxxx
//
// 2. The token starts at the same position with the deletion range
// 2a. The token starts at the same position, and ends inside the deletion range
// -------
// xxxxxxxxxxx
// 2b. The token starts at the same position, and ends at the same position as the deletion range
// ----------
// xxxxxxxxxx
// 2c. The token starts at the same position, and ends after the deletion range
// -------------
// xxxxxxx
//
// 3. The token starts inside the deletion range
// 3a. The token is inside the deletion range
// -------
// xxxxxxxxxxxxx
// 3b. The token starts inside the deletion range, and ends at the same position as the deletion range
// ----------
// xxxxxxxxxxxxx
// 3c. The token starts inside the deletion range, and ends after the deletion range
// ------------
// xxxxxxxxxxx
//
// 4. The token starts after the deletion range
// -----------
// xxxxxxxx
//
var tokens = this._tokens;
var tokenCount = this._tokenCount;
var deletedLineCount = (endDeltaLine - startDeltaLine);
var newTokenCount = 0;
var hasDeletedTokens = false;
for (var i = 0; i < tokenCount; i++) {
var srcOffset = 4 * i;
var tokenDeltaLine = tokens[srcOffset];
var tokenStartCharacter = tokens[srcOffset + 1];
var tokenEndCharacter = tokens[srcOffset + 2];
var tokenMetadata = tokens[srcOffset + 3];
if (tokenDeltaLine < startDeltaLine || (tokenDeltaLine === startDeltaLine && tokenEndCharacter <= startCharacter)) {
// 1a. The token is completely before the deletion range
// => nothing to do
newTokenCount++;
continue;
}
else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter < startCharacter) {
// 1b, 1c, 1d
// => the token survives, but it needs to shrink
if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
// 1d. The token starts before, the deletion range is inside the token
// => the token shrinks by the deletion character count
tokenEndCharacter -= (endCharacter - startCharacter);
}
else {
// 1b. The token starts before, the deletion range ends after the token
// 1c. The token starts before, the deletion range ends precisely with the token
// => the token shrinks its ending to the deletion start
tokenEndCharacter = startCharacter;
}
}
else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter === startCharacter) {
// 2a, 2b, 2c
if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
// 2c. The token starts at the same position, and ends after the deletion range
// => the token shrinks by the deletion character count
tokenEndCharacter -= (endCharacter - startCharacter);
}
else {
// 2a. The token starts at the same position, and ends inside the deletion range
// 2b. The token starts at the same position, and ends at the same position as the deletion range
// => the token is deleted
hasDeletedTokens = true;
continue;
}
}
else if (tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter < endCharacter)) {
// 3a, 3b, 3c
if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
// 3c. The token starts inside the deletion range, and ends after the deletion range
// => the token moves left and shrinks
if (tokenDeltaLine === startDeltaLine) {
// the deletion started on the same line as the token
// => the token moves left and shrinks
tokenStartCharacter = startCharacter;
tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
}
else {
// the deletion started on a line above the token
// => the token moves to the beginning of the line
tokenStartCharacter = 0;
tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
}
}
else {
// 3a. The token is inside the deletion range
// 3b. The token starts inside the deletion range, and ends at the same position as the deletion range
// => the token is deleted
hasDeletedTokens = true;
continue;
}
}
else if (tokenDeltaLine > endDeltaLine) {
// 4. (partial) The token starts after the deletion range, on a line below...
if (deletedLineCount === 0 && !hasDeletedTokens) {
// early stop, there is no need to walk all the tokens and do nothing...
newTokenCount = tokenCount;
break;
}
tokenDeltaLine -= deletedLineCount;
}
else if (tokenDeltaLine === endDeltaLine && tokenStartCharacter >= endCharacter) {
// 4. (continued) The token starts after the deletion range, on the last line where a deletion occurs
if (horizontalShiftForFirstLineTokens && tokenDeltaLine === 0) {
tokenStartCharacter += horizontalShiftForFirstLineTokens;
tokenEndCharacter += horizontalShiftForFirstLineTokens;
}
tokenDeltaLine -= deletedLineCount;
tokenStartCharacter -= (endCharacter - startCharacter);
tokenEndCharacter -= (endCharacter - startCharacter);
}
else {
throw new Error("Not possible!");
}
var destOffset = 4 * newTokenCount;
tokens[destOffset] = tokenDeltaLine;
tokens[destOffset + 1] = tokenStartCharacter;
tokens[destOffset + 2] = tokenEndCharacter;
tokens[destOffset + 3] = tokenMetadata;
newTokenCount++;
}
this._tokenCount = newTokenCount;
};
SparseEncodedTokens.prototype.acceptInsertText = function (deltaLine, character, eolCount, firstLineLength, lastLineLength, firstCharCode) {
// Here are the cases I used to think about this:
//
// 1. The token is completely before the insertion point
// ----------- |
// 2. The token ends precisely at the insertion point
// -----------|
// 3. The token contains the insertion point
// -----|------
// 4. The token starts precisely at the insertion point
// |-----------
// 5. The token is completely after the insertion point
// | -----------
//
var isInsertingPreciselyOneWordCharacter = (eolCount === 0
&& firstLineLength === 1
&& ((firstCharCode >= 48 /* Digit0 */ && firstCharCode <= 57 /* Digit9 */)
|| (firstCharCode >= 65 /* A */ && firstCharCode <= 90 /* Z */)
|| (firstCharCode >= 97 /* a */ && firstCharCode <= 122 /* z */)));
var tokens = this._tokens;
var tokenCount = this._tokenCount;
for (var i = 0; i < tokenCount; i++) {
var offset = 4 * i;
var tokenDeltaLine = tokens[offset];
var tokenStartCharacter = tokens[offset + 1];
var tokenEndCharacter = tokens[offset + 2];
if (tokenDeltaLine < deltaLine || (tokenDeltaLine === deltaLine && tokenEndCharacter < character)) {
// 1. The token is completely before the insertion point
// => nothing to do
continue;
}
else if (tokenDeltaLine === deltaLine && tokenEndCharacter === character) {
// 2. The token ends precisely at the insertion point
// => expand the end character only if inserting precisely one character that is a word character
if (isInsertingPreciselyOneWordCharacter) {
tokenEndCharacter += 1;
}
else {
continue;
}
}
else if (tokenDeltaLine === deltaLine && tokenStartCharacter < character && character < tokenEndCharacter) {
// 3. The token contains the insertion point
if (eolCount === 0) {
// => just expand the end character
tokenEndCharacter += firstLineLength;
}
else {
// => cut off the token
tokenEndCharacter = character;
}
}
else {
// 4. or 5.
if (tokenDeltaLine === deltaLine && tokenStartCharacter === character) {
// 4. The token starts precisely at the insertion point
// => grow the token (by keeping its start constant) only if inserting precisely one character that is a word character
// => otherwise behave as in case 5.
if (isInsertingPreciselyOneWordCharacter) {
continue;
}
}
// => the token must move and keep its size constant
if (tokenDeltaLine === deltaLine) {
tokenDeltaLine += eolCount;
// this token is on the line where the insertion is taking place
if (eolCount === 0) {
tokenStartCharacter += firstLineLength;
tokenEndCharacter += firstLineLength;
}
else {
var tokenLength = tokenEndCharacter - tokenStartCharacter;
tokenStartCharacter = lastLineLength + (tokenStartCharacter - character);
tokenEndCharacter = tokenStartCharacter + tokenLength;
}
}
else {
tokenDeltaLine += eolCount;
}
}
tokens[offset] = tokenDeltaLine;
tokens[offset + 1] = tokenStartCharacter;
tokens[offset + 2] = tokenEndCharacter;
}
};
return SparseEncodedTokens;
}());
exports.SparseEncodedTokens = SparseEncodedTokens;
var LineTokens2 = /** @class */ (function () {
function LineTokens2(actual, startTokenIndex, endTokenIndex) {
this._actual = actual;
this._startTokenIndex = startTokenIndex;
this._endTokenIndex = endTokenIndex;
}
LineTokens2.prototype.getCount = function () {
return this._endTokenIndex - this._startTokenIndex + 1;
};
LineTokens2.prototype.getStartCharacter = function (tokenIndex) {
return this._actual.getStartCharacter(this._startTokenIndex + tokenIndex);
};
LineTokens2.prototype.getEndCharacter = function (tokenIndex) {
return this._actual.getEndCharacter(this._startTokenIndex + tokenIndex);
};
LineTokens2.prototype.getMetadata = function (tokenIndex) {
return this._actual.getMetadata(this._startTokenIndex + tokenIndex);
};
return LineTokens2;
}());
exports.LineTokens2 = LineTokens2;
var MultilineTokens2 = /** @class */ (function () {
function MultilineTokens2(startLineNumber, tokens) {
this.startLineNumber = startLineNumber;
this.tokens = tokens;
this.endLineNumber = this.startLineNumber + this.tokens.getMaxDeltaLine();
}
MultilineTokens2.prototype._updateEndLineNumber = function () {
this.endLineNumber = this.startLineNumber + this.tokens.getMaxDeltaLine();
};
MultilineTokens2.prototype.getLineTokens = function (lineNumber) {
if (this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber) {
var findResult = MultilineTokens2._findTokensWithLine(this.tokens, lineNumber - this.startLineNumber);
if (findResult) {
var startTokenIndex = findResult[0], endTokenIndex = findResult[1];
return new LineTokens2(this.tokens, startTokenIndex, endTokenIndex);
}
}
return null;
};
MultilineTokens2._findTokensWithLine = function (tokens, deltaLine) {
var low = 0;
var high = tokens.getTokenCount() - 1;
while (low < high) {
var mid = low + Math.floor((high - low) / 2);
var midDeltaLine = tokens.getDeltaLine(mid);
if (midDeltaLine < deltaLine) {
low = mid + 1;
}
else if (midDeltaLine > deltaLine) {
high = mid - 1;
}
else {
var min = mid;
while (min > low && tokens.getDeltaLine(min - 1) === deltaLine) {
min--;
}
var max = mid;
while (max < high && tokens.getDeltaLine(max + 1) === deltaLine) {
max++;
}
return [min, max];
}
}
if (tokens.getDeltaLine(low) === deltaLine) {
return [low, low];
}
return null;
};
MultilineTokens2.prototype.applyEdit = function (range, text) {
var _a = countEOL(text), eolCount = _a[0], firstLineLength = _a[1], lastLineLength = _a[2];
this.acceptEdit(range, eolCount, firstLineLength, lastLineLength, text.length > 0 ? text.charCodeAt(0) : 0 /* Null */);
};
MultilineTokens2.prototype.acceptEdit = function (range, eolCount, firstLineLength, lastLineLength, firstCharCode) {
this._acceptDeleteRange(range);
this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength, lastLineLength, firstCharCode);
this._updateEndLineNumber();
};
MultilineTokens2.prototype._acceptDeleteRange = function (range) {
if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
// Nothing to delete
return;
}
var firstLineIndex = range.startLineNumber - this.startLineNumber;
var lastLineIndex = range.endLineNumber - this.startLineNumber;
if (lastLineIndex < 0) {
// this deletion occurs entirely before this block, so we only need to adjust line numbers
var deletedLinesCount = lastLineIndex - firstLineIndex;
this.startLineNumber -= deletedLinesCount;
return;
}
var tokenMaxDeltaLine = this.tokens.getMaxDeltaLine();
if (firstLineIndex >= tokenMaxDeltaLine + 1) {
// this deletion occurs entirely after this block, so there is nothing to do
return;
}
if (firstLineIndex < 0 && lastLineIndex >= tokenMaxDeltaLine + 1) {
// this deletion completely encompasses this block
this.startLineNumber = 0;
this.tokens.clear();
return;
}
if (firstLineIndex < 0) {
var deletedBefore = -firstLineIndex;
this.startLineNumber -= deletedBefore;
this.tokens.acceptDeleteRange(range.startColumn - 1, 0, 0, lastLineIndex, range.endColumn - 1);
}
else {
this.tokens.acceptDeleteRange(0, firstLineIndex, range.startColumn - 1, lastLineIndex, range.endColumn - 1);
}
};
MultilineTokens2.prototype._acceptInsertText = function (position, eolCount, firstLineLength, lastLineLength, firstCharCode) {
if (eolCount === 0 && firstLineLength === 0) {
// Nothing to insert
return;
}
var lineIndex = position.lineNumber - this.startLineNumber;
if (lineIndex < 0) {
// this insertion occurs before this block, so we only need to adjust line numbers
this.startLineNumber += eolCount;
return;
}
var tokenMaxDeltaLine = this.tokens.getMaxDeltaLine();
if (lineIndex >= tokenMaxDeltaLine + 1) {
// this insertion occurs after this block, so there is nothing to do
return;
}
this.tokens.acceptInsertText(lineIndex, position.column - 1, eolCount, firstLineLength, lastLineLength, firstCharCode);
};
return MultilineTokens2;
}());
exports.MultilineTokens2 = MultilineTokens2;
var MultilineTokens = /** @class */ (function () {
function MultilineTokens(startLineNumber, tokens) {
this.startLineNumber = startLineNumber;
this.tokens = tokens;
}
return MultilineTokens;
}());
exports.MultilineTokens = MultilineTokens;
function toUint32Array(arr) {
if (arr instanceof Uint32Array) {
return arr;
}
else {
return new Uint32Array(arr);
}
}
var TokensStore2 = /** @class */ (function () {
function TokensStore2() {
this._pieces = [];
}
TokensStore2.prototype.flush = function () {
this._pieces = [];
};
TokensStore2.prototype.set = function (pieces) {
this._pieces = pieces || [];
};
TokensStore2.prototype.addSemanticTokens = function (lineNumber, aTokens) {
var pieces = this._pieces;
if (pieces.length === 0) {
return aTokens;
}
var pieceIndex = TokensStore2._findFirstPieceWithLine(pieces, lineNumber);
var bTokens = this._pieces[pieceIndex].getLineTokens(lineNumber);
if (!bTokens) {
return aTokens;
}
var aLen = aTokens.getCount();
var bLen = bTokens.getCount();
var aIndex = 0;
var result = [], resultLen = 0;
for (var bIndex = 0; bIndex < bLen; bIndex++) {
var bStartCharacter = bTokens.getStartCharacter(bIndex);
var bEndCharacter = bTokens.getEndCharacter(bIndex);
var bMetadata = bTokens.getMetadata(bIndex);
var bMask = (((bMetadata & 1 /* SEMANTIC_USE_ITALIC */) ? 2048 /* ITALIC_MASK */ : 0)
| ((bMetadata & 2 /* SEMANTIC_USE_BOLD */) ? 4096 /* BOLD_MASK */ : 0)
| ((bMetadata & 4 /* SEMANTIC_USE_UNDERLINE */) ? 8192 /* UNDERLINE_MASK */ : 0)
| ((bMetadata & 8 /* SEMANTIC_USE_FOREGROUND */) ? 8372224 /* FOREGROUND_MASK */ : 0)
| ((bMetadata & 16 /* SEMANTIC_USE_BACKGROUND */) ? 4286578688 /* BACKGROUND_MASK */ : 0)) >>> 0;
var aMask = (~bMask) >>> 0;
// push any token from `a` that is before `b`
while (aIndex < aLen && aTokens.getEndOffset(aIndex) <= bStartCharacter) {
result[resultLen++] = aTokens.getEndOffset(aIndex);
result[resultLen++] = aTokens.getMetadata(aIndex);
aIndex++;
}
// push the token from `a` if it intersects the token from `b`
if (aIndex < aLen && aTokens.getStartOffset(aIndex) < bStartCharacter) {
result[resultLen++] = bStartCharacter;
result[resultLen++] = aTokens.getMetadata(aIndex);
}
// skip any tokens from `a` that are contained inside `b`
while (aIndex < aLen && aTokens.getEndOffset(aIndex) < bEndCharacter) {
result[resultLen++] = aTokens.getEndOffset(aIndex);
result[resultLen++] = (aTokens.getMetadata(aIndex) & aMask) | (bMetadata & bMask);
aIndex++;
}
if (aIndex < aLen && aTokens.getEndOffset(aIndex) === bEndCharacter) {
// `a` ends exactly at the same spot as `b`!
result[resultLen++] = aTokens.getEndOffset(aIndex);
result[resultLen++] = (aTokens.getMetadata(aIndex) & aMask) | (bMetadata & bMask);
aIndex++;
}
else {
var aMergeIndex = Math.min(Math.max(0, aIndex - 1), aLen - 1);
// push the token from `b`
result[resultLen++] = bEndCharacter;
result[resultLen++] = (aTokens.getMetadata(aMergeIndex) & aMask) | (bMetadata & bMask);
}
}
// push the remaining tokens from `a`
while (aIndex < aLen) {
result[resultLen++] = aTokens.getEndOffset(aIndex);
result[resultLen++] = aTokens.getMetadata(aIndex);
aIndex++;
}
return new lineTokens_1.LineTokens(new Uint32Array(result), aTokens.getLineContent());
};
TokensStore2._findFirstPieceWithLine = function (pieces, lineNumber) {
var low = 0;
var high = pieces.length - 1;
while (low < high) {
var mid = low + Math.floor((high - low) / 2);
if (pieces[mid].endLineNumber < lineNumber) {
low = mid + 1;
}
else if (pieces[mid].startLineNumber > lineNumber) {
high = mid - 1;
}
else {
while (mid > low && pieces[mid - 1].startLineNumber <= lineNumber && lineNumber <= pieces[mid - 1].endLineNumber) {
mid--;
}
return mid;
}
}
return low;
};
//#region Editing
TokensStore2.prototype.acceptEdit = function (range, eolCount, firstLineLength, lastLineLength, firstCharCode) {
for (var _i = 0, _a = this._pieces; _i < _a.length; _i++) {
var piece = _a[_i];
piece.acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode);
}
};
return TokensStore2;
}());
exports.TokensStore2 = TokensStore2;
var TokensStore = /** @class */ (function () {
function TokensStore() {
this._lineTokens = [];
this._len = 0;
}
TokensStore.prototype.flush = function () {
this._lineTokens = [];
this._len = 0;
};
TokensStore.prototype.getTokens = function (topLevelLanguageId, lineIndex, lineText) {
var rawLineTokens = null;
if (lineIndex < this._len) {
rawLineTokens = this._lineTokens[lineIndex];
}
if (rawLineTokens !== null && rawLineTokens !== EMPTY_LINE_TOKENS) {
return new lineTokens_1.LineTokens(toUint32Array(rawLineTokens), lineText);
}
var lineTokens = new Uint32Array(2);
lineTokens[0] = lineText.length;
lineTokens[1] = getDefaultMetadata(topLevelLanguageId);
return new lineTokens_1.LineTokens(lineTokens, lineText);
};
TokensStore._massageTokens = function (topLevelLanguageId, lineTextLength, _tokens) {
var tokens = _tokens ? toUint32Array(_tokens) : null;
if (lineTextLength === 0) {
var hasDifferentLanguageId = false;
if (tokens && tokens.length > 1) {
hasDifferentLanguageId = (modes_1.TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId);
}
if (!hasDifferentLanguageId) {
return EMPTY_LINE_TOKENS;
}
}
if (!tokens || tokens.length === 0) {
var tokens_1 = new Uint32Array(2);
tokens_1[0] = lineTextLength;
tokens_1[1] = getDefaultMetadata(topLevelLanguageId);
return tokens_1.buffer;
}
// Ensure the last token covers the end of the text
tokens[tokens.length - 2] = lineTextLength;
if (tokens.byteOffset === 0 && tokens.byteLength === tokens.buffer.byteLength) {
// Store directly the ArrayBuffer pointer to save an object
return tokens.buffer;
}
return tokens;
};
TokensStore.prototype._ensureLine = function (lineIndex) {
while (lineIndex >= this._len) {
this._lineTokens[this._len] = null;
this._len++;
}
};
TokensStore.prototype._deleteLines = function (start, deleteCount) {
if (deleteCount === 0) {
return;
}
if (start + deleteCount > this._len) {
deleteCount = this._len - start;
}
this._lineTokens.splice(start, deleteCount);
this._len -= deleteCount;
};
TokensStore.prototype._insertLines = function (insertIndex, insertCount) {
if (insertCount === 0) {
return;
}
var lineTokens = [];
for (var i = 0; i < insertCount; i++) {
lineTokens[i] = null;
}
this._lineTokens = arrays.arrayInsert(this._lineTokens, insertIndex, lineTokens);
this._len += insertCount;
};
TokensStore.prototype.setTokens = function (topLevelLanguageId, lineIndex, lineTextLength, _tokens) {
var tokens = TokensStore._massageTokens(topLevelLanguageId, lineTextLength, _tokens);
this._ensureLine(lineIndex);
this._lineTokens[lineIndex] = tokens;
};
//#region Editing
TokensStore.prototype.acceptEdit = function (range, eolCount, firstLineLength) {
this._acceptDeleteRange(range);
this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength);
};
TokensStore.prototype._acceptDeleteRange = function (range) {
var firstLineIndex = range.startLineNumber - 1;
if (firstLineIndex >= this._len) {
return;
}
if (range.startLineNumber === range.endLineNumber) {
if (range.startColumn === range.endColumn) {
// Nothing to delete
return;
}
this._lineTokens[firstLineIndex] = TokensStore._delete(this._lineTokens[firstLineIndex], range.startColumn - 1, range.endColumn - 1);
return;
}
this._lineTokens[firstLineIndex] = TokensStore._deleteEnding(this._lineTokens[firstLineIndex], range.startColumn - 1);
var lastLineIndex = range.endLineNumber - 1;
var lastLineTokens = null;
if (lastLineIndex < this._len) {
lastLineTokens = TokensStore._deleteBeginning(this._lineTokens[lastLineIndex], range.endColumn - 1);
}
// Take remaining text on last line and append it to remaining text on first line
this._lineTokens[firstLineIndex] = TokensStore._append(this._lineTokens[firstLineIndex], lastLineTokens);
// Delete middle lines
this._deleteLines(range.startLineNumber, range.endLineNumber - range.startLineNumber);
};
TokensStore.prototype._acceptInsertText = function (position, eolCount, firstLineLength) {
if (eolCount === 0 && firstLineLength === 0) {
// Nothing to insert
return;
}
var lineIndex = position.lineNumber - 1;
if (lineIndex >= this._len) {
return;
}
if (eolCount === 0) {
// Inserting text on one line
this._lineTokens[lineIndex] = TokensStore._insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
return;
}
this._lineTokens[lineIndex] = TokensStore._deleteEnding(this._lineTokens[lineIndex], position.column - 1);
this._lineTokens[lineIndex] = TokensStore._insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
this._insertLines(position.lineNumber, eolCount);
};
TokensStore._deleteBeginning = function (lineTokens, toChIndex) {
if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
return lineTokens;
}
return TokensStore._delete(lineTokens, 0, toChIndex);
};
TokensStore._deleteEnding = function (lineTokens, fromChIndex) {
if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
return lineTokens;
}
var tokens = toUint32Array(lineTokens);
var lineTextLength = tokens[tokens.length - 2];
return TokensStore._delete(lineTokens, fromChIndex, lineTextLength);
};
TokensStore._delete = function (lineTokens, fromChIndex, toChIndex) {
if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS || fromChIndex === toChIndex) {
return lineTokens;
}
var tokens = toUint32Array(lineTokens);
var tokensCount = (tokens.length >>> 1);
// special case: deleting everything
if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) {
return EMPTY_LINE_TOKENS;
}
var fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, fromChIndex);
var fromTokenStartOffset = (fromTokenIndex > 0 ? tokens[(fromTokenIndex - 1) << 1] : 0);
var fromTokenEndOffset = tokens[fromTokenIndex << 1];
if (toChIndex < fromTokenEndOffset) {
// the delete range is inside a single token
var delta_1 = (toChIndex - fromChIndex);
for (var i = fromTokenIndex; i < tokensCount; i++) {
tokens[i << 1] -= delta_1;
}
return lineTokens;
}
var dest;
var lastEnd;
if (fromTokenStartOffset !== fromChIndex) {
tokens[fromTokenIndex << 1] = fromChIndex;
dest = ((fromTokenIndex + 1) << 1);
lastEnd = fromChIndex;
}
else {
dest = (fromTokenIndex << 1);
lastEnd = fromTokenStartOffset;
}
var delta = (toChIndex - fromChIndex);
for (var tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) {
var tokenEndOffset = tokens[tokenIndex << 1] - delta;
if (tokenEndOffset > lastEnd) {
tokens[dest++] = tokenEndOffset;
tokens[dest++] = tokens[(tokenIndex << 1) + 1];
lastEnd = tokenEndOffset;
}
}
if (dest === tokens.length) {
// nothing to trim
return lineTokens;
}
var tmp = new Uint32Array(dest);
tmp.set(tokens.subarray(0, dest), 0);
return tmp.buffer;
};
TokensStore._append = function (lineTokens, _otherTokens) {
if (_otherTokens === EMPTY_LINE_TOKENS) {
return lineTokens;
}
if (lineTokens === EMPTY_LINE_TOKENS) {
return _otherTokens;
}
if (lineTokens === null) {
return lineTokens;
}
if (_otherTokens === null) {
// cannot determine combined line length...
return null;
}
var myTokens = toUint32Array(lineTokens);
var otherTokens = toUint32Array(_otherTokens);
var otherTokensCount = (otherTokens.length >>> 1);
var result = new Uint32Array(myTokens.length + otherTokens.length);
result.set(myTokens, 0);
var dest = myTokens.length;
var delta = myTokens[myTokens.length - 2];
for (var i = 0; i < otherTokensCount; i++) {
result[dest++] = otherTokens[(i << 1)] + delta;
result[dest++] = otherTokens[(i << 1) + 1];
}
return result.buffer;
};
TokensStore._insert = function (lineTokens, chIndex, textLength) {
if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
// nothing to do
return lineTokens;
}
var tokens = toUint32Array(lineTokens);
var tokensCount = (tokens.length >>> 1);
var fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, chIndex);
if (fromTokenIndex > 0) {
var fromTokenStartOffset = tokens[(fromTokenIndex - 1) << 1];
if (fromTokenStartOffset === chIndex) {
fromTokenIndex--;
}
}
for (var tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) {
tokens[tokenIndex << 1] += textLength;
}
return lineTokens;
};
return TokensStore;
}());
exports.TokensStore = TokensStore;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[63/*vs/editor/common/modes/nullMode*/], __M([0/*require*/,1/*exports*/,107/*vs/editor/common/core/token*/,17/*vs/editor/common/modes*/]), function (require, exports, token_1, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var NullStateImpl = /** @class */ (function () {
function NullStateImpl() {
}
NullStateImpl.prototype.clone = function () {
return this;
};
NullStateImpl.prototype.equals = function (other) {
return (this === other);
};
return NullStateImpl;
}());
exports.NULL_STATE = new NullStateImpl();
exports.NULL_MODE_ID = 'vs.editor.nullMode';
exports.NULL_LANGUAGE_IDENTIFIER = new modes_1.LanguageIdentifier(exports.NULL_MODE_ID, 0 /* Null */);
function nullTokenize(modeId, buffer, state, deltaOffset) {
return new token_1.TokenizationResult([new token_1.Token(deltaOffset, '', modeId)], state);
}
exports.nullTokenize = nullTokenize;
function nullTokenize2(languageId, buffer, state, deltaOffset) {
var tokens = new Uint32Array(2);
tokens[0] = deltaOffset;
tokens[1] = ((languageId << 0 /* LANGUAGEID_OFFSET */)
| (0 /* Other */ << 8 /* TOKEN_TYPE_OFFSET */)
| (0 /* None */ << 11 /* FONT_STYLE_OFFSET */)
| (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */)
| (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0;
return new token_1.TokenizationResult2(tokens, state === null ? exports.NULL_STATE : state);
}
exports.nullTokenize2 = nullTokenize2;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[482/*vs/editor/common/model/textModelTokens*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,10/*vs/base/common/errors*/,93/*vs/editor/common/core/lineTokens*/,13/*vs/editor/common/core/position*/,17/*vs/editor/common/modes*/,63/*vs/editor/common/modes/nullMode*/,2/*vs/base/common/lifecycle*/,132/*vs/base/common/stopwatch*/,157/*vs/editor/common/model/tokensStore*/,16/*vs/base/common/platform*/]), function (require, exports, arrays, errors_1, lineTokens_1, position_1, modes_1, nullMode_1, lifecycle_1, stopwatch_1, tokensStore_1, platform) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TokenizationStateStore = /** @class */ (function () {
function TokenizationStateStore() {
this._beginState = [];
this._valid = [];
this._len = 0;
this._invalidLineStartIndex = 0;
}
TokenizationStateStore.prototype._reset = function (initialState) {
this._beginState = [];
this._valid = [];
this._len = 0;
this._invalidLineStartIndex = 0;
if (initialState) {
this._setBeginState(0, initialState);
}
};
TokenizationStateStore.prototype.flush = function (initialState) {
this._reset(initialState);
};
Object.defineProperty(TokenizationStateStore.prototype, "invalidLineStartIndex", {
get: function () {
return this._invalidLineStartIndex;
},
enumerable: true,
configurable: true
});
TokenizationStateStore.prototype._invalidateLine = function (lineIndex) {
if (lineIndex < this._len) {
this._valid[lineIndex] = false;
}
if (lineIndex < this._invalidLineStartIndex) {
this._invalidLineStartIndex = lineIndex;
}
};
TokenizationStateStore.prototype._isValid = function (lineIndex) {
if (lineIndex < this._len) {
return this._valid[lineIndex];
}
return false;
};
TokenizationStateStore.prototype.getBeginState = function (lineIndex) {
if (lineIndex < this._len) {
return this._beginState[lineIndex];
}
return null;
};
TokenizationStateStore.prototype._ensureLine = function (lineIndex) {
while (lineIndex >= this._len) {
this._beginState[this._len] = null;
this._valid[this._len] = false;
this._len++;
}
};
TokenizationStateStore.prototype._deleteLines = function (start, deleteCount) {
if (deleteCount === 0) {
return;
}
if (start + deleteCount > this._len) {
deleteCount = this._len - start;
}
this._beginState.splice(start, deleteCount);
this._valid.splice(start, deleteCount);
this._len -= deleteCount;
};
TokenizationStateStore.prototype._insertLines = function (insertIndex, insertCount) {
if (insertCount === 0) {
return;
}
var beginState = [];
var valid = [];
for (var i = 0; i < insertCount; i++) {
beginState[i] = null;
valid[i] = false;
}
this._beginState = arrays.arrayInsert(this._beginState, insertIndex, beginState);
this._valid = arrays.arrayInsert(this._valid, insertIndex, valid);
this._len += insertCount;
};
TokenizationStateStore.prototype._setValid = function (lineIndex, valid) {
this._ensureLine(lineIndex);
this._valid[lineIndex] = valid;
};
TokenizationStateStore.prototype._setBeginState = function (lineIndex, beginState) {
this._ensureLine(lineIndex);
this._beginState[lineIndex] = beginState;
};
TokenizationStateStore.prototype.setEndState = function (linesLength, lineIndex, endState) {
this._setValid(lineIndex, true);
this._invalidLineStartIndex = lineIndex + 1;
// Check if this was the last line
if (lineIndex === linesLength - 1) {
return;
}
// Check if the end state has changed
var previousEndState = this.getBeginState(lineIndex + 1);
if (previousEndState === null || !endState.equals(previousEndState)) {
this._setBeginState(lineIndex + 1, endState);
this._invalidateLine(lineIndex + 1);
return;
}
// Perhaps we can skip tokenizing some lines...
var i = lineIndex + 1;
while (i < linesLength) {
if (!this._isValid(i)) {
break;
}
i++;
}
this._invalidLineStartIndex = i;
};
TokenizationStateStore.prototype.setFakeTokens = function (lineIndex) {
this._setValid(lineIndex, false);
};
//#region Editing
TokenizationStateStore.prototype.applyEdits = function (range, eolCount) {
var deletingLinesCnt = range.endLineNumber - range.startLineNumber;
var insertingLinesCnt = eolCount;
var editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
for (var j = editingLinesCnt; j >= 0; j--) {
this._invalidateLine(range.startLineNumber + j - 1);
}
this._acceptDeleteRange(range);
this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount);
};
TokenizationStateStore.prototype._acceptDeleteRange = function (range) {
var firstLineIndex = range.startLineNumber - 1;
if (firstLineIndex >= this._len) {
return;
}
this._deleteLines(range.startLineNumber, range.endLineNumber - range.startLineNumber);
};
TokenizationStateStore.prototype._acceptInsertText = function (position, eolCount) {
var lineIndex = position.lineNumber - 1;
if (lineIndex >= this._len) {
return;
}
this._insertLines(position.lineNumber, eolCount);
};
return TokenizationStateStore;
}());
exports.TokenizationStateStore = TokenizationStateStore;
var TextModelTokenization = /** @class */ (function (_super) {
__extends(TextModelTokenization, _super);
function TextModelTokenization(textModel) {
var _this = _super.call(this) || this;
_this._isDisposed = false;
_this._textModel = textModel;
_this._tokenizationStateStore = new TokenizationStateStore();
_this._tokenizationSupport = null;
_this._register(modes_1.TokenizationRegistry.onDidChange(function (e) {
var languageIdentifier = _this._textModel.getLanguageIdentifier();
if (e.changedLanguages.indexOf(languageIdentifier.language) === -1) {
return;
}
_this._resetTokenizationState();
_this._textModel.clearTokens();
}));
_this._register(_this._textModel.onDidChangeRawContentFast(function (e) {
if (e.containsEvent(1 /* Flush */)) {
_this._resetTokenizationState();
return;
}
}));
_this._register(_this._textModel.onDidChangeContentFast(function (e) {
for (var i = 0, len = e.changes.length; i < len; i++) {
var change = e.changes[i];
var eolCount = tokensStore_1.countEOL(change.text)[0];
_this._tokenizationStateStore.applyEdits(change.range, eolCount);
}
_this._beginBackgroundTokenization();
}));
_this._register(_this._textModel.onDidChangeAttached(function () {
_this._beginBackgroundTokenization();
}));
_this._register(_this._textModel.onDidChangeLanguage(function () {
_this._resetTokenizationState();
_this._textModel.clearTokens();
}));
_this._resetTokenizationState();
return _this;
}
TextModelTokenization.prototype.dispose = function () {
this._isDisposed = true;
_super.prototype.dispose.call(this);
};
TextModelTokenization.prototype._resetTokenizationState = function () {
var _a = initializeTokenization(this._textModel), tokenizationSupport = _a[0], initialState = _a[1];
this._tokenizationSupport = tokenizationSupport;
this._tokenizationStateStore.flush(initialState);
this._beginBackgroundTokenization();
};
TextModelTokenization.prototype._beginBackgroundTokenization = function () {
var _this = this;
if (this._textModel.isAttachedToEditor() && this._hasLinesToTokenize()) {
platform.setImmediate(function () {
if (_this._isDisposed) {
// disposed in the meantime
return;
}
_this._revalidateTokensNow();
});
}
};
TextModelTokenization.prototype._revalidateTokensNow = function (toLineNumber) {
if (toLineNumber === void 0) { toLineNumber = this._textModel.getLineCount(); }
var MAX_ALLOWED_TIME = 1;
var builder = new tokensStore_1.MultilineTokensBuilder();
var sw = stopwatch_1.StopWatch.create(false);
while (this._hasLinesToTokenize()) {
if (sw.elapsed() > MAX_ALLOWED_TIME) {
// Stop if MAX_ALLOWED_TIME is reached
break;
}
var tokenizedLineNumber = this._tokenizeOneInvalidLine(builder);
if (tokenizedLineNumber >= toLineNumber) {
break;
}
}
this._beginBackgroundTokenization();
this._textModel.setTokens(builder.tokens);
};
TextModelTokenization.prototype.tokenizeViewport = function (startLineNumber, endLineNumber) {
var builder = new tokensStore_1.MultilineTokensBuilder();
this._tokenizeViewport(builder, startLineNumber, endLineNumber);
this._textModel.setTokens(builder.tokens);
};
TextModelTokenization.prototype.reset = function () {
this._resetTokenizationState();
this._textModel.clearTokens();
};
TextModelTokenization.prototype.forceTokenization = function (lineNumber) {
var builder = new tokensStore_1.MultilineTokensBuilder();
this._updateTokensUntilLine(builder, lineNumber);
this._textModel.setTokens(builder.tokens);
};
TextModelTokenization.prototype.isCheapToTokenize = function (lineNumber) {
if (!this._tokenizationSupport) {
return true;
}
var firstInvalidLineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1;
if (lineNumber > firstInvalidLineNumber) {
return false;
}
if (lineNumber < firstInvalidLineNumber) {
return true;
}
if (this._textModel.getLineLength(lineNumber) < 2048 /* CHEAP_TOKENIZATION_LENGTH_LIMIT */) {
return true;
}
return false;
};
TextModelTokenization.prototype._hasLinesToTokenize = function () {
if (!this._tokenizationSupport) {
return false;
}
return (this._tokenizationStateStore.invalidLineStartIndex < this._textModel.getLineCount());
};
TextModelTokenization.prototype._tokenizeOneInvalidLine = function (builder) {
if (!this._hasLinesToTokenize()) {
return this._textModel.getLineCount() + 1;
}
var lineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1;
this._updateTokensUntilLine(builder, lineNumber);
return lineNumber;
};
TextModelTokenization.prototype._updateTokensUntilLine = function (builder, lineNumber) {
if (!this._tokenizationSupport) {
return;
}
var languageIdentifier = this._textModel.getLanguageIdentifier();
var linesLength = this._textModel.getLineCount();
var endLineIndex = lineNumber - 1;
// Validate all states up to and including endLineIndex
for (var lineIndex = this._tokenizationStateStore.invalidLineStartIndex; lineIndex <= endLineIndex; lineIndex++) {
var text = this._textModel.getLineContent(lineIndex + 1);
var lineStartState = this._tokenizationStateStore.getBeginState(lineIndex);
var r = safeTokenize(languageIdentifier, this._tokenizationSupport, text, lineStartState);
builder.add(lineIndex + 1, r.tokens);
this._tokenizationStateStore.setEndState(linesLength, lineIndex, r.endState);
lineIndex = this._tokenizationStateStore.invalidLineStartIndex - 1; // -1 because the outer loop increments it
}
};
TextModelTokenization.prototype._tokenizeViewport = function (builder, startLineNumber, endLineNumber) {
if (!this._tokenizationSupport) {
// nothing to do
return;
}
if (endLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) {
// nothing to do
return;
}
if (startLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) {
// tokenization has reached the viewport start...
this._updateTokensUntilLine(builder, endLineNumber);
return;
}
var nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(startLineNumber);
var fakeLines = [];
var initialState = null;
for (var i = startLineNumber - 1; nonWhitespaceColumn > 0 && i >= 1; i--) {
var newNonWhitespaceIndex = this._textModel.getLineFirstNonWhitespaceColumn(i);
if (newNonWhitespaceIndex === 0) {
continue;
}
if (newNonWhitespaceIndex < nonWhitespaceColumn) {
initialState = this._tokenizationStateStore.getBeginState(i - 1);
if (initialState) {
break;
}
fakeLines.push(this._textModel.getLineContent(i));
nonWhitespaceColumn = newNonWhitespaceIndex;
}
}
if (!initialState) {
initialState = this._tokenizationSupport.getInitialState();
}
var languageIdentifier = this._textModel.getLanguageIdentifier();
var state = initialState;
for (var i = fakeLines.length - 1; i >= 0; i--) {
var r = safeTokenize(languageIdentifier, this._tokenizationSupport, fakeLines[i], state);
state = r.endState;
}
for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
var text = this._textModel.getLineContent(lineNumber);
var r = safeTokenize(languageIdentifier, this._tokenizationSupport, text, state);
builder.add(lineNumber, r.tokens);
this._tokenizationStateStore.setFakeTokens(lineNumber - 1);
state = r.endState;
}
};
return TextModelTokenization;
}(lifecycle_1.Disposable));
exports.TextModelTokenization = TextModelTokenization;
function initializeTokenization(textModel) {
var languageIdentifier = textModel.getLanguageIdentifier();
var tokenizationSupport = (textModel.isTooLargeForTokenization()
? null
: modes_1.TokenizationRegistry.get(languageIdentifier.language));
var initialState = null;
if (tokenizationSupport) {
try {
initialState = tokenizationSupport.getInitialState();
}
catch (e) {
errors_1.onUnexpectedError(e);
tokenizationSupport = null;
}
}
return [tokenizationSupport, initialState];
}
function safeTokenize(languageIdentifier, tokenizationSupport, text, state) {
var r = null;
if (tokenizationSupport) {
try {
r = tokenizationSupport.tokenize2(text, state.clone(), 0);
}
catch (e) {
errors_1.onUnexpectedError(e);
}
}
if (!r) {
r = nullMode_1.nullTokenize2(languageIdentifier.id, text, state, 0);
}
lineTokens_1.LineTokens.convertToEndOffset(r.tokens, text.length);
return r;
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[30/*vs/editor/common/model/textModel*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/,25/*vs/base/common/uri*/,33/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,48/*vs/editor/common/model*/,342/*vs/editor/common/model/editStack*/,343/*vs/editor/common/model/indentationGuesser*/,344/*vs/editor/common/model/intervalTree*/,348/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/,346/*vs/editor/common/model/textModelEvents*/,144/*vs/editor/common/model/textModelSearch*/,482/*vs/editor/common/model/textModelTokens*/,109/*vs/editor/common/model/wordHelper*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,63/*vs/editor/common/modes/nullMode*/,145/*vs/editor/common/modes/supports*/,146/*vs/editor/common/modes/supports/richEditBrackets*/,21/*vs/base/common/types*/,157/*vs/editor/common/model/tokensStore*/,27/*vs/base/common/color*/]), function (require, exports, errors_1, event_1, lifecycle_1, strings, uri_1, editorOptions_1, position_1, range_1, selection_1, model, editStack_1, indentationGuesser_1, intervalTree_1, pieceTreeTextBufferBuilder_1, textModelEvents_1, textModelSearch_1, textModelTokens_1, wordHelper_1, languageConfigurationRegistry_1, nullMode_1, supports_1, richEditBrackets_1, types_1, tokensStore_1, color_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function createTextBufferBuilder() {
return new pieceTreeTextBufferBuilder_1.PieceTreeTextBufferBuilder();
}
function createTextBufferFactory(text) {
var builder = createTextBufferBuilder();
builder.acceptChunk(text);
return builder.finish();
}
exports.createTextBufferFactory = createTextBufferFactory;
function createTextBuffer(value, defaultEOL) {
var factory = (typeof value === 'string' ? createTextBufferFactory(value) : value);
return factory.create(defaultEOL);
}
exports.createTextBuffer = createTextBuffer;
var MODEL_ID = 0;
var LIMIT_FIND_COUNT = 999;
exports.LONG_LINE_BOUNDARY = 10000;
var invalidFunc = function () { throw new Error("Invalid change accessor"); };
var TextModel = /** @class */ (function (_super) {
__extends(TextModel, _super);
//#endregion
function TextModel(source, creationOptions, languageIdentifier, associatedResource) {
if (associatedResource === void 0) { associatedResource = null; }
var _this = _super.call(this) || this;
//#region Events
_this._onWillDispose = _this._register(new event_1.Emitter());
_this.onWillDispose = _this._onWillDispose.event;
_this._onDidChangeDecorations = _this._register(new DidChangeDecorationsEmitter());
_this.onDidChangeDecorations = _this._onDidChangeDecorations.event;
_this._onDidChangeLanguage = _this._register(new event_1.Emitter());
_this.onDidChangeLanguage = _this._onDidChangeLanguage.event;
_this._onDidChangeLanguageConfiguration = _this._register(new event_1.Emitter());
_this.onDidChangeLanguageConfiguration = _this._onDidChangeLanguageConfiguration.event;
_this._onDidChangeTokens = _this._register(new event_1.Emitter());
_this.onDidChangeTokens = _this._onDidChangeTokens.event;
_this._onDidChangeOptions = _this._register(new event_1.Emitter());
_this.onDidChangeOptions = _this._onDidChangeOptions.event;
_this._onDidChangeAttached = _this._register(new event_1.Emitter());
_this.onDidChangeAttached = _this._onDidChangeAttached.event;
_this._eventEmitter = _this._register(new DidChangeContentEmitter());
// Generate a new unique model id
MODEL_ID++;
_this.id = '$model' + MODEL_ID;
_this.isForSimpleWidget = creationOptions.isForSimpleWidget;
if (typeof associatedResource === 'undefined' || associatedResource === null) {
_this._associatedResource = uri_1.URI.parse('inmemory://model/' + MODEL_ID);
}
else {
_this._associatedResource = associatedResource;
}
_this._attachedEditorCount = 0;
_this._buffer = createTextBuffer(source, creationOptions.defaultEOL);
_this._options = TextModel.resolveOptions(_this._buffer, creationOptions);
var bufferLineCount = _this._buffer.getLineCount();
var bufferTextLength = _this._buffer.getValueLengthInRange(new range_1.Range(1, 1, bufferLineCount, _this._buffer.getLineLength(bufferLineCount) + 1), 0 /* TextDefined */);
// !!! Make a decision in the ctor and permanently respect this decision !!!
// If a model is too large at construction time, it will never get tokenized,
// under no circumstances.
if (creationOptions.largeFileOptimizations) {
_this._isTooLargeForTokenization = ((bufferTextLength > TextModel.LARGE_FILE_SIZE_THRESHOLD)
|| (bufferLineCount > TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD));
}
else {
_this._isTooLargeForTokenization = false;
}
_this._isTooLargeForSyncing = (bufferTextLength > TextModel.MODEL_SYNC_LIMIT);
_this._versionId = 1;
_this._alternativeVersionId = 1;
_this._isDisposed = false;
_this._isDisposing = false;
_this._languageIdentifier = languageIdentifier || nullMode_1.NULL_LANGUAGE_IDENTIFIER;
_this._languageRegistryListener = languageConfigurationRegistry_1.LanguageConfigurationRegistry.onDidChange(function (e) {
if (e.languageIdentifier.id === _this._languageIdentifier.id) {
_this._onDidChangeLanguageConfiguration.fire({});
}
});
_this._instanceId = strings.singleLetterHash(MODEL_ID);
_this._lastDecorationId = 0;
_this._decorations = Object.create(null);
_this._decorationsTree = new DecorationsTrees();
_this._commandManager = new editStack_1.EditStack(_this);
_this._isUndoing = false;
_this._isRedoing = false;
_this._trimAutoWhitespaceLines = null;
_this._tokens = new tokensStore_1.TokensStore();
_this._tokens2 = new tokensStore_1.TokensStore2();
_this._tokenization = new textModelTokens_1.TextModelTokenization(_this);
return _this;
}
TextModel.createFromString = function (text, options, languageIdentifier, uri) {
if (options === void 0) { options = TextModel.DEFAULT_CREATION_OPTIONS; }
if (languageIdentifier === void 0) { languageIdentifier = null; }
if (uri === void 0) { uri = null; }
return new TextModel(text, options, languageIdentifier, uri);
};
TextModel.resolveOptions = function (textBuffer, options) {
if (options.detectIndentation) {
var guessedIndentation = indentationGuesser_1.guessIndentation(textBuffer, options.tabSize, options.insertSpaces);
return new model.TextModelResolvedOptions({
tabSize: guessedIndentation.tabSize,
indentSize: guessedIndentation.tabSize,
insertSpaces: guessedIndentation.insertSpaces,
trimAutoWhitespace: options.trimAutoWhitespace,
defaultEOL: options.defaultEOL
});
}
return new model.TextModelResolvedOptions({
tabSize: options.tabSize,
indentSize: options.indentSize,
insertSpaces: options.insertSpaces,
trimAutoWhitespace: options.trimAutoWhitespace,
defaultEOL: options.defaultEOL
});
};
TextModel.prototype.onDidChangeRawContentFast = function (listener) {
return this._eventEmitter.fastEvent(function (e) { return listener(e.rawContentChangedEvent); });
};
TextModel.prototype.onDidChangeRawContent = function (listener) {
return this._eventEmitter.slowEvent(function (e) { return listener(e.rawContentChangedEvent); });
};
TextModel.prototype.onDidChangeContentFast = function (listener) {
return this._eventEmitter.fastEvent(function (e) { return listener(e.contentChangedEvent); });
};
TextModel.prototype.onDidChangeContent = function (listener) {
return this._eventEmitter.slowEvent(function (e) { return listener(e.contentChangedEvent); });
};
TextModel.prototype.dispose = function () {
this._isDisposing = true;
this._onWillDispose.fire();
this._languageRegistryListener.dispose();
this._tokenization.dispose();
this._isDisposed = true;
_super.prototype.dispose.call(this);
this._isDisposing = false;
};
TextModel.prototype._assertNotDisposed = function () {
if (this._isDisposed) {
throw new Error('Model is disposed!');
}
};
TextModel.prototype._emitContentChangedEvent = function (rawChange, change) {
if (this._isDisposing) {
// Do not confuse listeners by emitting any event after disposing
return;
}
this._eventEmitter.fire(new textModelEvents_1.InternalModelContentChangeEvent(rawChange, change));
};
TextModel.prototype.setValue = function (value) {
this._assertNotDisposed();
if (value === null) {
// There's nothing to do
return;
}
var textBuffer = createTextBuffer(value, this._options.defaultEOL);
this.setValueFromTextBuffer(textBuffer);
};
TextModel.prototype._createContentChanged2 = function (range, rangeOffset, rangeLength, text, isUndoing, isRedoing, isFlush) {
return {
changes: [{
range: range,
rangeOffset: rangeOffset,
rangeLength: rangeLength,
text: text,
}],
eol: this._buffer.getEOL(),
versionId: this.getVersionId(),
isUndoing: isUndoing,
isRedoing: isRedoing,
isFlush: isFlush
};
};
TextModel.prototype.setValueFromTextBuffer = function (textBuffer) {
this._assertNotDisposed();
if (textBuffer === null) {
// There's nothing to do
return;
}
var oldFullModelRange = this.getFullModelRange();
var oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
var endLineNumber = this.getLineCount();
var endColumn = this.getLineMaxColumn(endLineNumber);
this._buffer = textBuffer;
this._increaseVersionId();
// Flush all tokens
this._tokens.flush();
this._tokens2.flush();
// Destroy all my decorations
this._decorations = Object.create(null);
this._decorationsTree = new DecorationsTrees();
// Destroy my edit history and settings
this._commandManager = new editStack_1.EditStack(this);
this._trimAutoWhitespaceLines = null;
this._emitContentChangedEvent(new textModelEvents_1.ModelRawContentChangedEvent([
new textModelEvents_1.ModelRawFlush()
], this._versionId, false, false), this._createContentChanged2(new range_1.Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true));
};
TextModel.prototype.setEOL = function (eol) {
this._assertNotDisposed();
var newEOL = (eol === 1 /* CRLF */ ? '\r\n' : '\n');
if (this._buffer.getEOL() === newEOL) {
// Nothing to do
return;
}
var oldFullModelRange = this.getFullModelRange();
var oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
var endLineNumber = this.getLineCount();
var endColumn = this.getLineMaxColumn(endLineNumber);
this._onBeforeEOLChange();
this._buffer.setEOL(newEOL);
this._increaseVersionId();
this._onAfterEOLChange();
this._emitContentChangedEvent(new textModelEvents_1.ModelRawContentChangedEvent([
new textModelEvents_1.ModelRawEOLChanged()
], this._versionId, false, false), this._createContentChanged2(new range_1.Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false));
};
TextModel.prototype._onBeforeEOLChange = function () {
// Ensure all decorations get their `range` set.
var versionId = this.getVersionId();
var allDecorations = this._decorationsTree.search(0, false, false, versionId);
this._ensureNodesHaveRanges(allDecorations);
};
TextModel.prototype._onAfterEOLChange = function () {
// Transform back `range` to offsets
var versionId = this.getVersionId();
var allDecorations = this._decorationsTree.collectNodesPostOrder();
for (var i = 0, len = allDecorations.length; i < len; i++) {
var node = allDecorations[i];
var delta = node.cachedAbsoluteStart - node.start;
var startOffset = this._buffer.getOffsetAt(node.range.startLineNumber, node.range.startColumn);
var endOffset = this._buffer.getOffsetAt(node.range.endLineNumber, node.range.endColumn);
node.cachedAbsoluteStart = startOffset;
node.cachedAbsoluteEnd = endOffset;
node.cachedVersionId = versionId;
node.start = startOffset - delta;
node.end = endOffset - delta;
intervalTree_1.recomputeMaxEnd(node);
}
};
TextModel.prototype.onBeforeAttached = function () {
this._attachedEditorCount++;
if (this._attachedEditorCount === 1) {
this._onDidChangeAttached.fire(undefined);
}
};
TextModel.prototype.onBeforeDetached = function () {
this._attachedEditorCount--;
if (this._attachedEditorCount === 0) {
this._onDidChangeAttached.fire(undefined);
}
};
TextModel.prototype.isAttachedToEditor = function () {
return this._attachedEditorCount > 0;
};
TextModel.prototype.getAttachedEditorCount = function () {
return this._attachedEditorCount;
};
TextModel.prototype.isTooLargeForSyncing = function () {
return this._isTooLargeForSyncing;
};
TextModel.prototype.isTooLargeForTokenization = function () {
return this._isTooLargeForTokenization;
};
TextModel.prototype.isDisposed = function () {
return this._isDisposed;
};
TextModel.prototype.isDominatedByLongLines = function () {
this._assertNotDisposed();
if (this.isTooLargeForTokenization()) {
// Cannot word wrap huge files anyways, so it doesn't really matter
return false;
}
var smallLineCharCount = 0;
var longLineCharCount = 0;
var lineCount = this._buffer.getLineCount();
for (var lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
var lineLength = this._buffer.getLineLength(lineNumber);
if (lineLength >= exports.LONG_LINE_BOUNDARY) {
longLineCharCount += lineLength;
}
else {
smallLineCharCount += lineLength;
}
}
return (longLineCharCount > smallLineCharCount);
};
Object.defineProperty(TextModel.prototype, "uri", {
get: function () {
return this._associatedResource;
},
enumerable: true,
configurable: true
});
//#region Options
TextModel.prototype.getOptions = function () {
this._assertNotDisposed();
return this._options;
};
TextModel.prototype.getFormattingOptions = function () {
return {
tabSize: this._options.indentSize,
insertSpaces: this._options.insertSpaces
};
};
TextModel.prototype.updateOptions = function (_newOpts) {
this._assertNotDisposed();
var tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize;
var indentSize = (typeof _newOpts.indentSize !== 'undefined') ? _newOpts.indentSize : this._options.indentSize;
var insertSpaces = (typeof _newOpts.insertSpaces !== 'undefined') ? _newOpts.insertSpaces : this._options.insertSpaces;
var trimAutoWhitespace = (typeof _newOpts.trimAutoWhitespace !== 'undefined') ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;
var newOpts = new model.TextModelResolvedOptions({
tabSize: tabSize,
indentSize: indentSize,
insertSpaces: insertSpaces,
defaultEOL: this._options.defaultEOL,
trimAutoWhitespace: trimAutoWhitespace
});
if (this._options.equals(newOpts)) {
return;
}
var e = this._options.createChangeEvent(newOpts);
this._options = newOpts;
this._onDidChangeOptions.fire(e);
};
TextModel.prototype.detectIndentation = function (defaultInsertSpaces, defaultTabSize) {
this._assertNotDisposed();
var guessedIndentation = indentationGuesser_1.guessIndentation(this._buffer, defaultTabSize, defaultInsertSpaces);
this.updateOptions({
insertSpaces: guessedIndentation.insertSpaces,
tabSize: guessedIndentation.tabSize,
indentSize: guessedIndentation.tabSize,
});
};
TextModel._normalizeIndentationFromWhitespace = function (str, indentSize, insertSpaces) {
var spacesCnt = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) === '\t') {
spacesCnt += indentSize;
}
else {
spacesCnt++;
}
}
var result = '';
if (!insertSpaces) {
var tabsCnt = Math.floor(spacesCnt / indentSize);
spacesCnt = spacesCnt % indentSize;
for (var i = 0; i < tabsCnt; i++) {
result += '\t';
}
}
for (var i = 0; i < spacesCnt; i++) {
result += ' ';
}
return result;
};
TextModel.normalizeIndentation = function (str, indentSize, insertSpaces) {
var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str);
if (firstNonWhitespaceIndex === -1) {
firstNonWhitespaceIndex = str.length;
}
return TextModel._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex);
};
TextModel.prototype.normalizeIndentation = function (str) {
this._assertNotDisposed();
return TextModel.normalizeIndentation(str, this._options.indentSize, this._options.insertSpaces);
};
//#endregion
//#region Reading
TextModel.prototype.getVersionId = function () {
this._assertNotDisposed();
return this._versionId;
};
TextModel.prototype.mightContainRTL = function () {
return this._buffer.mightContainRTL();
};
TextModel.prototype.mightContainNonBasicASCII = function () {
return this._buffer.mightContainNonBasicASCII();
};
TextModel.prototype.getAlternativeVersionId = function () {
this._assertNotDisposed();
return this._alternativeVersionId;
};
TextModel.prototype.getOffsetAt = function (rawPosition) {
this._assertNotDisposed();
var position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, 0 /* Relaxed */);
return this._buffer.getOffsetAt(position.lineNumber, position.column);
};
TextModel.prototype.getPositionAt = function (rawOffset) {
this._assertNotDisposed();
var offset = (Math.min(this._buffer.getLength(), Math.max(0, rawOffset)));
return this._buffer.getPositionAt(offset);
};
TextModel.prototype._increaseVersionId = function () {
this._versionId = this._versionId + 1;
this._alternativeVersionId = this._versionId;
};
TextModel.prototype._overwriteAlternativeVersionId = function (newAlternativeVersionId) {
this._alternativeVersionId = newAlternativeVersionId;
};
TextModel.prototype.getValue = function (eol, preserveBOM) {
if (preserveBOM === void 0) { preserveBOM = false; }
this._assertNotDisposed();
var fullModelRange = this.getFullModelRange();
var fullModelValue = this.getValueInRange(fullModelRange, eol);
if (preserveBOM) {
return this._buffer.getBOM() + fullModelValue;
}
return fullModelValue;
};
TextModel.prototype.getValueLength = function (eol, preserveBOM) {
if (preserveBOM === void 0) { preserveBOM = false; }
this._assertNotDisposed();
var fullModelRange = this.getFullModelRange();
var fullModelValue = this.getValueLengthInRange(fullModelRange, eol);
if (preserveBOM) {
return this._buffer.getBOM().length + fullModelValue;
}
return fullModelValue;
};
TextModel.prototype.getValueInRange = function (rawRange, eol) {
if (eol === void 0) { eol = 0 /* TextDefined */; }
this._assertNotDisposed();
return this._buffer.getValueInRange(this.validateRange(rawRange), eol);
};
TextModel.prototype.getValueLengthInRange = function (rawRange, eol) {
if (eol === void 0) { eol = 0 /* TextDefined */; }
this._assertNotDisposed();
return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);
};
TextModel.prototype.getCharacterCountInRange = function (rawRange, eol) {
if (eol === void 0) { eol = 0 /* TextDefined */; }
this._assertNotDisposed();
return this._buffer.getCharacterCountInRange(this.validateRange(rawRange), eol);
};
TextModel.prototype.getLineCount = function () {
this._assertNotDisposed();
return this._buffer.getLineCount();
};
TextModel.prototype.getLineContent = function (lineNumber) {
this._assertNotDisposed();
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._buffer.getLineContent(lineNumber);
};
TextModel.prototype.getLineLength = function (lineNumber) {
this._assertNotDisposed();
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._buffer.getLineLength(lineNumber);
};
TextModel.prototype.getLinesContent = function () {
this._assertNotDisposed();
return this._buffer.getLinesContent();
};
TextModel.prototype.getEOL = function () {
this._assertNotDisposed();
return this._buffer.getEOL();
};
TextModel.prototype.getLineMinColumn = function (lineNumber) {
this._assertNotDisposed();
return 1;
};
TextModel.prototype.getLineMaxColumn = function (lineNumber) {
this._assertNotDisposed();
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._buffer.getLineLength(lineNumber) + 1;
};
TextModel.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) {
this._assertNotDisposed();
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);
};
TextModel.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) {
this._assertNotDisposed();
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._buffer.getLineLastNonWhitespaceColumn(lineNumber);
};
/**
* Validates `range` is within buffer bounds, but allows it to sit in between surrogate pairs, etc.
* Will try to not allocate if possible.
*/
TextModel.prototype._validateRangeRelaxedNoAllocations = function (range) {
var linesCount = this._buffer.getLineCount();
var initialStartLineNumber = range.startLineNumber;
var initialStartColumn = range.startColumn;
var startLineNumber;
var startColumn;
if (initialStartLineNumber < 1) {
startLineNumber = 1;
startColumn = 1;
}
else if (initialStartLineNumber > linesCount) {
startLineNumber = linesCount;
startColumn = this.getLineMaxColumn(startLineNumber);
}
else {
startLineNumber = initialStartLineNumber | 0;
if (initialStartColumn <= 1) {
startColumn = 1;
}
else {
var maxColumn = this.getLineMaxColumn(startLineNumber);
if (initialStartColumn >= maxColumn) {
startColumn = maxColumn;
}
else {
startColumn = initialStartColumn | 0;
}
}
}
var initialEndLineNumber = range.endLineNumber;
var initialEndColumn = range.endColumn;
var endLineNumber;
var endColumn;
if (initialEndLineNumber < 1) {
endLineNumber = 1;
endColumn = 1;
}
else if (initialEndLineNumber > linesCount) {
endLineNumber = linesCount;
endColumn = this.getLineMaxColumn(endLineNumber);
}
else {
endLineNumber = initialEndLineNumber | 0;
if (initialEndColumn <= 1) {
endColumn = 1;
}
else {
var maxColumn = this.getLineMaxColumn(endLineNumber);
if (initialEndColumn >= maxColumn) {
endColumn = maxColumn;
}
else {
endColumn = initialEndColumn | 0;
}
}
}
if (initialStartLineNumber === startLineNumber
&& initialStartColumn === startColumn
&& initialEndLineNumber === endLineNumber
&& initialEndColumn === endColumn
&& range instanceof range_1.Range
&& !(range instanceof selection_1.Selection)) {
return range;
}
return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
};
TextModel.prototype._isValidPosition = function (lineNumber, column, validationType) {
if (typeof lineNumber !== 'number' || typeof column !== 'number') {
return false;
}
if (isNaN(lineNumber) || isNaN(column)) {
return false;
}
if (lineNumber < 1 || column < 1) {
return false;
}
if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) {
return false;
}
var lineCount = this._buffer.getLineCount();
if (lineNumber > lineCount) {
return false;
}
if (column === 1) {
return true;
}
var maxColumn = this.getLineMaxColumn(lineNumber);
if (column > maxColumn) {
return false;
}
if (validationType === 1 /* SurrogatePairs */) {
// !!At this point, column > 1
var charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
if (strings.isHighSurrogate(charCodeBefore)) {
return false;
}
}
return true;
};
TextModel.prototype._validatePosition = function (_lineNumber, _column, validationType) {
var lineNumber = Math.floor((typeof _lineNumber === 'number' && !isNaN(_lineNumber)) ? _lineNumber : 1);
var column = Math.floor((typeof _column === 'number' && !isNaN(_column)) ? _column : 1);
var lineCount = this._buffer.getLineCount();
if (lineNumber < 1) {
return new position_1.Position(1, 1);
}
if (lineNumber > lineCount) {
return new position_1.Position(lineCount, this.getLineMaxColumn(lineCount));
}
if (column <= 1) {
return new position_1.Position(lineNumber, 1);
}
var maxColumn = this.getLineMaxColumn(lineNumber);
if (column >= maxColumn) {
return new position_1.Position(lineNumber, maxColumn);
}
if (validationType === 1 /* SurrogatePairs */) {
// If the position would end up in the middle of a high-low surrogate pair,
// we move it to before the pair
// !!At this point, column > 1
var charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
if (strings.isHighSurrogate(charCodeBefore)) {
return new position_1.Position(lineNumber, column - 1);
}
}
return new position_1.Position(lineNumber, column);
};
TextModel.prototype.validatePosition = function (position) {
var validationType = 1 /* SurrogatePairs */;
this._assertNotDisposed();
// Avoid object allocation and cover most likely case
if (position instanceof position_1.Position) {
if (this._isValidPosition(position.lineNumber, position.column, validationType)) {
return position;
}
}
return this._validatePosition(position.lineNumber, position.column, validationType);
};
TextModel.prototype._isValidRange = function (range, validationType) {
var startLineNumber = range.startLineNumber;
var startColumn = range.startColumn;
var endLineNumber = range.endLineNumber;
var endColumn = range.endColumn;
if (!this._isValidPosition(startLineNumber, startColumn, 0 /* Relaxed */)) {
return false;
}
if (!this._isValidPosition(endLineNumber, endColumn, 0 /* Relaxed */)) {
return false;
}
if (validationType === 1 /* SurrogatePairs */) {
var charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);
var charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);
var startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart);
var endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd);
if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
return true;
}
return false;
}
return true;
};
TextModel.prototype.validateRange = function (_range) {
var validationType = 1 /* SurrogatePairs */;
this._assertNotDisposed();
// Avoid object allocation and cover most likely case
if ((_range instanceof range_1.Range) && !(_range instanceof selection_1.Selection)) {
if (this._isValidRange(_range, validationType)) {
return _range;
}
}
var start = this._validatePosition(_range.startLineNumber, _range.startColumn, 0 /* Relaxed */);
var end = this._validatePosition(_range.endLineNumber, _range.endColumn, 0 /* Relaxed */);
var startLineNumber = start.lineNumber;
var startColumn = start.column;
var endLineNumber = end.lineNumber;
var endColumn = end.column;
if (validationType === 1 /* SurrogatePairs */) {
var charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);
var charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);
var startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart);
var endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd);
if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
}
if (startLineNumber === endLineNumber && startColumn === endColumn) {
// do not expand a collapsed range, simply move it to a valid location
return new range_1.Range(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1);
}
if (startInsideSurrogatePair && endInsideSurrogatePair) {
// expand range at both ends
return new range_1.Range(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1);
}
if (startInsideSurrogatePair) {
// only expand range at the start
return new range_1.Range(startLineNumber, startColumn - 1, endLineNumber, endColumn);
}
// only expand range at the end
return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn + 1);
}
return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
};
TextModel.prototype.modifyPosition = function (rawPosition, offset) {
this._assertNotDisposed();
var candidate = this.getOffsetAt(rawPosition) + offset;
return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate)));
};
TextModel.prototype.getFullModelRange = function () {
this._assertNotDisposed();
var lineCount = this.getLineCount();
return new range_1.Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
};
TextModel.prototype.findMatchesLineByLine = function (searchRange, searchData, captureMatches, limitResultCount) {
return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
};
TextModel.prototype.findMatches = function (searchString, rawSearchScope, isRegex, matchCase, wordSeparators, captureMatches, limitResultCount) {
if (limitResultCount === void 0) { limitResultCount = LIMIT_FIND_COUNT; }
this._assertNotDisposed();
var searchRange;
if (range_1.Range.isIRange(rawSearchScope)) {
searchRange = this.validateRange(rawSearchScope);
}
else {
searchRange = this.getFullModelRange();
}
if (!isRegex && searchString.indexOf('\n') < 0) {
// not regex, not multi line
var searchParams = new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators);
var searchData = searchParams.parseSearchRequest();
if (!searchData) {
return [];
}
return this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
}
return textModelSearch_1.TextModelSearch.findMatches(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchRange, captureMatches, limitResultCount);
};
TextModel.prototype.findNextMatch = function (searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) {
this._assertNotDisposed();
var searchStart = this.validatePosition(rawSearchStart);
if (!isRegex && searchString.indexOf('\n') < 0) {
var searchParams = new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators);
var searchData = searchParams.parseSearchRequest();
if (!searchData) {
return null;
}
var lineCount = this.getLineCount();
var searchRange = new range_1.Range(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount));
var ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
textModelSearch_1.TextModelSearch.findNextMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
if (ret.length > 0) {
return ret[0];
}
searchRange = new range_1.Range(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber));
ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
if (ret.length > 0) {
return ret[0];
}
return null;
}
return textModelSearch_1.TextModelSearch.findNextMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
};
TextModel.prototype.findPreviousMatch = function (searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) {
this._assertNotDisposed();
var searchStart = this.validatePosition(rawSearchStart);
return textModelSearch_1.TextModelSearch.findPreviousMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
};
//#endregion
//#region Editing
TextModel.prototype.pushStackElement = function () {
this._commandManager.pushStackElement();
};
TextModel.prototype.pushEOL = function (eol) {
var currentEOL = (this.getEOL() === '\n' ? 0 /* LF */ : 1 /* CRLF */);
if (currentEOL === eol) {
return;
}
try {
this._onDidChangeDecorations.beginDeferredEmit();
this._eventEmitter.beginDeferredEmit();
this._commandManager.pushEOL(eol);
}
finally {
this._eventEmitter.endDeferredEmit();
this._onDidChangeDecorations.endDeferredEmit();
}
};
TextModel.prototype.pushEditOperations = function (beforeCursorState, editOperations, cursorStateComputer) {
try {
this._onDidChangeDecorations.beginDeferredEmit();
this._eventEmitter.beginDeferredEmit();
return this._pushEditOperations(beforeCursorState, editOperations, cursorStateComputer);
}
finally {
this._eventEmitter.endDeferredEmit();
this._onDidChangeDecorations.endDeferredEmit();
}
};
TextModel.prototype._pushEditOperations = function (beforeCursorState, editOperations, cursorStateComputer) {
var _this = this;
if (this._options.trimAutoWhitespace && this._trimAutoWhitespaceLines) {
// Go through each saved line number and insert a trim whitespace edit
// if it is safe to do so (no conflicts with other edits).
var incomingEdits = editOperations.map(function (op) {
return {
range: _this.validateRange(op.range),
text: op.text
};
});
// Sometimes, auto-formatters change ranges automatically which can cause undesired auto whitespace trimming near the cursor
// We'll use the following heuristic: if the edits occur near the cursor, then it's ok to trim auto whitespace
var editsAreNearCursors = true;
for (var i = 0, len = beforeCursorState.length; i < len; i++) {
var sel = beforeCursorState[i];
var foundEditNearSel = false;
for (var j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
var editRange = incomingEdits[j].range;
var selIsAbove = editRange.startLineNumber > sel.endLineNumber;
var selIsBelow = sel.startLineNumber > editRange.endLineNumber;
if (!selIsAbove && !selIsBelow) {
foundEditNearSel = true;
break;
}
}
if (!foundEditNearSel) {
editsAreNearCursors = false;
break;
}
}
if (editsAreNearCursors) {
for (var i = 0, len = this._trimAutoWhitespaceLines.length; i < len; i++) {
var trimLineNumber = this._trimAutoWhitespaceLines[i];
var maxLineColumn = this.getLineMaxColumn(trimLineNumber);
var allowTrimLine = true;
for (var j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
var editRange = incomingEdits[j].range;
var editText = incomingEdits[j].text;
if (trimLineNumber < editRange.startLineNumber || trimLineNumber > editRange.endLineNumber) {
// `trimLine` is completely outside this edit
continue;
}
// At this point:
// editRange.startLineNumber <= trimLine <= editRange.endLineNumber
if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn
&& editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === '\n') {
// This edit inserts a new line (and maybe other text) after `trimLine`
continue;
}
if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1
&& editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === '\n') {
// This edit inserts a new line (and maybe other text) before `trimLine`
continue;
}
// Looks like we can't trim this line as it would interfere with an incoming edit
allowTrimLine = false;
break;
}
if (allowTrimLine) {
editOperations.push({
range: new range_1.Range(trimLineNumber, 1, trimLineNumber, maxLineColumn),
text: null
});
}
}
}
this._trimAutoWhitespaceLines = null;
}
return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer);
};
TextModel.prototype.applyEdits = function (rawOperations) {
try {
this._onDidChangeDecorations.beginDeferredEmit();
this._eventEmitter.beginDeferredEmit();
return this._applyEdits(rawOperations);
}
finally {
this._eventEmitter.endDeferredEmit();
this._onDidChangeDecorations.endDeferredEmit();
}
};
TextModel.prototype._applyEdits = function (rawOperations) {
for (var i = 0, len = rawOperations.length; i < len; i++) {
rawOperations[i].range = this.validateRange(rawOperations[i].range);
}
var oldLineCount = this._buffer.getLineCount();
var result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace);
var newLineCount = this._buffer.getLineCount();
var contentChanges = result.changes;
this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers;
if (contentChanges.length !== 0) {
var rawContentChanges = [];
var lineCount = oldLineCount;
for (var i = 0, len = contentChanges.length; i < len; i++) {
var change = contentChanges[i];
var _a = tokensStore_1.countEOL(change.text), eolCount = _a[0], firstLineLength = _a[1], lastLineLength = _a[2];
this._tokens.acceptEdit(change.range, eolCount, firstLineLength);
this._tokens2.acceptEdit(change.range, eolCount, firstLineLength, lastLineLength, change.text.length > 0 ? change.text.charCodeAt(0) : 0 /* Null */);
this._onDidChangeDecorations.fire();
this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);
var startLineNumber = change.range.startLineNumber;
var endLineNumber = change.range.endLineNumber;
var deletingLinesCnt = endLineNumber - startLineNumber;
var insertingLinesCnt = eolCount;
var editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
var changeLineCountDelta = (insertingLinesCnt - deletingLinesCnt);
for (var j = editingLinesCnt; j >= 0; j--) {
var editLineNumber = startLineNumber + j;
var currentEditLineNumber = newLineCount - lineCount - changeLineCountDelta + editLineNumber;
rawContentChanges.push(new textModelEvents_1.ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber)));
}
if (editingLinesCnt < deletingLinesCnt) {
// Must delete some lines
var spliceStartLineNumber = startLineNumber + editingLinesCnt;
rawContentChanges.push(new textModelEvents_1.ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber));
}
if (editingLinesCnt < insertingLinesCnt) {
// Must insert some lines
var spliceLineNumber = startLineNumber + editingLinesCnt;
var cnt = insertingLinesCnt - editingLinesCnt;
var fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1;
var newLines = [];
for (var i_1 = 0; i_1 < cnt; i_1++) {
var lineNumber = fromLineNumber + i_1;
newLines[lineNumber - fromLineNumber] = this.getLineContent(lineNumber);
}
rawContentChanges.push(new textModelEvents_1.ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines));
}
lineCount += changeLineCountDelta;
}
this._increaseVersionId();
this._emitContentChangedEvent(new textModelEvents_1.ModelRawContentChangedEvent(rawContentChanges, this.getVersionId(), this._isUndoing, this._isRedoing), {
changes: contentChanges,
eol: this._buffer.getEOL(),
versionId: this.getVersionId(),
isUndoing: this._isUndoing,
isRedoing: this._isRedoing,
isFlush: false
});
}
return result.reverseEdits;
};
TextModel.prototype._undo = function () {
this._isUndoing = true;
var r = this._commandManager.undo();
this._isUndoing = false;
if (!r) {
return null;
}
this._overwriteAlternativeVersionId(r.recordedVersionId);
return r.selections;
};
TextModel.prototype.undo = function () {
try {
this._onDidChangeDecorations.beginDeferredEmit();
this._eventEmitter.beginDeferredEmit();
return this._undo();
}
finally {
this._eventEmitter.endDeferredEmit();
this._onDidChangeDecorations.endDeferredEmit();
}
};
TextModel.prototype.canUndo = function () {
return this._commandManager.canUndo();
};
TextModel.prototype._redo = function () {
this._isRedoing = true;
var r = this._commandManager.redo();
this._isRedoing = false;
if (!r) {
return null;
}
this._overwriteAlternativeVersionId(r.recordedVersionId);
return r.selections;
};
TextModel.prototype.redo = function () {
try {
this._onDidChangeDecorations.beginDeferredEmit();
this._eventEmitter.beginDeferredEmit();
return this._redo();
}
finally {
this._eventEmitter.endDeferredEmit();
this._onDidChangeDecorations.endDeferredEmit();
}
};
TextModel.prototype.canRedo = function () {
return this._commandManager.canRedo();
};
//#endregion
//#region Decorations
TextModel.prototype.changeDecorations = function (callback, ownerId) {
if (ownerId === void 0) { ownerId = 0; }
this._assertNotDisposed();
try {
this._onDidChangeDecorations.beginDeferredEmit();
return this._changeDecorations(ownerId, callback);
}
finally {
this._onDidChangeDecorations.endDeferredEmit();
}
};
TextModel.prototype._changeDecorations = function (ownerId, callback) {
var _this = this;
var changeAccessor = {
addDecoration: function (range, options) {
_this._onDidChangeDecorations.fire();
return _this._deltaDecorationsImpl(ownerId, [], [{ range: range, options: options }])[0];
},
changeDecoration: function (id, newRange) {
_this._onDidChangeDecorations.fire();
_this._changeDecorationImpl(id, newRange);
},
changeDecorationOptions: function (id, options) {
_this._onDidChangeDecorations.fire();
_this._changeDecorationOptionsImpl(id, _normalizeOptions(options));
},
removeDecoration: function (id) {
_this._onDidChangeDecorations.fire();
_this._deltaDecorationsImpl(ownerId, [id], []);
},
deltaDecorations: function (oldDecorations, newDecorations) {
if (oldDecorations.length === 0 && newDecorations.length === 0) {
// nothing to do
return [];
}
_this._onDidChangeDecorations.fire();
return _this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
}
};
var result = null;
try {
result = callback(changeAccessor);
}
catch (e) {
errors_1.onUnexpectedError(e);
}
// Invalidate change accessor
changeAccessor.addDecoration = invalidFunc;
changeAccessor.changeDecoration = invalidFunc;
changeAccessor.changeDecorationOptions = invalidFunc;
changeAccessor.removeDecoration = invalidFunc;
changeAccessor.deltaDecorations = invalidFunc;
return result;
};
TextModel.prototype.deltaDecorations = function (oldDecorations, newDecorations, ownerId) {
if (ownerId === void 0) { ownerId = 0; }
this._assertNotDisposed();
if (!oldDecorations) {
oldDecorations = [];
}
if (oldDecorations.length === 0 && newDecorations.length === 0) {
// nothing to do
return [];
}
try {
this._onDidChangeDecorations.beginDeferredEmit();
this._onDidChangeDecorations.fire();
return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
}
finally {
this._onDidChangeDecorations.endDeferredEmit();
}
};
TextModel.prototype._getTrackedRange = function (id) {
return this.getDecorationRange(id);
};
TextModel.prototype._setTrackedRange = function (id, newRange, newStickiness) {
var node = (id ? this._decorations[id] : null);
if (!node) {
if (!newRange) {
// node doesn't exist, the request is to delete => nothing to do
return null;
}
// node doesn't exist, the request is to set => add the tracked range
return this._deltaDecorationsImpl(0, [], [{ range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness] }])[0];
}
if (!newRange) {
// node exists, the request is to delete => delete node
this._decorationsTree.delete(node);
delete this._decorations[node.id];
return null;
}
// node exists, the request is to set => change the tracked range and its options
var range = this._validateRangeRelaxedNoAllocations(newRange);
var startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
var endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
this._decorationsTree.delete(node);
node.reset(this.getVersionId(), startOffset, endOffset, range);
node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);
this._decorationsTree.insert(node);
return node.id;
};
TextModel.prototype.removeAllDecorationsWithOwnerId = function (ownerId) {
if (this._isDisposed) {
return;
}
var nodes = this._decorationsTree.collectNodesFromOwner(ownerId);
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
this._decorationsTree.delete(node);
delete this._decorations[node.id];
}
};
TextModel.prototype.getDecorationOptions = function (decorationId) {
var node = this._decorations[decorationId];
if (!node) {
return null;
}
return node.options;
};
TextModel.prototype.getDecorationRange = function (decorationId) {
var node = this._decorations[decorationId];
if (!node) {
return null;
}
var versionId = this.getVersionId();
if (node.cachedVersionId !== versionId) {
this._decorationsTree.resolveNode(node, versionId);
}
if (node.range === null) {
node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
}
return node.range;
};
TextModel.prototype.getLineDecorations = function (lineNumber, ownerId, filterOutValidation) {
if (ownerId === void 0) { ownerId = 0; }
if (filterOutValidation === void 0) { filterOutValidation = false; }
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
return [];
}
return this.getLinesDecorations(lineNumber, lineNumber, ownerId, filterOutValidation);
};
TextModel.prototype.getLinesDecorations = function (_startLineNumber, _endLineNumber, ownerId, filterOutValidation) {
if (ownerId === void 0) { ownerId = 0; }
if (filterOutValidation === void 0) { filterOutValidation = false; }
var lineCount = this.getLineCount();
var startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber));
var endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber));
var endColumn = this.getLineMaxColumn(endLineNumber);
return this._getDecorationsInRange(new range_1.Range(startLineNumber, 1, endLineNumber, endColumn), ownerId, filterOutValidation);
};
TextModel.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) {
if (ownerId === void 0) { ownerId = 0; }
if (filterOutValidation === void 0) { filterOutValidation = false; }
var validatedRange = this.validateRange(range);
return this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation);
};
TextModel.prototype.getOverviewRulerDecorations = function (ownerId, filterOutValidation) {
if (ownerId === void 0) { ownerId = 0; }
if (filterOutValidation === void 0) { filterOutValidation = false; }
var versionId = this.getVersionId();
var result = this._decorationsTree.search(ownerId, filterOutValidation, true, versionId);
return this._ensureNodesHaveRanges(result);
};
TextModel.prototype.getAllDecorations = function (ownerId, filterOutValidation) {
if (ownerId === void 0) { ownerId = 0; }
if (filterOutValidation === void 0) { filterOutValidation = false; }
var versionId = this.getVersionId();
var result = this._decorationsTree.search(ownerId, filterOutValidation, false, versionId);
return this._ensureNodesHaveRanges(result);
};
TextModel.prototype._getDecorationsInRange = function (filterRange, filterOwnerId, filterOutValidation) {
var startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn);
var endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn);
var versionId = this.getVersionId();
var result = this._decorationsTree.intervalSearch(startOffset, endOffset, filterOwnerId, filterOutValidation, versionId);
return this._ensureNodesHaveRanges(result);
};
TextModel.prototype._ensureNodesHaveRanges = function (nodes) {
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
if (node.range === null) {
node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
}
}
return nodes;
};
TextModel.prototype._getRangeAt = function (start, end) {
return this._buffer.getRangeAt(start, end - start);
};
TextModel.prototype._changeDecorationImpl = function (decorationId, _range) {
var node = this._decorations[decorationId];
if (!node) {
return;
}
var range = this._validateRangeRelaxedNoAllocations(_range);
var startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
var endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
this._decorationsTree.delete(node);
node.reset(this.getVersionId(), startOffset, endOffset, range);
this._decorationsTree.insert(node);
};
TextModel.prototype._changeDecorationOptionsImpl = function (decorationId, options) {
var node = this._decorations[decorationId];
if (!node) {
return;
}
var nodeWasInOverviewRuler = (node.options.overviewRuler && node.options.overviewRuler.color ? true : false);
var nodeIsInOverviewRuler = (options.overviewRuler && options.overviewRuler.color ? true : false);
if (nodeWasInOverviewRuler !== nodeIsInOverviewRuler) {
// Delete + Insert due to an overview ruler status change
this._decorationsTree.delete(node);
node.setOptions(options);
this._decorationsTree.insert(node);
}
else {
node.setOptions(options);
}
};
TextModel.prototype._deltaDecorationsImpl = function (ownerId, oldDecorationsIds, newDecorations) {
var versionId = this.getVersionId();
var oldDecorationsLen = oldDecorationsIds.length;
var oldDecorationIndex = 0;
var newDecorationsLen = newDecorations.length;
var newDecorationIndex = 0;
var result = new Array(newDecorationsLen);
while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {
var node = null;
if (oldDecorationIndex < oldDecorationsLen) {
// (1) get ourselves an old node
do {
node = this._decorations[oldDecorationsIds[oldDecorationIndex++]];
} while (!node && oldDecorationIndex < oldDecorationsLen);
// (2) remove the node from the tree (if it exists)
if (node) {
this._decorationsTree.delete(node);
}
}
if (newDecorationIndex < newDecorationsLen) {
// (3) create a new node if necessary
if (!node) {
var internalDecorationId = (++this._lastDecorationId);
var decorationId = this._instanceId + ";" + internalDecorationId;
node = new intervalTree_1.IntervalNode(decorationId, 0, 0);
this._decorations[decorationId] = node;
}
// (4) initialize node
var newDecoration = newDecorations[newDecorationIndex];
var range = this._validateRangeRelaxedNoAllocations(newDecoration.range);
var options = _normalizeOptions(newDecoration.options);
var startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
var endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
node.ownerId = ownerId;
node.reset(versionId, startOffset, endOffset, range);
node.setOptions(options);
this._decorationsTree.insert(node);
result[newDecorationIndex] = node.id;
newDecorationIndex++;
}
else {
if (node) {
delete this._decorations[node.id];
}
}
}
return result;
};
//#endregion
//#region Tokenization
TextModel.prototype.setLineTokens = function (lineNumber, tokens) {
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), tokens);
};
TextModel.prototype.setTokens = function (tokens) {
if (tokens.length === 0) {
return;
}
var ranges = [];
for (var i = 0, len = tokens.length; i < len; i++) {
var element = tokens[i];
ranges.push({ fromLineNumber: element.startLineNumber, toLineNumber: element.startLineNumber + element.tokens.length - 1 });
for (var j = 0, lenJ = element.tokens.length; j < lenJ; j++) {
this.setLineTokens(element.startLineNumber + j, element.tokens[j]);
}
}
this._emitModelTokensChangedEvent({
tokenizationSupportChanged: false,
ranges: ranges
});
};
TextModel.prototype.setSemanticTokens = function (tokens) {
this._tokens2.set(tokens);
this._emitModelTokensChangedEvent({
tokenizationSupportChanged: false,
ranges: [{ fromLineNumber: 1, toLineNumber: this.getLineCount() }]
});
};
TextModel.prototype.tokenizeViewport = function (startLineNumber, endLineNumber) {
startLineNumber = Math.max(1, startLineNumber);
endLineNumber = Math.min(this._buffer.getLineCount(), endLineNumber);
this._tokenization.tokenizeViewport(startLineNumber, endLineNumber);
};
TextModel.prototype.clearTokens = function () {
this._tokens.flush();
this._emitModelTokensChangedEvent({
tokenizationSupportChanged: true,
ranges: [{
fromLineNumber: 1,
toLineNumber: this._buffer.getLineCount()
}]
});
};
TextModel.prototype._emitModelTokensChangedEvent = function (e) {
if (!this._isDisposing) {
this._onDidChangeTokens.fire(e);
}
};
TextModel.prototype.resetTokenization = function () {
this._tokenization.reset();
};
TextModel.prototype.forceTokenization = function (lineNumber) {
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
this._tokenization.forceTokenization(lineNumber);
};
TextModel.prototype.isCheapToTokenize = function (lineNumber) {
return this._tokenization.isCheapToTokenize(lineNumber);
};
TextModel.prototype.tokenizeIfCheap = function (lineNumber) {
if (this.isCheapToTokenize(lineNumber)) {
this.forceTokenization(lineNumber);
}
};
TextModel.prototype.getLineTokens = function (lineNumber) {
if (lineNumber < 1 || lineNumber > this.getLineCount()) {
throw new Error('Illegal value for lineNumber');
}
return this._getLineTokens(lineNumber);
};
TextModel.prototype._getLineTokens = function (lineNumber) {
var lineText = this.getLineContent(lineNumber);
var syntacticTokens = this._tokens.getTokens(this._languageIdentifier.id, lineNumber - 1, lineText);
return this._tokens2.addSemanticTokens(lineNumber, syntacticTokens);
};
TextModel.prototype.getLanguageIdentifier = function () {
return this._languageIdentifier;
};
TextModel.prototype.getModeId = function () {
return this._languageIdentifier.language;
};
TextModel.prototype.setMode = function (languageIdentifier) {
if (this._languageIdentifier.id === languageIdentifier.id) {
// There's nothing to do
return;
}
var e = {
oldLanguage: this._languageIdentifier.language,
newLanguage: languageIdentifier.language
};
this._languageIdentifier = languageIdentifier;
this._onDidChangeLanguage.fire(e);
this._onDidChangeLanguageConfiguration.fire({});
};
TextModel.prototype.getLanguageIdAtPosition = function (lineNumber, column) {
var position = this.validatePosition(new position_1.Position(lineNumber, column));
var lineTokens = this.getLineTokens(position.lineNumber);
return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
};
// Having tokens allows implementing additional helper methods
TextModel.prototype.getWordAtPosition = function (_position) {
this._assertNotDisposed();
var position = this.validatePosition(_position);
var lineContent = this.getLineContent(position.lineNumber);
var lineTokens = this._getLineTokens(position.lineNumber);
var tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
// (1). First try checking right biased word
var _a = TextModel._findLanguageBoundaries(lineTokens, tokenIndex), rbStartOffset = _a[0], rbEndOffset = _a[1];
var rightBiasedWord = wordHelper_1.getWordAtText(position.column, languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex)), lineContent.substring(rbStartOffset, rbEndOffset), rbStartOffset);
// Make sure the result touches the original passed in position
if (rightBiasedWord && rightBiasedWord.startColumn <= _position.column && _position.column <= rightBiasedWord.endColumn) {
return rightBiasedWord;
}
// (2). Else, if we were at a language boundary, check the left biased word
if (tokenIndex > 0 && rbStartOffset === position.column - 1) {
// edge case, where `position` sits between two tokens belonging to two different languages
var _b = TextModel._findLanguageBoundaries(lineTokens, tokenIndex - 1), lbStartOffset = _b[0], lbEndOffset = _b[1];
var leftBiasedWord = wordHelper_1.getWordAtText(position.column, languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex - 1)), lineContent.substring(lbStartOffset, lbEndOffset), lbStartOffset);
// Make sure the result touches the original passed in position
if (leftBiasedWord && leftBiasedWord.startColumn <= _position.column && _position.column <= leftBiasedWord.endColumn) {
return leftBiasedWord;
}
}
return null;
};
TextModel._findLanguageBoundaries = function (lineTokens, tokenIndex) {
var languageId = lineTokens.getLanguageId(tokenIndex);
// go left until a different language is hit
var startOffset = 0;
for (var i = tokenIndex; i >= 0 && lineTokens.getLanguageId(i) === languageId; i--) {
startOffset = lineTokens.getStartOffset(i);
}
// go right until a different language is hit
var endOffset = lineTokens.getLineContent().length;
for (var i = tokenIndex, tokenCount = lineTokens.getCount(); i < tokenCount && lineTokens.getLanguageId(i) === languageId; i++) {
endOffset = lineTokens.getEndOffset(i);
}
return [startOffset, endOffset];
};
TextModel.prototype.getWordUntilPosition = function (position) {
var wordAtPosition = this.getWordAtPosition(position);
if (!wordAtPosition) {
return {
word: '',
startColumn: position.column,
endColumn: position.column
};
}
return {
word: wordAtPosition.word.substr(0, position.column - wordAtPosition.startColumn),
startColumn: wordAtPosition.startColumn,
endColumn: position.column
};
};
TextModel.prototype.findMatchingBracketUp = function (_bracket, _position) {
var bracket = _bracket.toLowerCase();
var position = this.validatePosition(_position);
var lineTokens = this._getLineTokens(position.lineNumber);
var languageId = lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
var bracketsSupport = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
if (!bracketsSupport) {
return null;
}
var data = bracketsSupport.textIsBracket[bracket];
if (!data) {
return null;
}
return this._findMatchingBracketUp(data, position);
};
TextModel.prototype.matchBracket = function (position) {
return this._matchBracket(this.validatePosition(position));
};
TextModel.prototype._matchBracket = function (position) {
var lineNumber = position.lineNumber;
var lineTokens = this._getLineTokens(lineNumber);
var tokenCount = lineTokens.getCount();
var lineText = this._buffer.getLineContent(lineNumber);
var tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
if (tokenIndex < 0) {
return null;
}
var currentModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex));
// check that the token is not to be ignored
if (currentModeBrackets && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) {
// limit search to not go before `maxBracketLength`
var searchStartOffset = Math.max(0, position.column - 1 - currentModeBrackets.maxBracketLength);
for (var i = tokenIndex - 1; i >= 0; i--) {
var tokenEndOffset = lineTokens.getEndOffset(i);
if (tokenEndOffset <= searchStartOffset) {
break;
}
if (supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(i))) {
searchStartOffset = tokenEndOffset;
}
}
// limit search to not go after `maxBracketLength`
var searchEndOffset = Math.min(lineText.length, position.column - 1 + currentModeBrackets.maxBracketLength);
// it might be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets
// `bestResult` will contain the most right-side result
var bestResult = null;
while (true) {
var foundBracket = richEditBrackets_1.BracketsUtils.findNextBracketInRange(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (!foundBracket) {
// there are no more brackets in this text
break;
}
// check that we didn't hit a bracket too far away from position
if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
var foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
var r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText]);
if (r) {
bestResult = r;
}
}
searchStartOffset = foundBracket.endColumn - 1;
}
if (bestResult) {
return bestResult;
}
}
// If position is in between two tokens, try also looking in the previous token
if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position.column - 1) {
var prevTokenIndex = tokenIndex - 1;
var prevModeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(prevTokenIndex));
// check that previous token is not to be ignored
if (prevModeBrackets && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(prevTokenIndex))) {
// limit search in case previous token is very large, there's no need to go beyond `maxBracketLength`
var searchStartOffset = Math.max(0, position.column - 1 - prevModeBrackets.maxBracketLength);
var searchEndOffset = Math.min(lineText.length, position.column - 1 + prevModeBrackets.maxBracketLength);
for (var i = prevTokenIndex + 1; i < tokenCount; i++) {
var tokenStartOffset = lineTokens.getStartOffset(i);
if (tokenStartOffset >= searchEndOffset) {
break;
}
if (supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(i))) {
searchEndOffset = tokenStartOffset;
}
}
var foundBracket = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
// check that we didn't hit a bracket too far away from position
if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
var foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
var r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText]);
if (r) {
return r;
}
}
}
}
return null;
};
TextModel.prototype._matchFoundBracket = function (foundBracket, data, isOpen) {
if (!data) {
return null;
}
if (isOpen) {
var matched = this._findMatchingBracketDown(data, foundBracket.getEndPosition());
if (matched) {
return [foundBracket, matched];
}
}
else {
var matched = this._findMatchingBracketUp(data, foundBracket.getStartPosition());
if (matched) {
return [foundBracket, matched];
}
}
return null;
};
TextModel.prototype._findMatchingBracketUp = function (bracket, position) {
// console.log('_findMatchingBracketUp: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));
var languageId = bracket.languageIdentifier.id;
var reversedBracketRegex = bracket.reversedRegex;
var count = -1;
var searchPrevMatchingBracketInRange = function (lineNumber, lineText, searchStartOffset, searchEndOffset) {
while (true) {
var r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (!r) {
break;
}
var hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
if (bracket.isOpen(hitText)) {
count++;
}
else if (bracket.isClose(hitText)) {
count--;
}
if (count === 0) {
return r;
}
searchEndOffset = r.startColumn - 1;
}
return null;
};
for (var lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
var lineTokens = this._getLineTokens(lineNumber);
var tokenCount = lineTokens.getCount();
var lineText = this._buffer.getLineContent(lineNumber);
var tokenIndex = tokenCount - 1;
var searchStartOffset = lineText.length;
var searchEndOffset = lineText.length;
if (lineNumber === position.lineNumber) {
tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
searchStartOffset = position.column - 1;
searchEndOffset = position.column - 1;
}
var prevSearchInToken = true;
for (; tokenIndex >= 0; tokenIndex--) {
var searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
if (searchInToken) {
// this token should be searched
if (prevSearchInToken) {
// the previous token should be searched, simply extend searchStartOffset
searchStartOffset = lineTokens.getStartOffset(tokenIndex);
}
else {
// the previous token should not be searched
searchStartOffset = lineTokens.getStartOffset(tokenIndex);
searchEndOffset = lineTokens.getEndOffset(tokenIndex);
}
}
else {
// this token should not be searched
if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return r;
}
}
}
prevSearchInToken = searchInToken;
}
if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return r;
}
}
}
return null;
};
TextModel.prototype._findMatchingBracketDown = function (bracket, position) {
// console.log('_findMatchingBracketDown: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));
var languageId = bracket.languageIdentifier.id;
var bracketRegex = bracket.forwardRegex;
var count = 1;
var searchNextMatchingBracketInRange = function (lineNumber, lineText, searchStartOffset, searchEndOffset) {
while (true) {
var r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (!r) {
break;
}
var hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
if (bracket.isOpen(hitText)) {
count++;
}
else if (bracket.isClose(hitText)) {
count--;
}
if (count === 0) {
return r;
}
searchStartOffset = r.endColumn - 1;
}
return null;
};
var lineCount = this.getLineCount();
for (var lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
var lineTokens = this._getLineTokens(lineNumber);
var tokenCount = lineTokens.getCount();
var lineText = this._buffer.getLineContent(lineNumber);
var tokenIndex = 0;
var searchStartOffset = 0;
var searchEndOffset = 0;
if (lineNumber === position.lineNumber) {
tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
searchStartOffset = position.column - 1;
searchEndOffset = position.column - 1;
}
var prevSearchInToken = true;
for (; tokenIndex < tokenCount; tokenIndex++) {
var searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
if (searchInToken) {
// this token should be searched
if (prevSearchInToken) {
// the previous token should be searched, simply extend searchEndOffset
searchEndOffset = lineTokens.getEndOffset(tokenIndex);
}
else {
// the previous token should not be searched
searchStartOffset = lineTokens.getStartOffset(tokenIndex);
searchEndOffset = lineTokens.getEndOffset(tokenIndex);
}
}
else {
// this token should not be searched
if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return r;
}
}
}
prevSearchInToken = searchInToken;
}
if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return r;
}
}
}
return null;
};
TextModel.prototype.findPrevBracket = function (_position) {
var position = this.validatePosition(_position);
var languageId = -1;
var modeBrackets = null;
for (var lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
var lineTokens = this._getLineTokens(lineNumber);
var tokenCount = lineTokens.getCount();
var lineText = this._buffer.getLineContent(lineNumber);
var tokenIndex = tokenCount - 1;
var searchStartOffset = lineText.length;
var searchEndOffset = lineText.length;
if (lineNumber === position.lineNumber) {
tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
searchStartOffset = position.column - 1;
searchEndOffset = position.column - 1;
var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
if (languageId !== tokenLanguageId) {
languageId = tokenLanguageId;
modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
}
}
var prevSearchInToken = true;
for (; tokenIndex >= 0; tokenIndex--) {
var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
if (languageId !== tokenLanguageId) {
// language id change!
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
prevSearchInToken = false;
}
languageId = tokenLanguageId;
modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
}
var searchInToken = (!!modeBrackets && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
if (searchInToken) {
// this token should be searched
if (prevSearchInToken) {
// the previous token should be searched, simply extend searchStartOffset
searchStartOffset = lineTokens.getStartOffset(tokenIndex);
}
else {
// the previous token should not be searched
searchStartOffset = lineTokens.getStartOffset(tokenIndex);
searchEndOffset = lineTokens.getEndOffset(tokenIndex);
}
}
else {
// this token should not be searched
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
}
}
prevSearchInToken = searchInToken;
}
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
}
}
return null;
};
TextModel.prototype.findNextBracket = function (_position) {
var position = this.validatePosition(_position);
var lineCount = this.getLineCount();
var languageId = -1;
var modeBrackets = null;
for (var lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
var lineTokens = this._getLineTokens(lineNumber);
var tokenCount = lineTokens.getCount();
var lineText = this._buffer.getLineContent(lineNumber);
var tokenIndex = 0;
var searchStartOffset = 0;
var searchEndOffset = 0;
if (lineNumber === position.lineNumber) {
tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
searchStartOffset = position.column - 1;
searchEndOffset = position.column - 1;
var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
if (languageId !== tokenLanguageId) {
languageId = tokenLanguageId;
modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
}
}
var prevSearchInToken = true;
for (; tokenIndex < tokenCount; tokenIndex++) {
var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
if (languageId !== tokenLanguageId) {
// language id change!
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
prevSearchInToken = false;
}
languageId = tokenLanguageId;
modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
}
var searchInToken = (!!modeBrackets && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
if (searchInToken) {
// this token should be searched
if (prevSearchInToken) {
// the previous token should be searched, simply extend searchEndOffset
searchEndOffset = lineTokens.getEndOffset(tokenIndex);
}
else {
// the previous token should not be searched
searchStartOffset = lineTokens.getStartOffset(tokenIndex);
searchEndOffset = lineTokens.getEndOffset(tokenIndex);
}
}
else {
// this token should not be searched
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
}
}
prevSearchInToken = searchInToken;
}
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return this._toFoundBracket(modeBrackets, r);
}
}
}
return null;
};
TextModel.prototype.findEnclosingBrackets = function (_position, maxDuration) {
var _this = this;
if (maxDuration === void 0) { maxDuration = 1073741824 /* MAX_SAFE_SMALL_INTEGER */; }
var position = this.validatePosition(_position);
var lineCount = this.getLineCount();
var savedCounts = new Map();
var counts = [];
var resetCounts = function (languageId, modeBrackets) {
if (!savedCounts.has(languageId)) {
var tmp = [];
for (var i = 0, len = modeBrackets ? modeBrackets.brackets.length : 0; i < len; i++) {
tmp[i] = 0;
}
savedCounts.set(languageId, tmp);
}
counts = savedCounts.get(languageId);
};
var searchInRange = function (modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset) {
while (true) {
var r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (!r) {
break;
}
var hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
var bracket = modeBrackets.textIsBracket[hitText];
if (bracket) {
if (bracket.isOpen(hitText)) {
counts[bracket.index]++;
}
else if (bracket.isClose(hitText)) {
counts[bracket.index]--;
}
if (counts[bracket.index] === -1) {
return _this._matchFoundBracket(r, bracket, false);
}
}
searchStartOffset = r.endColumn - 1;
}
return null;
};
var languageId = -1;
var modeBrackets = null;
var startTime = Date.now();
for (var lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
var elapsedTime = Date.now() - startTime;
if (elapsedTime > maxDuration) {
return null;
}
var lineTokens = this._getLineTokens(lineNumber);
var tokenCount = lineTokens.getCount();
var lineText = this._buffer.getLineContent(lineNumber);
var tokenIndex = 0;
var searchStartOffset = 0;
var searchEndOffset = 0;
if (lineNumber === position.lineNumber) {
tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
searchStartOffset = position.column - 1;
searchEndOffset = position.column - 1;
var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
if (languageId !== tokenLanguageId) {
languageId = tokenLanguageId;
modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
resetCounts(languageId, modeBrackets);
}
}
var prevSearchInToken = true;
for (; tokenIndex < tokenCount; tokenIndex++) {
var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
if (languageId !== tokenLanguageId) {
// language id change!
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return r;
}
prevSearchInToken = false;
}
languageId = tokenLanguageId;
modeBrackets = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getBracketsSupport(languageId);
resetCounts(languageId, modeBrackets);
}
var searchInToken = (!!modeBrackets && !supports_1.ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
if (searchInToken) {
// this token should be searched
if (prevSearchInToken) {
// the previous token should be searched, simply extend searchEndOffset
searchEndOffset = lineTokens.getEndOffset(tokenIndex);
}
else {
// the previous token should not be searched
searchStartOffset = lineTokens.getStartOffset(tokenIndex);
searchEndOffset = lineTokens.getEndOffset(tokenIndex);
}
}
else {
// this token should not be searched
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return r;
}
}
}
prevSearchInToken = searchInToken;
}
if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
var r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
if (r) {
return r;
}
}
}
return null;
};
TextModel.prototype._toFoundBracket = function (modeBrackets, r) {
if (!r) {
return null;
}
var text = this.getValueInRange(r);
text = text.toLowerCase();
var data = modeBrackets.textIsBracket[text];
if (!data) {
return null;
}
return {
range: r,
open: data.open,
close: data.close,
isOpen: modeBrackets.textIsOpenBracket[text]
};
};
/**
* Returns:
* - -1 => the line consists of whitespace
* - otherwise => the indent level is returned value
*/
TextModel.computeIndentLevel = function (line, tabSize) {
var indent = 0;
var i = 0;
var len = line.length;
while (i < len) {
var chCode = line.charCodeAt(i);
if (chCode === 32 /* Space */) {
indent++;
}
else if (chCode === 9 /* Tab */) {
indent = indent - indent % tabSize + tabSize;
}
else {
break;
}
i++;
}
if (i === len) {
return -1; // line only consists of whitespace
}
return indent;
};
TextModel.prototype._computeIndentLevel = function (lineIndex) {
return TextModel.computeIndentLevel(this._buffer.getLineContent(lineIndex + 1), this._options.tabSize);
};
TextModel.prototype.getActiveIndentGuide = function (lineNumber, minLineNumber, maxLineNumber) {
var _this = this;
this._assertNotDisposed();
var lineCount = this.getLineCount();
if (lineNumber < 1 || lineNumber > lineCount) {
throw new Error('Illegal value for lineNumber');
}
var foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);
var offSide = Boolean(foldingRules && foldingRules.offSide);
var up_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
var up_aboveContentLineIndent = -1;
var up_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
var up_belowContentLineIndent = -1;
var up_resolveIndents = function (lineNumber) {
if (up_aboveContentLineIndex !== -1 && (up_aboveContentLineIndex === -2 || up_aboveContentLineIndex > lineNumber - 1)) {
up_aboveContentLineIndex = -1;
up_aboveContentLineIndent = -1;
// must find previous line with content
for (var lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
var indent_1 = _this._computeIndentLevel(lineIndex);
if (indent_1 >= 0) {
up_aboveContentLineIndex = lineIndex;
up_aboveContentLineIndent = indent_1;
break;
}
}
}
if (up_belowContentLineIndex === -2) {
up_belowContentLineIndex = -1;
up_belowContentLineIndent = -1;
// must find next line with content
for (var lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
var indent_2 = _this._computeIndentLevel(lineIndex);
if (indent_2 >= 0) {
up_belowContentLineIndex = lineIndex;
up_belowContentLineIndent = indent_2;
break;
}
}
}
};
var down_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
var down_aboveContentLineIndent = -1;
var down_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
var down_belowContentLineIndent = -1;
var down_resolveIndents = function (lineNumber) {
if (down_aboveContentLineIndex === -2) {
down_aboveContentLineIndex = -1;
down_aboveContentLineIndent = -1;
// must find previous line with content
for (var lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
var indent_3 = _this._computeIndentLevel(lineIndex);
if (indent_3 >= 0) {
down_aboveContentLineIndex = lineIndex;
down_aboveContentLineIndent = indent_3;
break;
}
}
}
if (down_belowContentLineIndex !== -1 && (down_belowContentLineIndex === -2 || down_belowContentLineIndex < lineNumber - 1)) {
down_belowContentLineIndex = -1;
down_belowContentLineIndent = -1;
// must find next line with content
for (var lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
var indent_4 = _this._computeIndentLevel(lineIndex);
if (indent_4 >= 0) {
down_belowContentLineIndex = lineIndex;
down_belowContentLineIndent = indent_4;
break;
}
}
}
};
var startLineNumber = 0;
var goUp = true;
var endLineNumber = 0;
var goDown = true;
var indent = 0;
for (var distance = 0; goUp || goDown; distance++) {
var upLineNumber = lineNumber - distance;
var downLineNumber = lineNumber + distance;
if (distance !== 0 && (upLineNumber < 1 || upLineNumber < minLineNumber)) {
goUp = false;
}
if (distance !== 0 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) {
goDown = false;
}
if (distance > 50000) {
// stop processing
goUp = false;
goDown = false;
}
if (goUp) {
// compute indent level going up
var upLineIndentLevel = void 0;
var currentIndent = this._computeIndentLevel(upLineNumber - 1);
if (currentIndent >= 0) {
// This line has content (besides whitespace)
// Use the line's indent
up_belowContentLineIndex = upLineNumber - 1;
up_belowContentLineIndent = currentIndent;
upLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize);
}
else {
up_resolveIndents(upLineNumber);
upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
}
if (distance === 0) {
// This is the initial line number
startLineNumber = upLineNumber;
endLineNumber = downLineNumber;
indent = upLineIndentLevel;
if (indent === 0) {
// No need to continue
return { startLineNumber: startLineNumber, endLineNumber: endLineNumber, indent: indent };
}
continue;
}
if (upLineIndentLevel >= indent) {
startLineNumber = upLineNumber;
}
else {
goUp = false;
}
}
if (goDown) {
// compute indent level going down
var downLineIndentLevel = void 0;
var currentIndent = this._computeIndentLevel(downLineNumber - 1);
if (currentIndent >= 0) {
// This line has content (besides whitespace)
// Use the line's indent
down_aboveContentLineIndex = downLineNumber - 1;
down_aboveContentLineIndent = currentIndent;
downLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize);
}
else {
down_resolveIndents(downLineNumber);
downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);
}
if (downLineIndentLevel >= indent) {
endLineNumber = downLineNumber;
}
else {
goDown = false;
}
}
}
return { startLineNumber: startLineNumber, endLineNumber: endLineNumber, indent: indent };
};
TextModel.prototype.getLinesIndentGuides = function (startLineNumber, endLineNumber) {
this._assertNotDisposed();
var lineCount = this.getLineCount();
if (startLineNumber < 1 || startLineNumber > lineCount) {
throw new Error('Illegal value for startLineNumber');
}
if (endLineNumber < 1 || endLineNumber > lineCount) {
throw new Error('Illegal value for endLineNumber');
}
var foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);
var offSide = Boolean(foldingRules && foldingRules.offSide);
var result = new Array(endLineNumber - startLineNumber + 1);
var aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
var aboveContentLineIndent = -1;
var belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
var belowContentLineIndent = -1;
for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
var resultIndex = lineNumber - startLineNumber;
var currentIndent = this._computeIndentLevel(lineNumber - 1);
if (currentIndent >= 0) {
// This line has content (besides whitespace)
// Use the line's indent
aboveContentLineIndex = lineNumber - 1;
aboveContentLineIndent = currentIndent;
result[resultIndex] = Math.ceil(currentIndent / this._options.indentSize);
continue;
}
if (aboveContentLineIndex === -2) {
aboveContentLineIndex = -1;
aboveContentLineIndent = -1;
// must find previous line with content
for (var lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
var indent = this._computeIndentLevel(lineIndex);
if (indent >= 0) {
aboveContentLineIndex = lineIndex;
aboveContentLineIndent = indent;
break;
}
}
}
if (belowContentLineIndex !== -1 && (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) {
belowContentLineIndex = -1;
belowContentLineIndent = -1;
// must find next line with content
for (var lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
var indent = this._computeIndentLevel(lineIndex);
if (indent >= 0) {
belowContentLineIndex = lineIndex;
belowContentLineIndent = indent;
break;
}
}
}
result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent);
}
return result;
};
TextModel.prototype._getIndentLevelForWhitespaceLine = function (offSide, aboveContentLineIndent, belowContentLineIndent) {
if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) {
// At the top or bottom of the file
return 0;
}
else if (aboveContentLineIndent < belowContentLineIndent) {
// we are inside the region above
return (1 + Math.floor(aboveContentLineIndent / this._options.indentSize));
}
else if (aboveContentLineIndent === belowContentLineIndent) {
// we are in between two regions
return Math.ceil(belowContentLineIndent / this._options.indentSize);
}
else {
if (offSide) {
// same level as region below
return Math.ceil(belowContentLineIndent / this._options.indentSize);
}
else {
// we are inside the region that ends below
return (1 + Math.floor(belowContentLineIndent / this._options.indentSize));
}
}
};
TextModel.MODEL_SYNC_LIMIT = 50 * 1024 * 1024; // 50 MB
TextModel.LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024; // 20 MB;
TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1000; // 300K lines
TextModel.DEFAULT_CREATION_OPTIONS = {
isForSimpleWidget: false,
tabSize: editorOptions_1.EDITOR_MODEL_DEFAULTS.tabSize,
indentSize: editorOptions_1.EDITOR_MODEL_DEFAULTS.indentSize,
insertSpaces: editorOptions_1.EDITOR_MODEL_DEFAULTS.insertSpaces,
detectIndentation: false,
defaultEOL: 1 /* LF */,
trimAutoWhitespace: editorOptions_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
largeFileOptimizations: editorOptions_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
};
return TextModel;
}(lifecycle_1.Disposable));
exports.TextModel = TextModel;
//#region Decorations
var DecorationsTrees = /** @class */ (function () {
function DecorationsTrees() {
this._decorationsTree0 = new intervalTree_1.IntervalTree();
this._decorationsTree1 = new intervalTree_1.IntervalTree();
}
DecorationsTrees.prototype.intervalSearch = function (start, end, filterOwnerId, filterOutValidation, cachedVersionId) {
var r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
var r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
return r0.concat(r1);
};
DecorationsTrees.prototype.search = function (filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId) {
if (overviewRulerOnly) {
return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
}
else {
var r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId);
var r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
return r0.concat(r1);
}
};
DecorationsTrees.prototype.collectNodesFromOwner = function (ownerId) {
var r0 = this._decorationsTree0.collectNodesFromOwner(ownerId);
var r1 = this._decorationsTree1.collectNodesFromOwner(ownerId);
return r0.concat(r1);
};
DecorationsTrees.prototype.collectNodesPostOrder = function () {
var r0 = this._decorationsTree0.collectNodesPostOrder();
var r1 = this._decorationsTree1.collectNodesPostOrder();
return r0.concat(r1);
};
DecorationsTrees.prototype.insert = function (node) {
if (intervalTree_1.getNodeIsInOverviewRuler(node)) {
this._decorationsTree1.insert(node);
}
else {
this._decorationsTree0.insert(node);
}
};
DecorationsTrees.prototype.delete = function (node) {
if (intervalTree_1.getNodeIsInOverviewRuler(node)) {
this._decorationsTree1.delete(node);
}
else {
this._decorationsTree0.delete(node);
}
};
DecorationsTrees.prototype.resolveNode = function (node, cachedVersionId) {
if (intervalTree_1.getNodeIsInOverviewRuler(node)) {
this._decorationsTree1.resolveNode(node, cachedVersionId);
}
else {
this._decorationsTree0.resolveNode(node, cachedVersionId);
}
};
DecorationsTrees.prototype.acceptReplace = function (offset, length, textLength, forceMoveMarkers) {
this._decorationsTree0.acceptReplace(offset, length, textLength, forceMoveMarkers);
this._decorationsTree1.acceptReplace(offset, length, textLength, forceMoveMarkers);
};
return DecorationsTrees;
}());
function cleanClassName(className) {
return className.replace(/[^a-z0-9\-_]/gi, ' ');
}
var DecorationOptions = /** @class */ (function () {
function DecorationOptions(options) {
this.color = options.color || '';
this.darkColor = options.darkColor || '';
}
return DecorationOptions;
}());
var ModelDecorationOverviewRulerOptions = /** @class */ (function (_super) {
__extends(ModelDecorationOverviewRulerOptions, _super);
function ModelDecorationOverviewRulerOptions(options) {
var _this = _super.call(this, options) || this;
_this._resolvedColor = null;
_this.position = (typeof options.position === 'number' ? options.position : model.OverviewRulerLane.Center);
return _this;
}
ModelDecorationOverviewRulerOptions.prototype.getColor = function (theme) {
if (!this._resolvedColor) {
if (theme.type !== 'light' && this.darkColor) {
this._resolvedColor = this._resolveColor(this.darkColor, theme);
}
else {
this._resolvedColor = this._resolveColor(this.color, theme);
}
}
return this._resolvedColor;
};
ModelDecorationOverviewRulerOptions.prototype.invalidateCachedColor = function () {
this._resolvedColor = null;
};
ModelDecorationOverviewRulerOptions.prototype._resolveColor = function (color, theme) {
if (typeof color === 'string') {
return color;
}
var c = color ? theme.getColor(color.id) : null;
if (!c) {
return '';
}
return c.toString();
};
return ModelDecorationOverviewRulerOptions;
}(DecorationOptions));
exports.ModelDecorationOverviewRulerOptions = ModelDecorationOverviewRulerOptions;
var ModelDecorationMinimapOptions = /** @class */ (function (_super) {
__extends(ModelDecorationMinimapOptions, _super);
function ModelDecorationMinimapOptions(options) {
var _this = _super.call(this, options) || this;
_this.position = options.position;
return _this;
}
ModelDecorationMinimapOptions.prototype.getColor = function (theme) {
if (!this._resolvedColor) {
if (theme.type !== 'light' && this.darkColor) {
this._resolvedColor = this._resolveColor(this.darkColor, theme);
}
else {
this._resolvedColor = this._resolveColor(this.color, theme);
}
}
return this._resolvedColor;
};
ModelDecorationMinimapOptions.prototype.invalidateCachedColor = function () {
this._resolvedColor = undefined;
};
ModelDecorationMinimapOptions.prototype._resolveColor = function (color, theme) {
if (typeof color === 'string') {
return color_1.Color.fromHex(color);
}
return theme.getColor(color.id);
};
return ModelDecorationMinimapOptions;
}(DecorationOptions));
exports.ModelDecorationMinimapOptions = ModelDecorationMinimapOptions;
var ModelDecorationOptions = /** @class */ (function () {
function ModelDecorationOptions(options) {
this.stickiness = options.stickiness || 0 /* AlwaysGrowsWhenTypingAtEdges */;
this.zIndex = options.zIndex || 0;
this.className = options.className ? cleanClassName(options.className) : null;
this.hoverMessage = types_1.withUndefinedAsNull(options.hoverMessage);
this.glyphMarginHoverMessage = types_1.withUndefinedAsNull(options.glyphMarginHoverMessage);
this.isWholeLine = options.isWholeLine || false;
this.showIfCollapsed = options.showIfCollapsed || false;
this.collapseOnReplaceEdit = options.collapseOnReplaceEdit || false;
this.overviewRuler = options.overviewRuler ? new ModelDecorationOverviewRulerOptions(options.overviewRuler) : null;
this.minimap = options.minimap ? new ModelDecorationMinimapOptions(options.minimap) : null;
this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null;
this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : null;
this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : null;
this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : null;
this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : null;
this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : null;
}
ModelDecorationOptions.register = function (options) {
return new ModelDecorationOptions(options);
};
ModelDecorationOptions.createDynamic = function (options) {
return new ModelDecorationOptions(options);
};
return ModelDecorationOptions;
}());
exports.ModelDecorationOptions = ModelDecorationOptions;
ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({});
/**
* The order carefully matches the values of the enum.
*/
var TRACKED_RANGE_OPTIONS = [
ModelDecorationOptions.register({ stickiness: 0 /* AlwaysGrowsWhenTypingAtEdges */ }),
ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ }),
ModelDecorationOptions.register({ stickiness: 2 /* GrowsOnlyWhenTypingBefore */ }),
ModelDecorationOptions.register({ stickiness: 3 /* GrowsOnlyWhenTypingAfter */ }),
];
function _normalizeOptions(options) {
if (options instanceof ModelDecorationOptions) {
return options;
}
return ModelDecorationOptions.createDynamic(options);
}
var DidChangeDecorationsEmitter = /** @class */ (function (_super) {
__extends(DidChangeDecorationsEmitter, _super);
function DidChangeDecorationsEmitter() {
var _this = _super.call(this) || this;
_this._actual = _this._register(new event_1.Emitter());
_this.event = _this._actual.event;
_this._deferredCnt = 0;
_this._shouldFire = false;
return _this;
}
DidChangeDecorationsEmitter.prototype.beginDeferredEmit = function () {
this._deferredCnt++;
};
DidChangeDecorationsEmitter.prototype.endDeferredEmit = function () {
this._deferredCnt--;
if (this._deferredCnt === 0) {
if (this._shouldFire) {
this._shouldFire = false;
this._actual.fire({});
}
}
};
DidChangeDecorationsEmitter.prototype.fire = function () {
this._shouldFire = true;
};
return DidChangeDecorationsEmitter;
}(lifecycle_1.Disposable));
exports.DidChangeDecorationsEmitter = DidChangeDecorationsEmitter;
//#endregion
var DidChangeContentEmitter = /** @class */ (function (_super) {
__extends(DidChangeContentEmitter, _super);
function DidChangeContentEmitter() {
var _this = _super.call(this) || this;
/**
* Both `fastEvent` and `slowEvent` work the same way and contain the same events, but first we invoke `fastEvent` and then `slowEvent`.
*/
_this._fastEmitter = _this._register(new event_1.Emitter());
_this.fastEvent = _this._fastEmitter.event;
_this._slowEmitter = _this._register(new event_1.Emitter());
_this.slowEvent = _this._slowEmitter.event;
_this._deferredCnt = 0;
_this._deferredEvent = null;
return _this;
}
DidChangeContentEmitter.prototype.beginDeferredEmit = function () {
this._deferredCnt++;
};
DidChangeContentEmitter.prototype.endDeferredEmit = function () {
this._deferredCnt--;
if (this._deferredCnt === 0) {
if (this._deferredEvent !== null) {
var e = this._deferredEvent;
this._deferredEvent = null;
this._fastEmitter.fire(e);
this._slowEmitter.fire(e);
}
}
};
DidChangeContentEmitter.prototype.fire = function (e) {
if (this._deferredCnt > 0) {
if (this._deferredEvent) {
this._deferredEvent = this._deferredEvent.merge(e);
}
else {
this._deferredEvent = e;
}
return;
}
this._fastEmitter.fire(e);
this._slowEmitter.fire(e);
};
return DidChangeContentEmitter;
}(lifecycle_1.Disposable));
exports.DidChangeContentEmitter = DidChangeContentEmitter;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[40/*vs/editor/common/controller/cursorCommon*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,5/*vs/base/common/strings*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,30/*vs/editor/common/model/textModel*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, errors_1, strings, position_1, range_1, selection_1, textModel_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var autoCloseAlways = function () { return true; };
var autoCloseNever = function () { return false; };
var autoCloseBeforeWhitespace = function (chr) { return (chr === ' ' || chr === '\t'); };
function appendEntry(target, key, value) {
if (target.has(key)) {
target.get(key).push(value);
}
else {
target.set(key, [value]);
}
}
var CursorConfiguration = /** @class */ (function () {
function CursorConfiguration(languageIdentifier, modelOptions, configuration) {
this._languageIdentifier = languageIdentifier;
var options = configuration.options;
var layoutInfo = options.get(107 /* layoutInfo */);
this.readOnly = options.get(68 /* readOnly */);
this.tabSize = modelOptions.tabSize;
this.indentSize = modelOptions.indentSize;
this.insertSpaces = modelOptions.insertSpaces;
this.lineHeight = options.get(49 /* lineHeight */);
this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2);
this.useTabStops = options.get(95 /* useTabStops */);
this.wordSeparators = options.get(96 /* wordSeparators */);
this.emptySelectionClipboard = options.get(25 /* emptySelectionClipboard */);
this.copyWithSyntaxHighlighting = options.get(15 /* copyWithSyntaxHighlighting */);
this.multiCursorMergeOverlapping = options.get(58 /* multiCursorMergeOverlapping */);
this.multiCursorPaste = options.get(60 /* multiCursorPaste */);
this.autoClosingBrackets = options.get(5 /* autoClosingBrackets */);
this.autoClosingQuotes = options.get(7 /* autoClosingQuotes */);
this.autoClosingOvertype = options.get(6 /* autoClosingOvertype */);
this.autoSurround = options.get(10 /* autoSurround */);
this.autoIndent = options.get(8 /* autoIndent */);
this.autoClosingPairsOpen2 = new Map();
this.autoClosingPairsClose2 = new Map();
this.surroundingPairs = {};
this._electricChars = null;
this.shouldAutoCloseBefore = {
quote: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingQuotes),
bracket: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingBrackets)
};
var autoClosingPairs = CursorConfiguration._getAutoClosingPairs(languageIdentifier);
if (autoClosingPairs) {
for (var _i = 0, autoClosingPairs_1 = autoClosingPairs; _i < autoClosingPairs_1.length; _i++) {
var pair = autoClosingPairs_1[_i];
appendEntry(this.autoClosingPairsOpen2, pair.open.charAt(pair.open.length - 1), pair);
if (pair.close.length === 1) {
appendEntry(this.autoClosingPairsClose2, pair.close, pair);
}
}
}
var surroundingPairs = CursorConfiguration._getSurroundingPairs(languageIdentifier);
if (surroundingPairs) {
for (var _a = 0, surroundingPairs_1 = surroundingPairs; _a < surroundingPairs_1.length; _a++) {
var pair = surroundingPairs_1[_a];
this.surroundingPairs[pair.open] = pair.close;
}
}
}
CursorConfiguration.shouldRecreate = function (e) {
return (e.hasChanged(107 /* layoutInfo */)
|| e.hasChanged(96 /* wordSeparators */)
|| e.hasChanged(25 /* emptySelectionClipboard */)
|| e.hasChanged(58 /* multiCursorMergeOverlapping */)
|| e.hasChanged(60 /* multiCursorPaste */)
|| e.hasChanged(5 /* autoClosingBrackets */)
|| e.hasChanged(7 /* autoClosingQuotes */)
|| e.hasChanged(6 /* autoClosingOvertype */)
|| e.hasChanged(10 /* autoSurround */)
|| e.hasChanged(95 /* useTabStops */)
|| e.hasChanged(49 /* lineHeight */)
|| e.hasChanged(68 /* readOnly */));
};
Object.defineProperty(CursorConfiguration.prototype, "electricChars", {
get: function () {
if (!this._electricChars) {
this._electricChars = {};
var electricChars = CursorConfiguration._getElectricCharacters(this._languageIdentifier);
if (electricChars) {
for (var _i = 0, electricChars_1 = electricChars; _i < electricChars_1.length; _i++) {
var char = electricChars_1[_i];
this._electricChars[char] = true;
}
}
}
return this._electricChars;
},
enumerable: true,
configurable: true
});
CursorConfiguration.prototype.normalizeIndentation = function (str) {
return textModel_1.TextModel.normalizeIndentation(str, this.indentSize, this.insertSpaces);
};
CursorConfiguration._getElectricCharacters = function (languageIdentifier) {
try {
return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getElectricCharacters(languageIdentifier.id);
}
catch (e) {
errors_1.onUnexpectedError(e);
return null;
}
};
CursorConfiguration._getAutoClosingPairs = function (languageIdentifier) {
try {
return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getAutoClosingPairs(languageIdentifier.id);
}
catch (e) {
errors_1.onUnexpectedError(e);
return null;
}
};
CursorConfiguration._getShouldAutoClose = function (languageIdentifier, autoCloseConfig) {
switch (autoCloseConfig) {
case 'beforeWhitespace':
return autoCloseBeforeWhitespace;
case 'languageDefined':
return CursorConfiguration._getLanguageDefinedShouldAutoClose(languageIdentifier);
case 'always':
return autoCloseAlways;
case 'never':
return autoCloseNever;
}
};
CursorConfiguration._getLanguageDefinedShouldAutoClose = function (languageIdentifier) {
try {
var autoCloseBeforeSet_1 = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getAutoCloseBeforeSet(languageIdentifier.id);
return function (c) { return autoCloseBeforeSet_1.indexOf(c) !== -1; };
}
catch (e) {
errors_1.onUnexpectedError(e);
return autoCloseNever;
}
};
CursorConfiguration._getSurroundingPairs = function (languageIdentifier) {
try {
return languageConfigurationRegistry_1.LanguageConfigurationRegistry.getSurroundingPairs(languageIdentifier.id);
}
catch (e) {
errors_1.onUnexpectedError(e);
return null;
}
};
return CursorConfiguration;
}());
exports.CursorConfiguration = CursorConfiguration;
/**
* Represents the cursor state on either the model or on the view model.
*/
var SingleCursorState = /** @class */ (function () {
function SingleCursorState(selectionStart, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) {
this.selectionStart = selectionStart;
this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns;
this.position = position;
this.leftoverVisibleColumns = leftoverVisibleColumns;
this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position);
}
SingleCursorState.prototype.equals = function (other) {
return (this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns
&& this.leftoverVisibleColumns === other.leftoverVisibleColumns
&& this.position.equals(other.position)
&& this.selectionStart.equalsRange(other.selectionStart));
};
SingleCursorState.prototype.hasSelection = function () {
return (!this.selection.isEmpty() || !this.selectionStart.isEmpty());
};
SingleCursorState.prototype.move = function (inSelectionMode, lineNumber, column, leftoverVisibleColumns) {
if (inSelectionMode) {
// move just position
return new SingleCursorState(this.selectionStart, this.selectionStartLeftoverVisibleColumns, new position_1.Position(lineNumber, column), leftoverVisibleColumns);
}
else {
// move everything
return new SingleCursorState(new range_1.Range(lineNumber, column, lineNumber, column), leftoverVisibleColumns, new position_1.Position(lineNumber, column), leftoverVisibleColumns);
}
};
SingleCursorState._computeSelection = function (selectionStart, position) {
var startLineNumber, startColumn, endLineNumber, endColumn;
if (selectionStart.isEmpty()) {
startLineNumber = selectionStart.startLineNumber;
startColumn = selectionStart.startColumn;
endLineNumber = position.lineNumber;
endColumn = position.column;
}
else {
if (position.isBeforeOrEqual(selectionStart.getStartPosition())) {
startLineNumber = selectionStart.endLineNumber;
startColumn = selectionStart.endColumn;
endLineNumber = position.lineNumber;
endColumn = position.column;
}
else {
startLineNumber = selectionStart.startLineNumber;
startColumn = selectionStart.startColumn;
endLineNumber = position.lineNumber;
endColumn = position.column;
}
}
return new selection_1.Selection(startLineNumber, startColumn, endLineNumber, endColumn);
};
return SingleCursorState;
}());
exports.SingleCursorState = SingleCursorState;
var CursorContext = /** @class */ (function () {
function CursorContext(configuration, model, viewModel) {
this.model = model;
this.viewModel = viewModel;
this.config = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), configuration);
}
CursorContext.prototype.validateViewPosition = function (viewPosition, modelPosition) {
return this.viewModel.coordinatesConverter.validateViewPosition(viewPosition, modelPosition);
};
CursorContext.prototype.validateViewRange = function (viewRange, expectedModelRange) {
return this.viewModel.coordinatesConverter.validateViewRange(viewRange, expectedModelRange);
};
CursorContext.prototype.convertViewRangeToModelRange = function (viewRange) {
return this.viewModel.coordinatesConverter.convertViewRangeToModelRange(viewRange);
};
CursorContext.prototype.convertViewPositionToModelPosition = function (lineNumber, column) {
return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(lineNumber, column));
};
CursorContext.prototype.convertModelPositionToViewPosition = function (modelPosition) {
return this.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
};
CursorContext.prototype.convertModelRangeToViewRange = function (modelRange) {
return this.viewModel.coordinatesConverter.convertModelRangeToViewRange(modelRange);
};
CursorContext.prototype.getCurrentScrollTop = function () {
return this.viewModel.viewLayout.getCurrentScrollTop();
};
CursorContext.prototype.getCompletelyVisibleViewRange = function () {
return this.viewModel.getCompletelyVisibleViewRange();
};
CursorContext.prototype.getCompletelyVisibleModelRange = function () {
var viewRange = this.viewModel.getCompletelyVisibleViewRange();
return this.viewModel.coordinatesConverter.convertViewRangeToModelRange(viewRange);
};
CursorContext.prototype.getCompletelyVisibleViewRangeAtScrollTop = function (scrollTop) {
return this.viewModel.getCompletelyVisibleViewRangeAtScrollTop(scrollTop);
};
CursorContext.prototype.getVerticalOffsetForViewLine = function (viewLineNumber) {
return this.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewLineNumber);
};
return CursorContext;
}());
exports.CursorContext = CursorContext;
var PartialModelCursorState = /** @class */ (function () {
function PartialModelCursorState(modelState) {
this.modelState = modelState;
this.viewState = null;
}
return PartialModelCursorState;
}());
exports.PartialModelCursorState = PartialModelCursorState;
var PartialViewCursorState = /** @class */ (function () {
function PartialViewCursorState(viewState) {
this.modelState = null;
this.viewState = viewState;
}
return PartialViewCursorState;
}());
exports.PartialViewCursorState = PartialViewCursorState;
var CursorState = /** @class */ (function () {
function CursorState(modelState, viewState) {
this.modelState = modelState;
this.viewState = viewState;
}
CursorState.fromModelState = function (modelState) {
return new PartialModelCursorState(modelState);
};
CursorState.fromViewState = function (viewState) {
return new PartialViewCursorState(viewState);
};
CursorState.fromModelSelection = function (modelSelection) {
var selectionStartLineNumber = modelSelection.selectionStartLineNumber;
var selectionStartColumn = modelSelection.selectionStartColumn;
var positionLineNumber = modelSelection.positionLineNumber;
var positionColumn = modelSelection.positionColumn;
var modelState = new SingleCursorState(new range_1.Range(selectionStartLineNumber, selectionStartColumn, selectionStartLineNumber, selectionStartColumn), 0, new position_1.Position(positionLineNumber, positionColumn), 0);
return CursorState.fromModelState(modelState);
};
CursorState.fromModelSelections = function (modelSelections) {
var states = [];
for (var i = 0, len = modelSelections.length; i < len; i++) {
states[i] = this.fromModelSelection(modelSelections[i]);
}
return states;
};
CursorState.prototype.equals = function (other) {
return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState));
};
return CursorState;
}());
exports.CursorState = CursorState;
var EditOperationResult = /** @class */ (function () {
function EditOperationResult(type, commands, opts) {
this.type = type;
this.commands = commands;
this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore;
this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter;
}
return EditOperationResult;
}());
exports.EditOperationResult = EditOperationResult;
/**
* Common operations that work and make sense both on the model and on the view model.
*/
var CursorColumns = /** @class */ (function () {
function CursorColumns() {
}
CursorColumns.visibleColumnFromColumn = function (lineContent, column, tabSize) {
var lineContentLength = lineContent.length;
var endOffset = column - 1 < lineContentLength ? column - 1 : lineContentLength;
var result = 0;
var i = 0;
while (i < endOffset) {
var codePoint = strings.getNextCodePoint(lineContent, endOffset, i);
i += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
if (codePoint === 9 /* Tab */) {
result = CursorColumns.nextRenderTabStop(result, tabSize);
}
else {
var graphemeBreakType = strings.getGraphemeBreakType(codePoint);
while (i < endOffset) {
var nextCodePoint = strings.getNextCodePoint(lineContent, endOffset, i);
var nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint);
if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
break;
}
i += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
graphemeBreakType = nextGraphemeBreakType;
}
if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) {
result = result + 2;
}
else {
result = result + 1;
}
}
}
return result;
};
CursorColumns.visibleColumnFromColumn2 = function (config, model, position) {
return this.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, config.tabSize);
};
CursorColumns.columnFromVisibleColumn = function (lineContent, visibleColumn, tabSize) {
if (visibleColumn <= 0) {
return 1;
}
var lineLength = lineContent.length;
var beforeVisibleColumn = 0;
var beforeColumn = 1;
var i = 0;
while (i < lineLength) {
var codePoint = strings.getNextCodePoint(lineContent, lineLength, i);
i += (codePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
var afterVisibleColumn = void 0;
if (codePoint === 9 /* Tab */) {
afterVisibleColumn = CursorColumns.nextRenderTabStop(beforeVisibleColumn, tabSize);
}
else {
var graphemeBreakType = strings.getGraphemeBreakType(codePoint);
while (i < lineLength) {
var nextCodePoint = strings.getNextCodePoint(lineContent, lineLength, i);
var nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint);
if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
break;
}
i += (nextCodePoint >= 65536 /* UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
graphemeBreakType = nextGraphemeBreakType;
}
if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) {
afterVisibleColumn = beforeVisibleColumn + 2;
}
else {
afterVisibleColumn = beforeVisibleColumn + 1;
}
}
var afterColumn = i + 1;
if (afterVisibleColumn >= visibleColumn) {
var beforeDelta = visibleColumn - beforeVisibleColumn;
var afterDelta = afterVisibleColumn - visibleColumn;
if (afterDelta < beforeDelta) {
return afterColumn;
}
else {
return beforeColumn;
}
}
beforeVisibleColumn = afterVisibleColumn;
beforeColumn = afterColumn;
}
// walked the entire string
return lineLength + 1;
};
CursorColumns.columnFromVisibleColumn2 = function (config, model, lineNumber, visibleColumn) {
var result = this.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, config.tabSize);
var minColumn = model.getLineMinColumn(lineNumber);
if (result < minColumn) {
return minColumn;
}
var maxColumn = model.getLineMaxColumn(lineNumber);
if (result > maxColumn) {
return maxColumn;
}
return result;
};
/**
* ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)
*/
CursorColumns.nextRenderTabStop = function (visibleColumn, tabSize) {
return visibleColumn + tabSize - visibleColumn % tabSize;
};
/**
* ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)
*/
CursorColumns.nextIndentTabStop = function (visibleColumn, indentSize) {
return visibleColumn + indentSize - visibleColumn % indentSize;
};
/**
* ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)
*/
CursorColumns.prevRenderTabStop = function (column, tabSize) {
return column - 1 - (column - 1) % tabSize;
};
/**
* ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)
*/
CursorColumns.prevIndentTabStop = function (column, indentSize) {
return column - 1 - (column - 1) % indentSize;
};
return CursorColumns;
}());
exports.CursorColumns = CursorColumns;
function isQuote(ch) {
return (ch === '\'' || ch === '"' || ch === '`');
}
exports.isQuote = isQuote;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[211/*vs/editor/common/commands/shiftCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,40/*vs/editor/common/controller/cursorCommon*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, strings, cursorCommon_1, range_1, selection_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var repeatCache = Object.create(null);
function cachedStringRepeat(str, count) {
if (!repeatCache[str]) {
repeatCache[str] = ['', str];
}
var cache = repeatCache[str];
for (var i = cache.length; i <= count; i++) {
cache[i] = cache[i - 1] + str;
}
return cache[count];
}
exports.cachedStringRepeat = cachedStringRepeat;
var ShiftCommand = /** @class */ (function () {
function ShiftCommand(range, opts) {
this._opts = opts;
this._selection = range;
this._selectionId = null;
this._useLastEditRangeForCursorEndPosition = false;
this._selectionStartColumnStaysPut = false;
}
ShiftCommand.unshiftIndent = function (line, column, tabSize, indentSize, insertSpaces) {
// Determine the visible column where the content starts
var contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize);
if (insertSpaces) {
var indent = cachedStringRepeat(' ', indentSize);
var desiredTabStop = cursorCommon_1.CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize);
var indentCount = desiredTabStop / indentSize; // will be an integer
return cachedStringRepeat(indent, indentCount);
}
else {
var indent = '\t';
var desiredTabStop = cursorCommon_1.CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize);
var indentCount = desiredTabStop / tabSize; // will be an integer
return cachedStringRepeat(indent, indentCount);
}
};
ShiftCommand.shiftIndent = function (line, column, tabSize, indentSize, insertSpaces) {
// Determine the visible column where the content starts
var contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize);
if (insertSpaces) {
var indent = cachedStringRepeat(' ', indentSize);
var desiredTabStop = cursorCommon_1.CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize);
var indentCount = desiredTabStop / indentSize; // will be an integer
return cachedStringRepeat(indent, indentCount);
}
else {
var indent = '\t';
var desiredTabStop = cursorCommon_1.CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize);
var indentCount = desiredTabStop / tabSize; // will be an integer
return cachedStringRepeat(indent, indentCount);
}
};
ShiftCommand.prototype._addEditOperation = function (builder, range, text) {
if (this._useLastEditRangeForCursorEndPosition) {
builder.addTrackedEditOperation(range, text);
}
else {
builder.addEditOperation(range, text);
}
};
ShiftCommand.prototype.getEditOperations = function (model, builder) {
var startLine = this._selection.startLineNumber;
var endLine = this._selection.endLineNumber;
if (this._selection.endColumn === 1 && startLine !== endLine) {
endLine = endLine - 1;
}
var _a = this._opts, tabSize = _a.tabSize, indentSize = _a.indentSize, insertSpaces = _a.insertSpaces;
var shouldIndentEmptyLines = (startLine === endLine);
// if indenting or outdenting on a whitespace only line
if (this._selection.isEmpty()) {
if (/^\s*$/.test(model.getLineContent(startLine))) {
this._useLastEditRangeForCursorEndPosition = true;
}
}
if (this._opts.useTabStops) {
// keep track of previous line's "miss-alignment"
var previousLineExtraSpaces = 0, extraSpaces = 0;
for (var lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) {
extraSpaces = 0;
var lineText = model.getLineContent(lineNumber);
var indentationEndIndex = strings.firstNonWhitespaceIndex(lineText);
if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
// empty line or line with no leading whitespace => nothing to do
continue;
}
if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
// do not indent empty lines => nothing to do
continue;
}
if (indentationEndIndex === -1) {
// the entire line is whitespace
indentationEndIndex = lineText.length;
}
if (lineNumber > 1) {
var contentStartVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize);
if (contentStartVisibleColumn % indentSize !== 0) {
// The current line is "miss-aligned", so let's see if this is expected...
// This can only happen when it has trailing commas in the indent
if (model.isCheapToTokenize(lineNumber - 1)) {
var enterAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._opts.autoIndent, model, new range_1.Range(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1), lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)));
if (enterAction) {
extraSpaces = previousLineExtraSpaces;
if (enterAction.appendText) {
for (var j = 0, lenJ = enterAction.appendText.length; j < lenJ && extraSpaces < indentSize; j++) {
if (enterAction.appendText.charCodeAt(j) === 32 /* Space */) {
extraSpaces++;
}
else {
break;
}
}
}
if (enterAction.removeText) {
extraSpaces = Math.max(0, extraSpaces - enterAction.removeText);
}
// Act as if `prefixSpaces` is not part of the indentation
for (var j = 0; j < extraSpaces; j++) {
if (indentationEndIndex === 0 || lineText.charCodeAt(indentationEndIndex - 1) !== 32 /* Space */) {
break;
}
indentationEndIndex--;
}
}
}
}
}
if (this._opts.isUnshift && indentationEndIndex === 0) {
// line with no leading whitespace => nothing to do
continue;
}
var desiredIndent = void 0;
if (this._opts.isUnshift) {
desiredIndent = ShiftCommand.unshiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
}
else {
desiredIndent = ShiftCommand.shiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
}
this._addEditOperation(builder, new range_1.Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), desiredIndent);
if (lineNumber === startLine && !this._selection.isEmpty()) {
// Force the startColumn to stay put because we're inserting after it
this._selectionStartColumnStaysPut = (this._selection.startColumn <= indentationEndIndex + 1);
}
}
}
else {
var oneIndent = (insertSpaces ? cachedStringRepeat(' ', indentSize) : '\t');
for (var lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
var lineText = model.getLineContent(lineNumber);
var indentationEndIndex = strings.firstNonWhitespaceIndex(lineText);
if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
// empty line or line with no leading whitespace => nothing to do
continue;
}
if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
// do not indent empty lines => nothing to do
continue;
}
if (indentationEndIndex === -1) {
// the entire line is whitespace
indentationEndIndex = lineText.length;
}
if (this._opts.isUnshift && indentationEndIndex === 0) {
// line with no leading whitespace => nothing to do
continue;
}
if (this._opts.isUnshift) {
indentationEndIndex = Math.min(indentationEndIndex, indentSize);
for (var i = 0; i < indentationEndIndex; i++) {
var chr = lineText.charCodeAt(i);
if (chr === 9 /* Tab */) {
indentationEndIndex = i + 1;
break;
}
}
this._addEditOperation(builder, new range_1.Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), '');
}
else {
this._addEditOperation(builder, new range_1.Range(lineNumber, 1, lineNumber, 1), oneIndent);
if (lineNumber === startLine && !this._selection.isEmpty()) {
// Force the startColumn to stay put because we're inserting after it
this._selectionStartColumnStaysPut = (this._selection.startColumn === 1);
}
}
}
}
this._selectionId = builder.trackSelection(this._selection);
};
ShiftCommand.prototype.computeCursorState = function (model, helper) {
if (this._useLastEditRangeForCursorEndPosition) {
var lastOp = helper.getInverseEditOperations()[0];
return new selection_1.Selection(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn);
}
var result = helper.getTrackedSelection(this._selectionId);
if (this._selectionStartColumnStaysPut) {
// The selection start should not move
var initialStartColumn = this._selection.startColumn;
var resultStartColumn = result.startColumn;
if (resultStartColumn <= initialStartColumn) {
return result;
}
if (result.getDirection() === 0 /* LTR */) {
return new selection_1.Selection(result.startLineNumber, initialStartColumn, result.endLineNumber, result.endColumn);
}
return new selection_1.Selection(result.endLineNumber, result.endColumn, result.startLineNumber, initialStartColumn);
}
return result;
};
return ShiftCommand;
}());
exports.ShiftCommand = ShiftCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[483/*vs/editor/common/controller/cursorColumnSelection*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, cursorCommon_1, position_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ColumnSelection = /** @class */ (function () {
function ColumnSelection() {
}
ColumnSelection.columnSelect = function (config, model, fromLineNumber, fromVisibleColumn, toLineNumber, toVisibleColumn) {
var lineCount = Math.abs(toLineNumber - fromLineNumber) + 1;
var reversed = (fromLineNumber > toLineNumber);
var isRTL = (fromVisibleColumn > toVisibleColumn);
var isLTR = (fromVisibleColumn < toVisibleColumn);
var result = [];
// console.log(`fromVisibleColumn: ${fromVisibleColumn}, toVisibleColumn: ${toVisibleColumn}`);
for (var i = 0; i < lineCount; i++) {
var lineNumber = fromLineNumber + (reversed ? -i : i);
var startColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, fromVisibleColumn);
var endColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, toVisibleColumn);
var visibleStartColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, new position_1.Position(lineNumber, startColumn));
var visibleEndColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, new position_1.Position(lineNumber, endColumn));
// console.log(`lineNumber: ${lineNumber}: visibleStartColumn: ${visibleStartColumn}, visibleEndColumn: ${visibleEndColumn}`);
if (isLTR) {
if (visibleStartColumn > toVisibleColumn) {
continue;
}
if (visibleEndColumn < fromVisibleColumn) {
continue;
}
}
if (isRTL) {
if (visibleEndColumn > fromVisibleColumn) {
continue;
}
if (visibleStartColumn < toVisibleColumn) {
continue;
}
}
result.push(new cursorCommon_1.SingleCursorState(new range_1.Range(lineNumber, startColumn, lineNumber, startColumn), 0, new position_1.Position(lineNumber, endColumn), 0));
}
if (result.length === 0) {
// We are after all the lines, so add cursor at the end of each line
for (var i = 0; i < lineCount; i++) {
var lineNumber = fromLineNumber + (reversed ? -i : i);
var maxColumn = model.getLineMaxColumn(lineNumber);
result.push(new cursorCommon_1.SingleCursorState(new range_1.Range(lineNumber, maxColumn, lineNumber, maxColumn), 0, new position_1.Position(lineNumber, maxColumn), 0));
}
}
return {
viewStates: result,
reversed: reversed,
fromLineNumber: fromLineNumber,
fromVisualColumn: fromVisibleColumn,
toLineNumber: toLineNumber,
toVisualColumn: toVisibleColumn
};
};
ColumnSelection.columnSelectLeft = function (config, model, prevColumnSelectData) {
var toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
if (toViewVisualColumn > 1) {
toViewVisualColumn--;
}
return ColumnSelection.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
};
ColumnSelection.columnSelectRight = function (config, model, prevColumnSelectData) {
var maxVisualViewColumn = 0;
var minViewLineNumber = Math.min(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
var maxViewLineNumber = Math.max(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
for (var lineNumber = minViewLineNumber; lineNumber <= maxViewLineNumber; lineNumber++) {
var lineMaxViewColumn = model.getLineMaxColumn(lineNumber);
var lineMaxVisualViewColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, new position_1.Position(lineNumber, lineMaxViewColumn));
maxVisualViewColumn = Math.max(maxVisualViewColumn, lineMaxVisualViewColumn);
}
var toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
if (toViewVisualColumn < maxVisualViewColumn) {
toViewVisualColumn++;
}
return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
};
ColumnSelection.columnSelectUp = function (config, model, prevColumnSelectData, isPaged) {
var linesCount = isPaged ? config.pageSize : 1;
var toViewLineNumber = Math.max(1, prevColumnSelectData.toViewLineNumber - linesCount);
return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
};
ColumnSelection.columnSelectDown = function (config, model, prevColumnSelectData, isPaged) {
var linesCount = isPaged ? config.pageSize : 1;
var toViewLineNumber = Math.min(model.getLineCount(), prevColumnSelectData.toViewLineNumber + linesCount);
return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
};
return ColumnSelection;
}());
exports.ColumnSelection = ColumnSelection;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[158/*vs/editor/common/controller/cursorMoveOperations*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,5/*vs/base/common/strings*/]), function (require, exports, cursorCommon_1, position_1, range_1, strings) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CursorPosition = /** @class */ (function () {
function CursorPosition(lineNumber, column, leftoverVisibleColumns) {
this.lineNumber = lineNumber;
this.column = column;
this.leftoverVisibleColumns = leftoverVisibleColumns;
}
return CursorPosition;
}());
exports.CursorPosition = CursorPosition;
var MoveOperations = /** @class */ (function () {
function MoveOperations() {
}
MoveOperations.leftPosition = function (model, lineNumber, column) {
if (column > model.getLineMinColumn(lineNumber)) {
column = column - strings.prevCharLength(model.getLineContent(lineNumber), column - 1);
}
else if (lineNumber > 1) {
lineNumber = lineNumber - 1;
column = model.getLineMaxColumn(lineNumber);
}
return new position_1.Position(lineNumber, column);
};
MoveOperations.left = function (config, model, lineNumber, column) {
var pos = MoveOperations.leftPosition(model, lineNumber, column);
return new CursorPosition(pos.lineNumber, pos.column, 0);
};
MoveOperations.moveLeft = function (config, model, cursor, inSelectionMode, noOfColumns) {
var lineNumber, column;
if (cursor.hasSelection() && !inSelectionMode) {
// If we are in selection mode, move left without selection cancels selection and puts cursor at the beginning of the selection
lineNumber = cursor.selection.startLineNumber;
column = cursor.selection.startColumn;
}
else {
var r = MoveOperations.left(config, model, cursor.position.lineNumber, cursor.position.column - (noOfColumns - 1));
lineNumber = r.lineNumber;
column = r.column;
}
return cursor.move(inSelectionMode, lineNumber, column, 0);
};
MoveOperations.rightPosition = function (model, lineNumber, column) {
if (column < model.getLineMaxColumn(lineNumber)) {
column = column + strings.nextCharLength(model.getLineContent(lineNumber), column - 1);
}
else if (lineNumber < model.getLineCount()) {
lineNumber = lineNumber + 1;
column = model.getLineMinColumn(lineNumber);
}
return new position_1.Position(lineNumber, column);
};
MoveOperations.right = function (config, model, lineNumber, column) {
var pos = MoveOperations.rightPosition(model, lineNumber, column);
return new CursorPosition(pos.lineNumber, pos.column, 0);
};
MoveOperations.moveRight = function (config, model, cursor, inSelectionMode, noOfColumns) {
var lineNumber, column;
if (cursor.hasSelection() && !inSelectionMode) {
// If we are in selection mode, move right without selection cancels selection and puts cursor at the end of the selection
lineNumber = cursor.selection.endLineNumber;
column = cursor.selection.endColumn;
}
else {
var r = MoveOperations.right(config, model, cursor.position.lineNumber, cursor.position.column + (noOfColumns - 1));
lineNumber = r.lineNumber;
column = r.column;
}
return cursor.move(inSelectionMode, lineNumber, column, 0);
};
MoveOperations.down = function (config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) {
var currentVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns;
lineNumber = lineNumber + count;
var lineCount = model.getLineCount();
if (lineNumber > lineCount) {
lineNumber = lineCount;
if (allowMoveOnLastLine) {
column = model.getLineMaxColumn(lineNumber);
}
else {
column = Math.min(model.getLineMaxColumn(lineNumber), column);
}
}
else {
column = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn);
}
leftoverVisibleColumns = currentVisibleColumn - cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize);
return new CursorPosition(lineNumber, column, leftoverVisibleColumns);
};
MoveOperations.moveDown = function (config, model, cursor, inSelectionMode, linesCount) {
var lineNumber, column;
if (cursor.hasSelection() && !inSelectionMode) {
// If we are in selection mode, move down acts relative to the end of selection
lineNumber = cursor.selection.endLineNumber;
column = cursor.selection.endColumn;
}
else {
lineNumber = cursor.position.lineNumber;
column = cursor.position.column;
}
var r = MoveOperations.down(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);
};
MoveOperations.translateDown = function (config, model, cursor) {
var selection = cursor.selection;
var selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
var position = MoveOperations.down(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
return new cursorCommon_1.SingleCursorState(new range_1.Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new position_1.Position(position.lineNumber, position.column), position.leftoverVisibleColumns);
};
MoveOperations.up = function (config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) {
var currentVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns;
lineNumber = lineNumber - count;
if (lineNumber < 1) {
lineNumber = 1;
if (allowMoveOnFirstLine) {
column = model.getLineMinColumn(lineNumber);
}
else {
column = Math.min(model.getLineMaxColumn(lineNumber), column);
}
}
else {
column = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn);
}
leftoverVisibleColumns = currentVisibleColumn - cursorCommon_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize);
return new CursorPosition(lineNumber, column, leftoverVisibleColumns);
};
MoveOperations.moveUp = function (config, model, cursor, inSelectionMode, linesCount) {
var lineNumber, column;
if (cursor.hasSelection() && !inSelectionMode) {
// If we are in selection mode, move up acts relative to the beginning of selection
lineNumber = cursor.selection.startLineNumber;
column = cursor.selection.startColumn;
}
else {
lineNumber = cursor.position.lineNumber;
column = cursor.position.column;
}
var r = MoveOperations.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);
};
MoveOperations.translateUp = function (config, model, cursor) {
var selection = cursor.selection;
var selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
var position = MoveOperations.up(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
return new cursorCommon_1.SingleCursorState(new range_1.Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new position_1.Position(position.lineNumber, position.column), position.leftoverVisibleColumns);
};
MoveOperations.moveToBeginningOfLine = function (config, model, cursor, inSelectionMode) {
var lineNumber = cursor.position.lineNumber;
var minColumn = model.getLineMinColumn(lineNumber);
var firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn;
var column;
var relevantColumnNumber = cursor.position.column;
if (relevantColumnNumber === firstNonBlankColumn) {
column = minColumn;
}
else {
column = firstNonBlankColumn;
}
return cursor.move(inSelectionMode, lineNumber, column, 0);
};
MoveOperations.moveToEndOfLine = function (config, model, cursor, inSelectionMode) {
var lineNumber = cursor.position.lineNumber;
var maxColumn = model.getLineMaxColumn(lineNumber);
return cursor.move(inSelectionMode, lineNumber, maxColumn, 0);
};
MoveOperations.moveToBeginningOfBuffer = function (config, model, cursor, inSelectionMode) {
return cursor.move(inSelectionMode, 1, 1, 0);
};
MoveOperations.moveToEndOfBuffer = function (config, model, cursor, inSelectionMode) {
var lastLineNumber = model.getLineCount();
var lastColumn = model.getLineMaxColumn(lastLineNumber);
return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0);
};
return MoveOperations;
}());
exports.MoveOperations = MoveOperations;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[212/*vs/editor/common/controller/cursorDeleteOperations*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,80/*vs/editor/common/commands/replaceCommand*/,40/*vs/editor/common/controller/cursorCommon*/,158/*vs/editor/common/controller/cursorMoveOperations*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, replaceCommand_1, cursorCommon_1, cursorMoveOperations_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DeleteOperations = /** @class */ (function () {
function DeleteOperations() {
}
DeleteOperations.deleteRight = function (prevEditOperationType, config, model, selections) {
var commands = [];
var shouldPushStackElementBefore = (prevEditOperationType !== 3 /* DeletingRight */);
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
var deleteSelection = selection;
if (deleteSelection.isEmpty()) {
var position = selection.getPosition();
var rightOfPosition = cursorMoveOperations_1.MoveOperations.right(config, model, position.lineNumber, position.column);
deleteSelection = new range_1.Range(rightOfPosition.lineNumber, rightOfPosition.column, position.lineNumber, position.column);
}
if (deleteSelection.isEmpty()) {
// Probably at end of file => ignore
commands[i] = null;
continue;
}
if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {
shouldPushStackElementBefore = true;
}
commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, '');
}
return [shouldPushStackElementBefore, commands];
};
DeleteOperations._isAutoClosingPairDelete = function (config, model, selections) {
if (config.autoClosingBrackets === 'never' && config.autoClosingQuotes === 'never') {
return false;
}
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
var position = selection.getPosition();
if (!selection.isEmpty()) {
return false;
}
var lineText = model.getLineContent(position.lineNumber);
var character = lineText[position.column - 2];
var autoClosingPairCandidates = config.autoClosingPairsOpen2.get(character);
if (!autoClosingPairCandidates) {
return false;
}
if (cursorCommon_1.isQuote(character)) {
if (config.autoClosingQuotes === 'never') {
return false;
}
}
else {
if (config.autoClosingBrackets === 'never') {
return false;
}
}
var afterCharacter = lineText[position.column - 1];
var foundAutoClosingPair = false;
for (var _i = 0, autoClosingPairCandidates_1 = autoClosingPairCandidates; _i < autoClosingPairCandidates_1.length; _i++) {
var autoClosingPairCandidate = autoClosingPairCandidates_1[_i];
if (autoClosingPairCandidate.open === character && autoClosingPairCandidate.close === afterCharacter) {
foundAutoClosingPair = true;
}
}
if (!foundAutoClosingPair) {
return false;
}
}
return true;
};
DeleteOperations._runAutoClosingPairDelete = function (config, model, selections) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var position = selections[i].getPosition();
var deleteSelection = new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1);
commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, '');
}
return [true, commands];
};
DeleteOperations.deleteLeft = function (prevEditOperationType, config, model, selections) {
if (this._isAutoClosingPairDelete(config, model, selections)) {
return this._runAutoClosingPairDelete(config, model, selections);
}
var commands = [];
var shouldPushStackElementBefore = (prevEditOperationType !== 2 /* DeletingLeft */);
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
var deleteSelection = selection;
if (deleteSelection.isEmpty()) {
var position = selection.getPosition();
if (config.useTabStops && position.column > 1) {
var lineContent = model.getLineContent(position.lineNumber);
var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
var lastIndentationColumn = (firstNonWhitespaceIndex === -1
? /* entire string is whitespace */ lineContent.length + 1
: firstNonWhitespaceIndex + 1);
if (position.column <= lastIndentationColumn) {
var fromVisibleColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, position);
var toVisibleColumn = cursorCommon_1.CursorColumns.prevIndentTabStop(fromVisibleColumn, config.indentSize);
var toColumn = cursorCommon_1.CursorColumns.columnFromVisibleColumn2(config, model, position.lineNumber, toVisibleColumn);
deleteSelection = new range_1.Range(position.lineNumber, toColumn, position.lineNumber, position.column);
}
else {
deleteSelection = new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column);
}
}
else {
var leftOfPosition = cursorMoveOperations_1.MoveOperations.left(config, model, position.lineNumber, position.column);
deleteSelection = new range_1.Range(leftOfPosition.lineNumber, leftOfPosition.column, position.lineNumber, position.column);
}
}
if (deleteSelection.isEmpty()) {
// Probably at beginning of file => ignore
commands[i] = null;
continue;
}
if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {
shouldPushStackElementBefore = true;
}
commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, '');
}
return [shouldPushStackElementBefore, commands];
};
DeleteOperations.cut = function (config, model, selections) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
if (selection.isEmpty()) {
if (config.emptySelectionClipboard) {
// This is a full line cut
var position = selection.getPosition();
var startLineNumber = void 0, startColumn = void 0, endLineNumber = void 0, endColumn = void 0;
if (position.lineNumber < model.getLineCount()) {
// Cutting a line in the middle of the model
startLineNumber = position.lineNumber;
startColumn = 1;
endLineNumber = position.lineNumber + 1;
endColumn = 1;
}
else if (position.lineNumber > 1) {
// Cutting the last line & there are more than 1 lines in the model
startLineNumber = position.lineNumber - 1;
startColumn = model.getLineMaxColumn(position.lineNumber - 1);
endLineNumber = position.lineNumber;
endColumn = model.getLineMaxColumn(position.lineNumber);
}
else {
// Cutting the single line that the model contains
startLineNumber = position.lineNumber;
startColumn = 1;
endLineNumber = position.lineNumber;
endColumn = model.getLineMaxColumn(position.lineNumber);
}
var deleteSelection = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
if (!deleteSelection.isEmpty()) {
commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, '');
}
else {
commands[i] = null;
}
}
else {
// Cannot cut empty selection
commands[i] = null;
}
}
else {
commands[i] = new replaceCommand_1.ReplaceCommand(selection, '');
}
}
return new cursorCommon_1.EditOperationResult(0 /* Other */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: true
});
};
return DeleteOperations;
}());
exports.DeleteOperations = DeleteOperations;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[159/*vs/editor/common/controller/cursorTypeOperations*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,5/*vs/base/common/strings*/,80/*vs/editor/common/commands/replaceCommand*/,211/*vs/editor/common/commands/shiftCommand*/,340/*vs/editor/common/commands/surroundSelectionCommand*/,40/*vs/editor/common/controller/cursorCommon*/,89/*vs/editor/common/controller/wordCharacterClassifier*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,90/*vs/editor/common/modes/languageConfiguration*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, errors_1, strings, replaceCommand_1, shiftCommand_1, surroundSelectionCommand_1, cursorCommon_1, wordCharacterClassifier_1, range_1, selection_1, languageConfiguration_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TypeOperations = /** @class */ (function () {
function TypeOperations() {
}
TypeOperations.indent = function (config, model, selections) {
if (model === null || selections === null) {
return [];
}
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
commands[i] = new shiftCommand_1.ShiftCommand(selections[i], {
isUnshift: false,
tabSize: config.tabSize,
indentSize: config.indentSize,
insertSpaces: config.insertSpaces,
useTabStops: config.useTabStops,
autoIndent: config.autoIndent
});
}
return commands;
};
TypeOperations.outdent = function (config, model, selections) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
commands[i] = new shiftCommand_1.ShiftCommand(selections[i], {
isUnshift: true,
tabSize: config.tabSize,
indentSize: config.indentSize,
insertSpaces: config.insertSpaces,
useTabStops: config.useTabStops,
autoIndent: config.autoIndent
});
}
return commands;
};
TypeOperations.shiftIndent = function (config, indentation, count) {
count = count || 1;
return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
};
TypeOperations.unshiftIndent = function (config, indentation, count) {
count = count || 1;
return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
};
TypeOperations._distributedPaste = function (config, model, selections, text) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], text[i]);
}
return new cursorCommon_1.EditOperationResult(0 /* Other */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: true
});
};
TypeOperations._simplePaste = function (config, model, selections, text, pasteOnNewLine) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
var position = selection.getPosition();
if (pasteOnNewLine && !selection.isEmpty()) {
pasteOnNewLine = false;
}
if (pasteOnNewLine && text.indexOf('\n') !== text.length - 1) {
pasteOnNewLine = false;
}
if (pasteOnNewLine) {
// Paste entire line at the beginning of line
var typeSelection = new range_1.Range(position.lineNumber, 1, position.lineNumber, 1);
commands[i] = new replaceCommand_1.ReplaceCommandThatPreservesSelection(typeSelection, text, selection, true);
}
else {
commands[i] = new replaceCommand_1.ReplaceCommand(selection, text);
}
}
return new cursorCommon_1.EditOperationResult(0 /* Other */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: true
});
};
TypeOperations._distributePasteToCursors = function (config, selections, text, pasteOnNewLine, multicursorText) {
if (pasteOnNewLine) {
return null;
}
if (selections.length === 1) {
return null;
}
if (multicursorText && multicursorText.length === selections.length) {
return multicursorText;
}
if (config.multiCursorPaste === 'spread') {
// Try to spread the pasted text in case the line count matches the cursor count
// Remove trailing \n if present
if (text.charCodeAt(text.length - 1) === 10 /* LineFeed */) {
text = text.substr(0, text.length - 1);
}
// Remove trailing \r if present
if (text.charCodeAt(text.length - 1) === 13 /* CarriageReturn */) {
text = text.substr(0, text.length - 1);
}
var lines = text.split(/\r\n|\r|\n/);
if (lines.length === selections.length) {
return lines;
}
}
return null;
};
TypeOperations.paste = function (config, model, selections, text, pasteOnNewLine, multicursorText) {
var distributedPaste = this._distributePasteToCursors(config, selections, text, pasteOnNewLine, multicursorText);
if (distributedPaste) {
selections = selections.sort(range_1.Range.compareRangesUsingStarts);
return this._distributedPaste(config, model, selections, distributedPaste);
}
else {
return this._simplePaste(config, model, selections, text, pasteOnNewLine);
}
};
TypeOperations._goodIndentForLine = function (config, model, lineNumber) {
var action = null;
var indentation = '';
var expectedIndentAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getInheritIndentForLine(config.autoIndent, model, lineNumber, false);
if (expectedIndentAction) {
action = expectedIndentAction.action;
indentation = expectedIndentAction.indentation;
}
else if (lineNumber > 1) {
var lastLineNumber = void 0;
for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
var lineText = model.getLineContent(lastLineNumber);
var nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineText);
if (nonWhitespaceIdx >= 0) {
break;
}
}
if (lastLineNumber < 1) {
// No previous line with content found
return null;
}
var maxColumn = model.getLineMaxColumn(lastLineNumber);
var expectedEnterAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(config.autoIndent, model, new range_1.Range(lastLineNumber, maxColumn, lastLineNumber, maxColumn));
if (expectedEnterAction) {
indentation = expectedEnterAction.indentation + expectedEnterAction.appendText;
}
}
if (action) {
if (action === languageConfiguration_1.IndentAction.Indent) {
indentation = TypeOperations.shiftIndent(config, indentation);
}
if (action === languageConfiguration_1.IndentAction.Outdent) {
indentation = TypeOperations.unshiftIndent(config, indentation);
}
indentation = config.normalizeIndentation(indentation);
}
if (!indentation) {
return null;
}
return indentation;
};
TypeOperations._replaceJumpToNextIndent = function (config, model, selection, insertsAutoWhitespace) {
var typeText = '';
var position = selection.getStartPosition();
if (config.insertSpaces) {
var visibleColumnFromColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, position);
var indentSize = config.indentSize;
var spacesCnt = indentSize - (visibleColumnFromColumn % indentSize);
for (var i = 0; i < spacesCnt; i++) {
typeText += ' ';
}
}
else {
typeText = '\t';
}
return new replaceCommand_1.ReplaceCommand(selection, typeText, insertsAutoWhitespace);
};
TypeOperations.tab = function (config, model, selections) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
if (selection.isEmpty()) {
var lineText = model.getLineContent(selection.startLineNumber);
if (/^\s*$/.test(lineText) && model.isCheapToTokenize(selection.startLineNumber)) {
var goodIndent = this._goodIndentForLine(config, model, selection.startLineNumber);
goodIndent = goodIndent || '\t';
var possibleTypeText = config.normalizeIndentation(goodIndent);
if (!strings.startsWith(lineText, possibleTypeText)) {
commands[i] = new replaceCommand_1.ReplaceCommand(new range_1.Range(selection.startLineNumber, 1, selection.startLineNumber, lineText.length + 1), possibleTypeText, true);
continue;
}
}
commands[i] = this._replaceJumpToNextIndent(config, model, selection, true);
}
else {
if (selection.startLineNumber === selection.endLineNumber) {
var lineMaxColumn = model.getLineMaxColumn(selection.startLineNumber);
if (selection.startColumn !== 1 || selection.endColumn !== lineMaxColumn) {
// This is a single line selection that is not the entire line
commands[i] = this._replaceJumpToNextIndent(config, model, selection, false);
continue;
}
}
commands[i] = new shiftCommand_1.ShiftCommand(selection, {
isUnshift: false,
tabSize: config.tabSize,
indentSize: config.indentSize,
insertSpaces: config.insertSpaces,
useTabStops: config.useTabStops,
autoIndent: config.autoIndent
});
}
}
return commands;
};
TypeOperations.replacePreviousChar = function (prevEditOperationType, config, model, selections, txt, replaceCharCnt) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
if (!selection.isEmpty()) {
// looks like https://github.com/Microsoft/vscode/issues/2773
// where a cursor operation occurred before a canceled composition
// => ignore composition
commands[i] = null;
continue;
}
var pos = selection.getPosition();
var startColumn = Math.max(1, pos.column - replaceCharCnt);
var range = new range_1.Range(pos.lineNumber, startColumn, pos.lineNumber, pos.column);
commands[i] = new replaceCommand_1.ReplaceCommand(range, txt);
}
return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, {
shouldPushStackElementBefore: (prevEditOperationType !== 1 /* Typing */),
shouldPushStackElementAfter: false
});
};
TypeOperations._typeCommand = function (range, text, keepPosition) {
if (keepPosition) {
return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, text, true);
}
else {
return new replaceCommand_1.ReplaceCommand(range, text, true);
}
};
TypeOperations._enter = function (config, model, keepPosition, range) {
if (config.autoIndent === 0 /* None */) {
return TypeOperations._typeCommand(range, '\n', keepPosition);
}
if (!model.isCheapToTokenize(range.getStartPosition().lineNumber) || config.autoIndent === 1 /* Keep */) {
var lineText_1 = model.getLineContent(range.startLineNumber);
var indentation_1 = strings.getLeadingWhitespace(lineText_1).substring(0, range.startColumn - 1);
return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation_1), keepPosition);
}
var r = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(config.autoIndent, model, range);
if (r) {
if (r.indentAction === languageConfiguration_1.IndentAction.None) {
// Nothing special
return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(r.indentation + r.appendText), keepPosition);
}
else if (r.indentAction === languageConfiguration_1.IndentAction.Indent) {
// Indent once
return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(r.indentation + r.appendText), keepPosition);
}
else if (r.indentAction === languageConfiguration_1.IndentAction.IndentOutdent) {
// Ultra special
var normalIndent = config.normalizeIndentation(r.indentation);
var increasedIndent = config.normalizeIndentation(r.indentation + r.appendText);
var typeText = '\n' + increasedIndent + '\n' + normalIndent;
if (keepPosition) {
return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, typeText, true);
}
else {
return new replaceCommand_1.ReplaceCommandWithOffsetCursorState(range, typeText, -1, increasedIndent.length - normalIndent.length, true);
}
}
else if (r.indentAction === languageConfiguration_1.IndentAction.Outdent) {
var actualIndentation = TypeOperations.unshiftIndent(config, r.indentation);
return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(actualIndentation + r.appendText), keepPosition);
}
}
var lineText = model.getLineContent(range.startLineNumber);
var indentation = strings.getLeadingWhitespace(lineText).substring(0, range.startColumn - 1);
if (config.autoIndent >= 4 /* Full */) {
var ir = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentForEnter(config.autoIndent, model, range, {
unshiftIndent: function (indent) {
return TypeOperations.unshiftIndent(config, indent);
},
shiftIndent: function (indent) {
return TypeOperations.shiftIndent(config, indent);
},
normalizeIndentation: function (indent) {
return config.normalizeIndentation(indent);
}
});
if (ir) {
var oldEndViewColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(config, model, range.getEndPosition());
var oldEndColumn = range.endColumn;
var beforeText = '\n';
if (indentation !== config.normalizeIndentation(ir.beforeEnter)) {
beforeText = config.normalizeIndentation(ir.beforeEnter) + lineText.substring(indentation.length, range.startColumn - 1) + '\n';
range = new range_1.Range(range.startLineNumber, 1, range.endLineNumber, range.endColumn);
}
var newLineContent = model.getLineContent(range.endLineNumber);
var firstNonWhitespace = strings.firstNonWhitespaceIndex(newLineContent);
if (firstNonWhitespace >= 0) {
range = range.setEndPosition(range.endLineNumber, Math.max(range.endColumn, firstNonWhitespace + 1));
}
else {
range = range.setEndPosition(range.endLineNumber, model.getLineMaxColumn(range.endLineNumber));
}
if (keepPosition) {
return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, beforeText + config.normalizeIndentation(ir.afterEnter), true);
}
else {
var offset = 0;
if (oldEndColumn <= firstNonWhitespace + 1) {
if (!config.insertSpaces) {
oldEndViewColumn = Math.ceil(oldEndViewColumn / config.indentSize);
}
offset = Math.min(oldEndViewColumn + 1 - config.normalizeIndentation(ir.afterEnter).length - 1, 0);
}
return new replaceCommand_1.ReplaceCommandWithOffsetCursorState(range, beforeText + config.normalizeIndentation(ir.afterEnter), 0, offset, true);
}
}
}
return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition);
};
TypeOperations._isAutoIndentType = function (config, model, selections) {
if (config.autoIndent < 4 /* Full */) {
return false;
}
for (var i = 0, len = selections.length; i < len; i++) {
if (!model.isCheapToTokenize(selections[i].getEndPosition().lineNumber)) {
return false;
}
}
return true;
};
TypeOperations._runAutoIndentType = function (config, model, range, ch) {
var currentIndentation = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentationAtPosition(model, range.startLineNumber, range.startColumn);
var actualIndentation = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentActionForType(config.autoIndent, model, range, ch, {
shiftIndent: function (indentation) {
return TypeOperations.shiftIndent(config, indentation);
},
unshiftIndent: function (indentation) {
return TypeOperations.unshiftIndent(config, indentation);
},
});
if (actualIndentation === null) {
return null;
}
if (actualIndentation !== config.normalizeIndentation(currentIndentation)) {
var firstNonWhitespace = model.getLineFirstNonWhitespaceColumn(range.startLineNumber);
if (firstNonWhitespace === 0) {
return TypeOperations._typeCommand(new range_1.Range(range.startLineNumber, 0, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) + ch, false);
}
else {
return TypeOperations._typeCommand(new range_1.Range(range.startLineNumber, 0, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) +
model.getLineContent(range.startLineNumber).substring(firstNonWhitespace - 1, range.startColumn - 1) + ch, false);
}
}
return null;
};
TypeOperations._isAutoClosingOvertype = function (config, model, selections, autoClosedCharacters, ch) {
if (config.autoClosingOvertype === 'never') {
return false;
}
if (!config.autoClosingPairsClose2.has(ch)) {
return false;
}
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
if (!selection.isEmpty()) {
return false;
}
var position = selection.getPosition();
var lineText = model.getLineContent(position.lineNumber);
var afterCharacter = lineText.charAt(position.column - 1);
if (afterCharacter !== ch) {
return false;
}
// Do not over-type quotes after a backslash
var chIsQuote = cursorCommon_1.isQuote(ch);
var beforeCharacter = position.column > 2 ? lineText.charCodeAt(position.column - 2) : 0 /* Null */;
if (beforeCharacter === 92 /* Backslash */ && chIsQuote) {
return false;
}
// Must over-type a closing character typed by the editor
if (config.autoClosingOvertype === 'auto') {
var found = false;
for (var j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) {
var autoClosedCharacter = autoClosedCharacters[j];
if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
}
return true;
};
TypeOperations._runAutoClosingOvertype = function (prevEditOperationType, config, model, selections, ch) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
var position = selection.getPosition();
var typeSelection = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column + 1);
commands[i] = new replaceCommand_1.ReplaceCommand(typeSelection, ch);
}
return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, {
shouldPushStackElementBefore: (prevEditOperationType !== 1 /* Typing */),
shouldPushStackElementAfter: false
});
};
TypeOperations._autoClosingPairIsSymmetric = function (autoClosingPair) {
var open = autoClosingPair.open, close = autoClosingPair.close;
return (open.indexOf(close) >= 0 || close.indexOf(open) >= 0);
};
TypeOperations._isBeforeClosingBrace = function (config, autoClosingPair, characterAfter) {
var otherAutoClosingPairs = config.autoClosingPairsClose2.get(characterAfter);
if (!otherAutoClosingPairs) {
return false;
}
var thisBraceIsSymmetric = TypeOperations._autoClosingPairIsSymmetric(autoClosingPair);
for (var _i = 0, otherAutoClosingPairs_1 = otherAutoClosingPairs; _i < otherAutoClosingPairs_1.length; _i++) {
var otherAutoClosingPair = otherAutoClosingPairs_1[_i];
var otherBraceIsSymmetric = TypeOperations._autoClosingPairIsSymmetric(otherAutoClosingPair);
if (!thisBraceIsSymmetric && otherBraceIsSymmetric) {
continue;
}
return true;
}
return false;
};
TypeOperations._findAutoClosingPairOpen = function (config, model, positions, ch) {
var autoClosingPairCandidates = config.autoClosingPairsOpen2.get(ch);
if (!autoClosingPairCandidates) {
return null;
}
// Determine which auto-closing pair it is
var autoClosingPair = null;
for (var _i = 0, autoClosingPairCandidates_1 = autoClosingPairCandidates; _i < autoClosingPairCandidates_1.length; _i++) {
var autoClosingPairCandidate = autoClosingPairCandidates_1[_i];
if (autoClosingPair === null || autoClosingPairCandidate.open.length > autoClosingPair.open.length) {
var candidateIsMatch = true;
for (var _a = 0, positions_1 = positions; _a < positions_1.length; _a++) {
var position = positions_1[_a];
var relevantText = model.getValueInRange(new range_1.Range(position.lineNumber, position.column - autoClosingPairCandidate.open.length + 1, position.lineNumber, position.column));
if (relevantText + ch !== autoClosingPairCandidate.open) {
candidateIsMatch = false;
break;
}
}
if (candidateIsMatch) {
autoClosingPair = autoClosingPairCandidate;
}
}
}
return autoClosingPair;
};
TypeOperations._isAutoClosingOpenCharType = function (config, model, selections, ch, insertOpenCharacter) {
var chIsQuote = cursorCommon_1.isQuote(ch);
var autoCloseConfig = chIsQuote ? config.autoClosingQuotes : config.autoClosingBrackets;
if (autoCloseConfig === 'never') {
return null;
}
var autoClosingPair = this._findAutoClosingPairOpen(config, model, selections.map(function (s) { return s.getPosition(); }), ch);
if (!autoClosingPair) {
return null;
}
var shouldAutoCloseBefore = chIsQuote ? config.shouldAutoCloseBefore.quote : config.shouldAutoCloseBefore.bracket;
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
if (!selection.isEmpty()) {
return null;
}
var position = selection.getPosition();
var lineText = model.getLineContent(position.lineNumber);
// Only consider auto closing the pair if a space follows or if another autoclosed pair follows
if (lineText.length > position.column - 1) {
var characterAfter = lineText.charAt(position.column - 1);
var isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config, autoClosingPair, characterAfter);
if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) {
return null;
}
}
if (!model.isCheapToTokenize(position.lineNumber)) {
// Do not force tokenization
return null;
}
// Do not auto-close ' or " after a word character
if (autoClosingPair.open.length === 1 && chIsQuote && autoCloseConfig !== 'always') {
var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(config.wordSeparators);
if (insertOpenCharacter && position.column > 1 && wordSeparators.get(lineText.charCodeAt(position.column - 2)) === 0 /* Regular */) {
return null;
}
if (!insertOpenCharacter && position.column > 2 && wordSeparators.get(lineText.charCodeAt(position.column - 3)) === 0 /* Regular */) {
return null;
}
}
model.forceTokenization(position.lineNumber);
var lineTokens = model.getLineTokens(position.lineNumber);
var shouldAutoClosePair = false;
try {
shouldAutoClosePair = languageConfigurationRegistry_1.LanguageConfigurationRegistry.shouldAutoClosePair(autoClosingPair, lineTokens, insertOpenCharacter ? position.column : position.column - 1);
}
catch (e) {
errors_1.onUnexpectedError(e);
}
if (!shouldAutoClosePair) {
return null;
}
}
return autoClosingPair;
};
TypeOperations._runAutoClosingOpenCharType = function (prevEditOperationType, config, model, selections, ch, insertOpenCharacter, autoClosingPair) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
commands[i] = new TypeWithAutoClosingCommand(selection, ch, insertOpenCharacter, autoClosingPair.close);
}
return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: false
});
};
TypeOperations._shouldSurroundChar = function (config, ch) {
if (cursorCommon_1.isQuote(ch)) {
return (config.autoSurround === 'quotes' || config.autoSurround === 'languageDefined');
}
else {
// Character is a bracket
return (config.autoSurround === 'brackets' || config.autoSurround === 'languageDefined');
}
};
TypeOperations._isSurroundSelectionType = function (config, model, selections, ch) {
if (!TypeOperations._shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) {
return false;
}
var isTypingAQuoteCharacter = cursorCommon_1.isQuote(ch);
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
if (selection.isEmpty()) {
return false;
}
var selectionContainsOnlyWhitespace = true;
for (var lineNumber = selection.startLineNumber; lineNumber <= selection.endLineNumber; lineNumber++) {
var lineText = model.getLineContent(lineNumber);
var startIndex = (lineNumber === selection.startLineNumber ? selection.startColumn - 1 : 0);
var endIndex = (lineNumber === selection.endLineNumber ? selection.endColumn - 1 : lineText.length);
var selectedText = lineText.substring(startIndex, endIndex);
if (/[^ \t]/.test(selectedText)) {
// this selected text contains something other than whitespace
selectionContainsOnlyWhitespace = false;
break;
}
}
if (selectionContainsOnlyWhitespace) {
return false;
}
if (isTypingAQuoteCharacter && selection.startLineNumber === selection.endLineNumber && selection.startColumn + 1 === selection.endColumn) {
var selectionText = model.getValueInRange(selection);
if (cursorCommon_1.isQuote(selectionText)) {
// Typing a quote character on top of another quote character
// => disable surround selection type
return false;
}
}
}
return true;
};
TypeOperations._runSurroundSelectionType = function (prevEditOperationType, config, model, selections, ch) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
var closeCharacter = config.surroundingPairs[ch];
commands[i] = new surroundSelectionCommand_1.SurroundSelectionCommand(selection, ch, closeCharacter);
}
return new cursorCommon_1.EditOperationResult(0 /* Other */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: true
});
};
TypeOperations._isTypeInterceptorElectricChar = function (config, model, selections) {
if (selections.length === 1 && model.isCheapToTokenize(selections[0].getEndPosition().lineNumber)) {
return true;
}
return false;
};
TypeOperations._typeInterceptorElectricChar = function (prevEditOperationType, config, model, selection, ch) {
if (!config.electricChars.hasOwnProperty(ch) || !selection.isEmpty()) {
return null;
}
var position = selection.getPosition();
model.forceTokenization(position.lineNumber);
var lineTokens = model.getLineTokens(position.lineNumber);
var electricAction;
try {
electricAction = languageConfigurationRegistry_1.LanguageConfigurationRegistry.onElectricCharacter(ch, lineTokens, position.column);
}
catch (e) {
errors_1.onUnexpectedError(e);
return null;
}
if (!electricAction) {
return null;
}
if (electricAction.matchOpenBracket) {
var endColumn = (lineTokens.getLineContent() + ch).lastIndexOf(electricAction.matchOpenBracket) + 1;
var match = model.findMatchingBracketUp(electricAction.matchOpenBracket, {
lineNumber: position.lineNumber,
column: endColumn
});
if (match) {
if (match.startLineNumber === position.lineNumber) {
// matched something on the same line => no change in indentation
return null;
}
var matchLine = model.getLineContent(match.startLineNumber);
var matchLineIndentation = strings.getLeadingWhitespace(matchLine);
var newIndentation = config.normalizeIndentation(matchLineIndentation);
var lineText = model.getLineContent(position.lineNumber);
var lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber) || position.column;
var prefix = lineText.substring(lineFirstNonBlankColumn - 1, position.column - 1);
var typeText = newIndentation + prefix + ch;
var typeSelection = new range_1.Range(position.lineNumber, 1, position.lineNumber, position.column);
var command = new replaceCommand_1.ReplaceCommand(typeSelection, typeText);
return new cursorCommon_1.EditOperationResult(1 /* Typing */, [command], {
shouldPushStackElementBefore: false,
shouldPushStackElementAfter: true
});
}
}
return null;
};
/**
* This is very similar with typing, but the character is already in the text buffer!
*/
TypeOperations.compositionEndWithInterceptors = function (prevEditOperationType, config, model, selectionsWhenCompositionStarted, selections, autoClosedCharacters) {
if (!selectionsWhenCompositionStarted || selection_1.Selection.selectionsArrEqual(selectionsWhenCompositionStarted, selections)) {
// no content was typed
return null;
}
var ch = null;
// extract last typed character
for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) {
var selection = selections_1[_i];
if (!selection.isEmpty()) {
return null;
}
var position = selection.getPosition();
var currentChar = model.getValueInRange(new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column));
if (ch === null) {
ch = currentChar;
}
else if (ch !== currentChar) {
return null;
}
}
if (!ch) {
return null;
}
if (this._isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) {
// Unfortunately, the close character is at this point "doubled", so we need to delete it...
var commands = selections.map(function (s) { return new replaceCommand_1.ReplaceCommand(new range_1.Range(s.positionLineNumber, s.positionColumn, s.positionLineNumber, s.positionColumn + 1), '', false); });
return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: false
});
}
var autoClosingPairOpenCharType = this._isAutoClosingOpenCharType(config, model, selections, ch, false);
if (autoClosingPairOpenCharType) {
return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, false, autoClosingPairOpenCharType);
}
return null;
};
TypeOperations.typeWithInterceptors = function (prevEditOperationType, config, model, selections, autoClosedCharacters, ch) {
if (ch === '\n') {
var commands_1 = [];
for (var i = 0, len = selections.length; i < len; i++) {
commands_1[i] = TypeOperations._enter(config, model, false, selections[i]);
}
return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands_1, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: false,
});
}
if (this._isAutoIndentType(config, model, selections)) {
var commands_2 = [];
var autoIndentFails = false;
for (var i = 0, len = selections.length; i < len; i++) {
commands_2[i] = this._runAutoIndentType(config, model, selections[i], ch);
if (!commands_2[i]) {
autoIndentFails = true;
break;
}
}
if (!autoIndentFails) {
return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands_2, {
shouldPushStackElementBefore: true,
shouldPushStackElementAfter: false,
});
}
}
if (this._isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) {
return this._runAutoClosingOvertype(prevEditOperationType, config, model, selections, ch);
}
var autoClosingPairOpenCharType = this._isAutoClosingOpenCharType(config, model, selections, ch, true);
if (autoClosingPairOpenCharType) {
return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, true, autoClosingPairOpenCharType);
}
if (this._isSurroundSelectionType(config, model, selections, ch)) {
return this._runSurroundSelectionType(prevEditOperationType, config, model, selections, ch);
}
// Electric characters make sense only when dealing with a single cursor,
// as multiple cursors typing brackets for example would interfer with bracket matching
if (this._isTypeInterceptorElectricChar(config, model, selections)) {
var r = this._typeInterceptorElectricChar(prevEditOperationType, config, model, selections[0], ch);
if (r) {
return r;
}
}
// A simple character type
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], ch);
}
var shouldPushStackElementBefore = (prevEditOperationType !== 1 /* Typing */);
if (ch === ' ') {
shouldPushStackElementBefore = true;
}
return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, {
shouldPushStackElementBefore: shouldPushStackElementBefore,
shouldPushStackElementAfter: false
});
};
TypeOperations.typeWithoutInterceptors = function (prevEditOperationType, config, model, selections, str) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], str);
}
return new cursorCommon_1.EditOperationResult(1 /* Typing */, commands, {
shouldPushStackElementBefore: (prevEditOperationType !== 1 /* Typing */),
shouldPushStackElementAfter: false
});
};
TypeOperations.lineInsertBefore = function (config, model, selections) {
if (model === null || selections === null) {
return [];
}
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var lineNumber = selections[i].positionLineNumber;
if (lineNumber === 1) {
commands[i] = new replaceCommand_1.ReplaceCommandWithoutChangingPosition(new range_1.Range(1, 1, 1, 1), '\n');
}
else {
lineNumber--;
var column = model.getLineMaxColumn(lineNumber);
commands[i] = this._enter(config, model, false, new range_1.Range(lineNumber, column, lineNumber, column));
}
}
return commands;
};
TypeOperations.lineInsertAfter = function (config, model, selections) {
if (model === null || selections === null) {
return [];
}
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
var lineNumber = selections[i].positionLineNumber;
var column = model.getLineMaxColumn(lineNumber);
commands[i] = this._enter(config, model, false, new range_1.Range(lineNumber, column, lineNumber, column));
}
return commands;
};
TypeOperations.lineBreakInsert = function (config, model, selections) {
var commands = [];
for (var i = 0, len = selections.length; i < len; i++) {
commands[i] = this._enter(config, model, true, selections[i]);
}
return commands;
};
return TypeOperations;
}());
exports.TypeOperations = TypeOperations;
var TypeWithAutoClosingCommand = /** @class */ (function (_super) {
__extends(TypeWithAutoClosingCommand, _super);
function TypeWithAutoClosingCommand(selection, openCharacter, insertOpenCharacter, closeCharacter) {
var _this = _super.call(this, selection, (insertOpenCharacter ? openCharacter : '') + closeCharacter, 0, -closeCharacter.length) || this;
_this._openCharacter = openCharacter;
_this._closeCharacter = closeCharacter;
_this.closeCharacterRange = null;
_this.enclosingRange = null;
return _this;
}
TypeWithAutoClosingCommand.prototype.computeCursorState = function (model, helper) {
var inverseEditOperations = helper.getInverseEditOperations();
var range = inverseEditOperations[0].range;
this.closeCharacterRange = new range_1.Range(range.startLineNumber, range.endColumn - this._closeCharacter.length, range.endLineNumber, range.endColumn);
this.enclosingRange = new range_1.Range(range.startLineNumber, range.endColumn - this._openCharacter.length - this._closeCharacter.length, range.endLineNumber, range.endColumn);
return _super.prototype.computeCursorState.call(this, model, helper);
};
return TypeWithAutoClosingCommand;
}(replaceCommand_1.ReplaceCommandWithOffsetCursorState));
exports.TypeWithAutoClosingCommand = TypeWithAutoClosingCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[160/*vs/editor/common/controller/cursorWordOperations*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,40/*vs/editor/common/controller/cursorCommon*/,89/*vs/editor/common/controller/wordCharacterClassifier*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, strings, cursorCommon_1, wordCharacterClassifier_1, position_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var WordOperations = /** @class */ (function () {
function WordOperations() {
}
WordOperations._createWord = function (lineContent, wordType, nextCharClass, start, end) {
// console.log('WORD ==> ' + start + ' => ' + end + ':::: <<<' + lineContent.substring(start, end) + '>>>');
return { start: start, end: end, wordType: wordType, nextCharClass: nextCharClass };
};
WordOperations._findPreviousWordOnLine = function (wordSeparators, model, position) {
var lineContent = model.getLineContent(position.lineNumber);
return this._doFindPreviousWordOnLine(lineContent, wordSeparators, position);
};
WordOperations._doFindPreviousWordOnLine = function (lineContent, wordSeparators, position) {
var wordType = 0 /* None */;
for (var chIndex = position.column - 2; chIndex >= 0; chIndex--) {
var chCode = lineContent.charCodeAt(chIndex);
var chClass = wordSeparators.get(chCode);
if (chClass === 0 /* Regular */) {
if (wordType === 2 /* Separator */) {
return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
}
wordType = 1 /* Regular */;
}
else if (chClass === 2 /* WordSeparator */) {
if (wordType === 1 /* Regular */) {
return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
}
wordType = 2 /* Separator */;
}
else if (chClass === 1 /* Whitespace */) {
if (wordType !== 0 /* None */) {
return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
}
}
}
if (wordType !== 0 /* None */) {
return this._createWord(lineContent, wordType, 1 /* Whitespace */, 0, this._findEndOfWord(lineContent, wordSeparators, wordType, 0));
}
return null;
};
WordOperations._findEndOfWord = function (lineContent, wordSeparators, wordType, startIndex) {
var len = lineContent.length;
for (var chIndex = startIndex; chIndex < len; chIndex++) {
var chCode = lineContent.charCodeAt(chIndex);
var chClass = wordSeparators.get(chCode);
if (chClass === 1 /* Whitespace */) {
return chIndex;
}
if (wordType === 1 /* Regular */ && chClass === 2 /* WordSeparator */) {
return chIndex;
}
if (wordType === 2 /* Separator */ && chClass === 0 /* Regular */) {
return chIndex;
}
}
return len;
};
WordOperations._findNextWordOnLine = function (wordSeparators, model, position) {
var lineContent = model.getLineContent(position.lineNumber);
return this._doFindNextWordOnLine(lineContent, wordSeparators, position);
};
WordOperations._doFindNextWordOnLine = function (lineContent, wordSeparators, position) {
var wordType = 0 /* None */;
var len = lineContent.length;
for (var chIndex = position.column - 1; chIndex < len; chIndex++) {
var chCode = lineContent.charCodeAt(chIndex);
var chClass = wordSeparators.get(chCode);
if (chClass === 0 /* Regular */) {
if (wordType === 2 /* Separator */) {
return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
}
wordType = 1 /* Regular */;
}
else if (chClass === 2 /* WordSeparator */) {
if (wordType === 1 /* Regular */) {
return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
}
wordType = 2 /* Separator */;
}
else if (chClass === 1 /* Whitespace */) {
if (wordType !== 0 /* None */) {
return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
}
}
}
if (wordType !== 0 /* None */) {
return this._createWord(lineContent, wordType, 1 /* Whitespace */, this._findStartOfWord(lineContent, wordSeparators, wordType, len - 1), len);
}
return null;
};
WordOperations._findStartOfWord = function (lineContent, wordSeparators, wordType, startIndex) {
for (var chIndex = startIndex; chIndex >= 0; chIndex--) {
var chCode = lineContent.charCodeAt(chIndex);
var chClass = wordSeparators.get(chCode);
if (chClass === 1 /* Whitespace */) {
return chIndex + 1;
}
if (wordType === 1 /* Regular */ && chClass === 2 /* WordSeparator */) {
return chIndex + 1;
}
if (wordType === 2 /* Separator */ && chClass === 0 /* Regular */) {
return chIndex + 1;
}
}
return 0;
};
WordOperations.moveWordLeft = function (wordSeparators, model, position, wordNavigationType) {
var lineNumber = position.lineNumber;
var column = position.column;
var movedToPreviousLine = false;
if (column === 1) {
if (lineNumber > 1) {
movedToPreviousLine = true;
lineNumber = lineNumber - 1;
column = model.getLineMaxColumn(lineNumber);
}
}
var prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, column));
if (wordNavigationType === 0 /* WordStart */) {
if (prevWordOnLine && !movedToPreviousLine) {
// Special case for Visual Studio compatibility:
// when starting in the trim whitespace at the end of a line,
// go to the end of the last word
var lastWhitespaceColumn = model.getLineLastNonWhitespaceColumn(lineNumber);
if (lastWhitespaceColumn < column) {
return new position_1.Position(lineNumber, prevWordOnLine.end + 1);
}
}
return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
}
if (wordNavigationType === 1 /* WordStartFast */) {
if (prevWordOnLine
&& prevWordOnLine.wordType === 2 /* Separator */
&& prevWordOnLine.end - prevWordOnLine.start === 1
&& prevWordOnLine.nextCharClass === 0 /* Regular */) {
// Skip over a word made up of one single separator and followed by a regular character
prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1));
}
return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
}
if (wordNavigationType === 3 /* WordAccessibility */) {
while (prevWordOnLine
&& prevWordOnLine.wordType === 2 /* Separator */) {
// Skip over words made up of only separators
prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1));
}
return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
}
// We are stopping at the ending of words
if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1));
}
return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.end + 1 : 1);
};
WordOperations._moveWordPartLeft = function (model, position) {
var lineNumber = position.lineNumber;
var maxColumn = model.getLineMaxColumn(lineNumber);
if (position.column === 1) {
return (lineNumber > 1 ? new position_1.Position(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)) : position);
}
var lineContent = model.getLineContent(lineNumber);
for (var column = position.column - 1; column > 1; column--) {
var left = lineContent.charCodeAt(column - 2);
var right = lineContent.charCodeAt(column - 1);
if (left !== 95 /* Underline */ && right === 95 /* Underline */) {
// snake_case_variables
return new position_1.Position(lineNumber, column);
}
if (strings.isLowerAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {
// camelCaseVariables
return new position_1.Position(lineNumber, column);
}
if (strings.isUpperAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {
// thisIsACamelCaseWithOneLetterWords
if (column + 1 < maxColumn) {
var rightRight = lineContent.charCodeAt(column);
if (strings.isLowerAsciiLetter(rightRight)) {
return new position_1.Position(lineNumber, column);
}
}
}
}
return new position_1.Position(lineNumber, 1);
};
WordOperations.moveWordRight = function (wordSeparators, model, position, wordNavigationType) {
var lineNumber = position.lineNumber;
var column = position.column;
var movedDown = false;
if (column === model.getLineMaxColumn(lineNumber)) {
if (lineNumber < model.getLineCount()) {
movedDown = true;
lineNumber = lineNumber + 1;
column = 1;
}
}
var nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, column));
if (wordNavigationType === 2 /* WordEnd */) {
if (nextWordOnLine && nextWordOnLine.wordType === 2 /* Separator */) {
if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0 /* Regular */) {
// Skip over a word made up of one single separator and followed by a regular character
nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1));
}
}
if (nextWordOnLine) {
column = nextWordOnLine.end + 1;
}
else {
column = model.getLineMaxColumn(lineNumber);
}
}
else if (wordNavigationType === 3 /* WordAccessibility */) {
if (movedDown) {
// If we move to the next line, pretend that the cursor is right before the first character.
// This is needed when the first word starts right at the first character - and in order not to miss it,
// we need to start before.
column = 0;
}
while (nextWordOnLine
&& (nextWordOnLine.wordType === 2 /* Separator */
|| nextWordOnLine.start + 1 <= column)) {
// Skip over a word made up of one single separator
// Also skip over word if it begins before current cursor position to ascertain we're moving forward at least 1 character.
nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1));
}
if (nextWordOnLine) {
column = nextWordOnLine.start + 1;
}
else {
column = model.getLineMaxColumn(lineNumber);
}
}
else {
if (nextWordOnLine && !movedDown && column >= nextWordOnLine.start + 1) {
nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1));
}
if (nextWordOnLine) {
column = nextWordOnLine.start + 1;
}
else {
column = model.getLineMaxColumn(lineNumber);
}
}
return new position_1.Position(lineNumber, column);
};
WordOperations._moveWordPartRight = function (model, position) {
var lineNumber = position.lineNumber;
var maxColumn = model.getLineMaxColumn(lineNumber);
if (position.column === maxColumn) {
return (lineNumber < model.getLineCount() ? new position_1.Position(lineNumber + 1, 1) : position);
}
var lineContent = model.getLineContent(lineNumber);
for (var column = position.column + 1; column < maxColumn; column++) {
var left = lineContent.charCodeAt(column - 2);
var right = lineContent.charCodeAt(column - 1);
if (left === 95 /* Underline */ && right !== 95 /* Underline */) {
// snake_case_variables
return new position_1.Position(lineNumber, column);
}
if (strings.isLowerAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {
// camelCaseVariables
return new position_1.Position(lineNumber, column);
}
if (strings.isUpperAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {
// thisIsACamelCaseWithOneLetterWords
if (column + 1 < maxColumn) {
var rightRight = lineContent.charCodeAt(column);
if (strings.isLowerAsciiLetter(rightRight)) {
return new position_1.Position(lineNumber, column);
}
}
}
}
return new position_1.Position(lineNumber, maxColumn);
};
WordOperations._deleteWordLeftWhitespace = function (model, position) {
var lineContent = model.getLineContent(position.lineNumber);
var startIndex = position.column - 2;
var lastNonWhitespace = strings.lastNonWhitespaceIndex(lineContent, startIndex);
if (lastNonWhitespace + 1 < startIndex) {
return new range_1.Range(position.lineNumber, lastNonWhitespace + 2, position.lineNumber, position.column);
}
return null;
};
WordOperations.deleteWordLeft = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) {
if (!selection.isEmpty()) {
return selection;
}
var position = new position_1.Position(selection.positionLineNumber, selection.positionColumn);
var lineNumber = position.lineNumber;
var column = position.column;
if (lineNumber === 1 && column === 1) {
// Ignore deleting at beginning of file
return null;
}
if (whitespaceHeuristics) {
var r = this._deleteWordLeftWhitespace(model, position);
if (r) {
return r;
}
}
var prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
if (wordNavigationType === 0 /* WordStart */) {
if (prevWordOnLine) {
column = prevWordOnLine.start + 1;
}
else {
if (column > 1) {
column = 1;
}
else {
lineNumber--;
column = model.getLineMaxColumn(lineNumber);
}
}
}
else {
if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1));
}
if (prevWordOnLine) {
column = prevWordOnLine.end + 1;
}
else {
if (column > 1) {
column = 1;
}
else {
lineNumber--;
column = model.getLineMaxColumn(lineNumber);
}
}
}
return new range_1.Range(lineNumber, column, position.lineNumber, position.column);
};
WordOperations._deleteWordPartLeft = function (model, selection) {
if (!selection.isEmpty()) {
return selection;
}
var pos = selection.getPosition();
var toPosition = WordOperations._moveWordPartLeft(model, pos);
return new range_1.Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
};
WordOperations._findFirstNonWhitespaceChar = function (str, startIndex) {
var len = str.length;
for (var chIndex = startIndex; chIndex < len; chIndex++) {
var ch = str.charAt(chIndex);
if (ch !== ' ' && ch !== '\t') {
return chIndex;
}
}
return len;
};
WordOperations._deleteWordRightWhitespace = function (model, position) {
var lineContent = model.getLineContent(position.lineNumber);
var startIndex = position.column - 1;
var firstNonWhitespace = this._findFirstNonWhitespaceChar(lineContent, startIndex);
if (startIndex + 1 < firstNonWhitespace) {
// bingo
return new range_1.Range(position.lineNumber, position.column, position.lineNumber, firstNonWhitespace + 1);
}
return null;
};
WordOperations.deleteWordRight = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) {
if (!selection.isEmpty()) {
return selection;
}
var position = new position_1.Position(selection.positionLineNumber, selection.positionColumn);
var lineNumber = position.lineNumber;
var column = position.column;
var lineCount = model.getLineCount();
var maxColumn = model.getLineMaxColumn(lineNumber);
if (lineNumber === lineCount && column === maxColumn) {
// Ignore deleting at end of file
return null;
}
if (whitespaceHeuristics) {
var r = this._deleteWordRightWhitespace(model, position);
if (r) {
return r;
}
}
var nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, position);
if (wordNavigationType === 2 /* WordEnd */) {
if (nextWordOnLine) {
column = nextWordOnLine.end + 1;
}
else {
if (column < maxColumn || lineNumber === lineCount) {
column = maxColumn;
}
else {
lineNumber++;
nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, 1));
if (nextWordOnLine) {
column = nextWordOnLine.start + 1;
}
else {
column = model.getLineMaxColumn(lineNumber);
}
}
}
}
else {
if (nextWordOnLine && column >= nextWordOnLine.start + 1) {
nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1));
}
if (nextWordOnLine) {
column = nextWordOnLine.start + 1;
}
else {
if (column < maxColumn || lineNumber === lineCount) {
column = maxColumn;
}
else {
lineNumber++;
nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, 1));
if (nextWordOnLine) {
column = nextWordOnLine.start + 1;
}
else {
column = model.getLineMaxColumn(lineNumber);
}
}
}
}
return new range_1.Range(lineNumber, column, position.lineNumber, position.column);
};
WordOperations._deleteWordPartRight = function (model, selection) {
if (!selection.isEmpty()) {
return selection;
}
var pos = selection.getPosition();
var toPosition = WordOperations._moveWordPartRight(model, pos);
return new range_1.Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
};
WordOperations.word = function (config, model, cursor, inSelectionMode, position) {
var wordSeparators = wordCharacterClassifier_1.getMapForWordSeparators(config.wordSeparators);
var prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
var nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position);
if (!inSelectionMode) {
// Entering word selection for the first time
var startColumn_1;
var endColumn_1;
if (prevWord && prevWord.wordType === 1 /* Regular */ && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
// isTouchingPrevWord
startColumn_1 = prevWord.start + 1;
endColumn_1 = prevWord.end + 1;
}
else if (nextWord && nextWord.wordType === 1 /* Regular */ && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end) {
// isTouchingNextWord
startColumn_1 = nextWord.start + 1;
endColumn_1 = nextWord.end + 1;
}
else {
if (prevWord) {
startColumn_1 = prevWord.end + 1;
}
else {
startColumn_1 = 1;
}
if (nextWord) {
endColumn_1 = nextWord.start + 1;
}
else {
endColumn_1 = model.getLineMaxColumn(position.lineNumber);
}
}
return new cursorCommon_1.SingleCursorState(new range_1.Range(position.lineNumber, startColumn_1, position.lineNumber, endColumn_1), 0, new position_1.Position(position.lineNumber, endColumn_1), 0);
}
var startColumn;
var endColumn;
if (prevWord && prevWord.wordType === 1 /* Regular */ && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end) {
// isInsidePrevWord
startColumn = prevWord.start + 1;
endColumn = prevWord.end + 1;
}
else if (nextWord && nextWord.wordType === 1 /* Regular */ && nextWord.start < position.column - 1 && position.column - 1 < nextWord.end) {
// isInsideNextWord
startColumn = nextWord.start + 1;
endColumn = nextWord.end + 1;
}
else {
startColumn = position.column;
endColumn = position.column;
}
var lineNumber = position.lineNumber;
var column;
if (cursor.selectionStart.containsPosition(position)) {
column = cursor.selectionStart.endColumn;
}
else if (position.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) {
column = startColumn;
var possiblePosition = new position_1.Position(lineNumber, column);
if (cursor.selectionStart.containsPosition(possiblePosition)) {
column = cursor.selectionStart.endColumn;
}
}
else {
column = endColumn;
var possiblePosition = new position_1.Position(lineNumber, column);
if (cursor.selectionStart.containsPosition(possiblePosition)) {
column = cursor.selectionStart.startColumn;
}
}
return cursor.move(true, lineNumber, column, 0);
};
return WordOperations;
}());
exports.WordOperations = WordOperations;
var WordPartOperations = /** @class */ (function (_super) {
__extends(WordPartOperations, _super);
function WordPartOperations() {
return _super !== null && _super.apply(this, arguments) || this;
}
WordPartOperations.deleteWordPartLeft = function (wordSeparators, model, selection, whitespaceHeuristics) {
var candidates = enforceDefined([
WordOperations.deleteWordLeft(wordSeparators, model, selection, whitespaceHeuristics, 0 /* WordStart */),
WordOperations.deleteWordLeft(wordSeparators, model, selection, whitespaceHeuristics, 2 /* WordEnd */),
WordOperations._deleteWordPartLeft(model, selection)
]);
candidates.sort(range_1.Range.compareRangesUsingEnds);
return candidates[2];
};
WordPartOperations.deleteWordPartRight = function (wordSeparators, model, selection, whitespaceHeuristics) {
var candidates = enforceDefined([
WordOperations.deleteWordRight(wordSeparators, model, selection, whitespaceHeuristics, 0 /* WordStart */),
WordOperations.deleteWordRight(wordSeparators, model, selection, whitespaceHeuristics, 2 /* WordEnd */),
WordOperations._deleteWordPartRight(model, selection)
]);
candidates.sort(range_1.Range.compareRangesUsingStarts);
return candidates[0];
};
WordPartOperations.moveWordPartLeft = function (wordSeparators, model, position) {
var candidates = enforceDefined([
WordOperations.moveWordLeft(wordSeparators, model, position, 0 /* WordStart */),
WordOperations.moveWordLeft(wordSeparators, model, position, 2 /* WordEnd */),
WordOperations._moveWordPartLeft(model, position)
]);
candidates.sort(position_1.Position.compare);
return candidates[2];
};
WordPartOperations.moveWordPartRight = function (wordSeparators, model, position) {
var candidates = enforceDefined([
WordOperations.moveWordRight(wordSeparators, model, position, 0 /* WordStart */),
WordOperations.moveWordRight(wordSeparators, model, position, 2 /* WordEnd */),
WordOperations._moveWordPartRight(model, position)
]);
candidates.sort(position_1.Position.compare);
return candidates[0];
};
return WordPartOperations;
}(WordOperations));
exports.WordPartOperations = WordPartOperations;
function enforceDefined(arr) {
return arr.filter(function (el) { return Boolean(el); });
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[213/*vs/editor/common/controller/cursorMoveCommands*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/,40/*vs/editor/common/controller/cursorCommon*/,158/*vs/editor/common/controller/cursorMoveOperations*/,160/*vs/editor/common/controller/cursorWordOperations*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/]), function (require, exports, types, cursorCommon_1, cursorMoveOperations_1, cursorWordOperations_1, position_1, range_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CursorMoveCommands = /** @class */ (function () {
function CursorMoveCommands() {
}
CursorMoveCommands.addCursorDown = function (context, cursors, useLogicalLine) {
var result = [], resultLen = 0;
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[resultLen++] = new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState);
if (useLogicalLine) {
result[resultLen++] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.translateDown(context.config, context.model, cursor.modelState));
}
else {
result[resultLen++] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.translateDown(context.config, context.viewModel, cursor.viewState));
}
}
return result;
};
CursorMoveCommands.addCursorUp = function (context, cursors, useLogicalLine) {
var result = [], resultLen = 0;
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[resultLen++] = new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState);
if (useLogicalLine) {
result[resultLen++] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.translateUp(context.config, context.model, cursor.modelState));
}
else {
result[resultLen++] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.translateUp(context.config, context.viewModel, cursor.viewState));
}
}
return result;
};
CursorMoveCommands.moveToBeginningOfLine = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[i] = this._moveToLineStart(context, cursor, inSelectionMode);
}
return result;
};
CursorMoveCommands._moveToLineStart = function (context, cursor, inSelectionMode) {
var currentViewStateColumn = cursor.viewState.position.column;
var currentModelStateColumn = cursor.modelState.position.column;
var isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn;
var currentViewStatelineNumber = cursor.viewState.position.lineNumber;
var firstNonBlankColumn = context.viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber);
var isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn;
if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) {
return this._moveToLineStartByView(context, cursor, inSelectionMode);
}
else {
return this._moveToLineStartByModel(context, cursor, inSelectionMode);
}
};
CursorMoveCommands._moveToLineStartByView = function (context, cursor, inSelectionMode) {
return cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode));
};
CursorMoveCommands._moveToLineStartByModel = function (context, cursor, inSelectionMode) {
return cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfLine(context.config, context.model, cursor.modelState, inSelectionMode));
};
CursorMoveCommands.moveToEndOfLine = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[i] = this._moveToLineEnd(context, cursor, inSelectionMode);
}
return result;
};
CursorMoveCommands._moveToLineEnd = function (context, cursor, inSelectionMode) {
var viewStatePosition = cursor.viewState.position;
var viewModelMaxColumn = context.viewModel.getLineMaxColumn(viewStatePosition.lineNumber);
var isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn;
var modelStatePosition = cursor.modelState.position;
var modelMaxColumn = context.model.getLineMaxColumn(modelStatePosition.lineNumber);
var isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column;
if (isEndOfViewLine || isEndLineOfWrappedLine) {
return this._moveToLineEndByModel(context, cursor, inSelectionMode);
}
else {
return this._moveToLineEndByView(context, cursor, inSelectionMode);
}
};
CursorMoveCommands._moveToLineEndByView = function (context, cursor, inSelectionMode) {
return cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToEndOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode));
};
CursorMoveCommands._moveToLineEndByModel = function (context, cursor, inSelectionMode) {
return cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToEndOfLine(context.config, context.model, cursor.modelState, inSelectionMode));
};
CursorMoveCommands.expandLineSelection = function (context, cursors) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var startLineNumber = cursor.modelState.selection.startLineNumber;
var lineCount = context.model.getLineCount();
var endLineNumber = cursor.modelState.selection.endLineNumber;
var endColumn = void 0;
if (endLineNumber === lineCount) {
endColumn = context.model.getLineMaxColumn(lineCount);
}
else {
endLineNumber++;
endColumn = 1;
}
result[i] = cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(startLineNumber, 1, startLineNumber, 1), 0, new position_1.Position(endLineNumber, endColumn), 0));
}
return result;
};
CursorMoveCommands.moveToBeginningOfBuffer = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode));
}
return result;
};
CursorMoveCommands.moveToEndOfBuffer = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToEndOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode));
}
return result;
};
CursorMoveCommands.selectAll = function (context, cursor) {
var lineCount = context.model.getLineCount();
var maxColumn = context.model.getLineMaxColumn(lineCount);
return cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 0, new position_1.Position(lineCount, maxColumn), 0));
};
CursorMoveCommands.line = function (context, cursor, inSelectionMode, _position, _viewPosition) {
var position = context.model.validatePosition(_position);
var viewPosition = (_viewPosition
? context.validateViewPosition(new position_1.Position(_viewPosition.lineNumber, _viewPosition.column), position)
: context.convertModelPositionToViewPosition(position));
if (!inSelectionMode || !cursor.modelState.hasSelection()) {
// Entering line selection for the first time
var lineCount = context.model.getLineCount();
var selectToLineNumber = position.lineNumber + 1;
var selectToColumn = 1;
if (selectToLineNumber > lineCount) {
selectToLineNumber = lineCount;
selectToColumn = context.model.getLineMaxColumn(selectToLineNumber);
}
return cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(position.lineNumber, 1, selectToLineNumber, selectToColumn), 0, new position_1.Position(selectToLineNumber, selectToColumn), 0));
}
// Continuing line selection
var enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber;
if (position.lineNumber < enteringLineNumber) {
return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), viewPosition.lineNumber, 1, 0));
}
else if (position.lineNumber > enteringLineNumber) {
var lineCount = context.viewModel.getLineCount();
var selectToViewLineNumber = viewPosition.lineNumber + 1;
var selectToViewColumn = 1;
if (selectToViewLineNumber > lineCount) {
selectToViewLineNumber = lineCount;
selectToViewColumn = context.viewModel.getLineMaxColumn(selectToViewLineNumber);
}
return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), selectToViewLineNumber, selectToViewColumn, 0));
}
else {
var endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition();
return cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(cursor.modelState.hasSelection(), endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0));
}
};
CursorMoveCommands.word = function (context, cursor, inSelectionMode, _position) {
var position = context.model.validatePosition(_position);
return cursorCommon_1.CursorState.fromModelState(cursorWordOperations_1.WordOperations.word(context.config, context.model, cursor.modelState, inSelectionMode, position));
};
CursorMoveCommands.cancelSelection = function (context, cursor) {
if (!cursor.modelState.hasSelection()) {
return new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState);
}
var lineNumber = cursor.viewState.position.lineNumber;
var column = cursor.viewState.position.column;
return cursorCommon_1.CursorState.fromViewState(new cursorCommon_1.SingleCursorState(new range_1.Range(lineNumber, column, lineNumber, column), 0, new position_1.Position(lineNumber, column), 0));
};
CursorMoveCommands.moveTo = function (context, cursor, inSelectionMode, _position, _viewPosition) {
var position = context.model.validatePosition(_position);
var viewPosition = (_viewPosition
? context.validateViewPosition(new position_1.Position(_viewPosition.lineNumber, _viewPosition.column), position)
: context.convertModelPositionToViewPosition(position));
return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0));
};
CursorMoveCommands.move = function (context, cursors, args) {
var inSelectionMode = args.select;
var value = args.value;
switch (args.direction) {
case 0 /* Left */: {
if (args.unit === 4 /* HalfLine */) {
// Move left by half the current line length
return this._moveHalfLineLeft(context, cursors, inSelectionMode);
}
else {
// Move left by `moveParams.value` columns
return this._moveLeft(context, cursors, inSelectionMode, value);
}
}
case 1 /* Right */: {
if (args.unit === 4 /* HalfLine */) {
// Move right by half the current line length
return this._moveHalfLineRight(context, cursors, inSelectionMode);
}
else {
// Move right by `moveParams.value` columns
return this._moveRight(context, cursors, inSelectionMode, value);
}
}
case 2 /* Up */: {
if (args.unit === 2 /* WrappedLine */) {
// Move up by view lines
return this._moveUpByViewLines(context, cursors, inSelectionMode, value);
}
else {
// Move up by model lines
return this._moveUpByModelLines(context, cursors, inSelectionMode, value);
}
}
case 3 /* Down */: {
if (args.unit === 2 /* WrappedLine */) {
// Move down by view lines
return this._moveDownByViewLines(context, cursors, inSelectionMode, value);
}
else {
// Move down by model lines
return this._moveDownByModelLines(context, cursors, inSelectionMode, value);
}
}
case 4 /* WrappedLineStart */: {
// Move to the beginning of the current view line
return this._moveToViewMinColumn(context, cursors, inSelectionMode);
}
case 5 /* WrappedLineFirstNonWhitespaceCharacter */: {
// Move to the first non-whitespace column of the current view line
return this._moveToViewFirstNonWhitespaceColumn(context, cursors, inSelectionMode);
}
case 6 /* WrappedLineColumnCenter */: {
// Move to the "center" of the current view line
return this._moveToViewCenterColumn(context, cursors, inSelectionMode);
}
case 7 /* WrappedLineEnd */: {
// Move to the end of the current view line
return this._moveToViewMaxColumn(context, cursors, inSelectionMode);
}
case 8 /* WrappedLineLastNonWhitespaceCharacter */: {
// Move to the last non-whitespace column of the current view line
return this._moveToViewLastNonWhitespaceColumn(context, cursors, inSelectionMode);
}
case 9 /* ViewPortTop */: {
// Move to the nth line start in the viewport (from the top)
var cursor = cursors[0];
var visibleModelRange = context.getCompletelyVisibleModelRange();
var modelLineNumber = this._firstLineNumberInRange(context.model, visibleModelRange, value);
var modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)];
}
case 11 /* ViewPortBottom */: {
// Move to the nth line start in the viewport (from the bottom)
var cursor = cursors[0];
var visibleModelRange = context.getCompletelyVisibleModelRange();
var modelLineNumber = this._lastLineNumberInRange(context.model, visibleModelRange, value);
var modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)];
}
case 10 /* ViewPortCenter */: {
// Move to the line start in the viewport center
var cursor = cursors[0];
var visibleModelRange = context.getCompletelyVisibleModelRange();
var modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2);
var modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)];
}
case 12 /* ViewPortIfOutside */: {
// Move to a position inside the viewport
var visibleViewRange = context.getCompletelyVisibleViewRange();
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[i] = this.findPositionInViewportIfOutside(context, cursor, visibleViewRange, inSelectionMode);
}
return result;
}
}
return null;
};
CursorMoveCommands.findPositionInViewportIfOutside = function (context, cursor, visibleViewRange, inSelectionMode) {
var viewLineNumber = cursor.viewState.position.lineNumber;
if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) {
// Nothing to do, cursor is in viewport
return new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState);
}
else {
if (viewLineNumber > visibleViewRange.endLineNumber - 1) {
viewLineNumber = visibleViewRange.endLineNumber - 1;
}
if (viewLineNumber < visibleViewRange.startLineNumber) {
viewLineNumber = visibleViewRange.startLineNumber;
}
var viewColumn = context.viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);
return this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);
}
};
/**
* Find the nth line start included in the range (from the start).
*/
CursorMoveCommands._firstLineNumberInRange = function (model, range, count) {
var startLineNumber = range.startLineNumber;
if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {
// Move on to the second line if the first line start is not included in the range
startLineNumber++;
}
return Math.min(range.endLineNumber, startLineNumber + count - 1);
};
/**
* Find the nth line start included in the range (from the end).
*/
CursorMoveCommands._lastLineNumberInRange = function (model, range, count) {
var startLineNumber = range.startLineNumber;
if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {
// Move on to the second line if the first line start is not included in the range
startLineNumber++;
}
return Math.max(startLineNumber, range.endLineNumber - count + 1);
};
CursorMoveCommands._moveLeft = function (context, cursors, inSelectionMode, noOfColumns) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var newViewState = cursorMoveOperations_1.MoveOperations.moveLeft(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns);
if (noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) {
// moved over to the previous view line
var newViewModelPosition = context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position);
if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) {
// stayed on the same model line => pass wrapping point where 2 view positions map to a single model position
newViewState = cursorMoveOperations_1.MoveOperations.moveLeft(context.config, context.viewModel, newViewState, inSelectionMode, 1);
}
}
result[i] = cursorCommon_1.CursorState.fromViewState(newViewState);
}
return result;
};
CursorMoveCommands._moveHalfLineLeft = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var viewLineNumber = cursor.viewState.position.lineNumber;
var halfLine = Math.round(context.viewModel.getLineContent(viewLineNumber).length / 2);
result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveLeft(context.config, context.viewModel, cursor.viewState, inSelectionMode, halfLine));
}
return result;
};
CursorMoveCommands._moveRight = function (context, cursors, inSelectionMode, noOfColumns) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var newViewState = cursorMoveOperations_1.MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns);
if (noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) {
// moved over to the next view line
var newViewModelPosition = context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position);
if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) {
// stayed on the same model line => pass wrapping point where 2 view positions map to a single model position
newViewState = cursorMoveOperations_1.MoveOperations.moveRight(context.config, context.viewModel, newViewState, inSelectionMode, 1);
}
}
result[i] = cursorCommon_1.CursorState.fromViewState(newViewState);
}
return result;
};
CursorMoveCommands._moveHalfLineRight = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var viewLineNumber = cursor.viewState.position.lineNumber;
var halfLine = Math.round(context.viewModel.getLineContent(viewLineNumber).length / 2);
result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, halfLine));
}
return result;
};
CursorMoveCommands._moveDownByViewLines = function (context, cursors, inSelectionMode, linesCount) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveDown(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount));
}
return result;
};
CursorMoveCommands._moveDownByModelLines = function (context, cursors, inSelectionMode, linesCount) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveDown(context.config, context.model, cursor.modelState, inSelectionMode, linesCount));
}
return result;
};
CursorMoveCommands._moveUpByViewLines = function (context, cursors, inSelectionMode, linesCount) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveUp(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount));
}
return result;
};
CursorMoveCommands._moveUpByModelLines = function (context, cursors, inSelectionMode, linesCount) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveUp(context.config, context.model, cursor.modelState, inSelectionMode, linesCount));
}
return result;
};
CursorMoveCommands._moveToViewPosition = function (context, cursor, inSelectionMode, toViewLineNumber, toViewColumn) {
return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0));
};
CursorMoveCommands._moveToModelPosition = function (context, cursor, inSelectionMode, toModelLineNumber, toModelColumn) {
return cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0));
};
CursorMoveCommands._moveToViewMinColumn = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var viewLineNumber = cursor.viewState.position.lineNumber;
var viewColumn = context.viewModel.getLineMinColumn(viewLineNumber);
result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);
}
return result;
};
CursorMoveCommands._moveToViewFirstNonWhitespaceColumn = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var viewLineNumber = cursor.viewState.position.lineNumber;
var viewColumn = context.viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);
result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);
}
return result;
};
CursorMoveCommands._moveToViewCenterColumn = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var viewLineNumber = cursor.viewState.position.lineNumber;
var viewColumn = Math.round((context.viewModel.getLineMaxColumn(viewLineNumber) + context.viewModel.getLineMinColumn(viewLineNumber)) / 2);
result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);
}
return result;
};
CursorMoveCommands._moveToViewMaxColumn = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var viewLineNumber = cursor.viewState.position.lineNumber;
var viewColumn = context.viewModel.getLineMaxColumn(viewLineNumber);
result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);
}
return result;
};
CursorMoveCommands._moveToViewLastNonWhitespaceColumn = function (context, cursors, inSelectionMode) {
var result = [];
for (var i = 0, len = cursors.length; i < len; i++) {
var cursor = cursors[i];
var viewLineNumber = cursor.viewState.position.lineNumber;
var viewColumn = context.viewModel.getLineLastNonWhitespaceColumn(viewLineNumber);
result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);
}
return result;
};
return CursorMoveCommands;
}());
exports.CursorMoveCommands = CursorMoveCommands;
var CursorMove;
(function (CursorMove) {
var isCursorMoveArgs = function (arg) {
if (!types.isObject(arg)) {
return false;
}
var cursorMoveArg = arg;
if (!types.isString(cursorMoveArg.to)) {
return false;
}
if (!types.isUndefined(cursorMoveArg.select) && !types.isBoolean(cursorMoveArg.select)) {
return false;
}
if (!types.isUndefined(cursorMoveArg.by) && !types.isString(cursorMoveArg.by)) {
return false;
}
if (!types.isUndefined(cursorMoveArg.value) && !types.isNumber(cursorMoveArg.value)) {
return false;
}
return true;
};
CursorMove.description = {
description: 'Move cursor to a logical position in the view',
args: [
{
name: 'Cursor move argument object',
description: "Property-value pairs that can be passed through this argument:\n\t\t\t\t\t* 'to': A mandatory logical position value providing where to move the cursor.\n\t\t\t\t\t\t```\n\t\t\t\t\t\t'left', 'right', 'up', 'down'\n\t\t\t\t\t\t'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter'\n\t\t\t\t\t\t'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter'\n\t\t\t\t\t\t'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside'\n\t\t\t\t\t\t```\n\t\t\t\t\t* 'by': Unit to move. Default is computed based on 'to' value.\n\t\t\t\t\t\t```\n\t\t\t\t\t\t'line', 'wrappedLine', 'character', 'halfLine'\n\t\t\t\t\t\t```\n\t\t\t\t\t* 'value': Number of units to move. Default is '1'.\n\t\t\t\t\t* 'select': If 'true' makes the selection. Default is 'false'.\n\t\t\t\t",
constraint: isCursorMoveArgs,
schema: {
'type': 'object',
'required': ['to'],
'properties': {
'to': {
'type': 'string',
'enum': ['left', 'right', 'up', 'down', 'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter', 'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter', 'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside']
},
'by': {
'type': 'string',
'enum': ['line', 'wrappedLine', 'character', 'halfLine']
},
'value': {
'type': 'number',
'default': 1
},
'select': {
'type': 'boolean',
'default': false
}
}
}
}
]
};
/**
* Positions in the view for cursor move command.
*/
CursorMove.RawDirection = {
Left: 'left',
Right: 'right',
Up: 'up',
Down: 'down',
WrappedLineStart: 'wrappedLineStart',
WrappedLineFirstNonWhitespaceCharacter: 'wrappedLineFirstNonWhitespaceCharacter',
WrappedLineColumnCenter: 'wrappedLineColumnCenter',
WrappedLineEnd: 'wrappedLineEnd',
WrappedLineLastNonWhitespaceCharacter: 'wrappedLineLastNonWhitespaceCharacter',
ViewPortTop: 'viewPortTop',
ViewPortCenter: 'viewPortCenter',
ViewPortBottom: 'viewPortBottom',
ViewPortIfOutside: 'viewPortIfOutside'
};
/**
* Units for Cursor move 'by' argument
*/
CursorMove.RawUnit = {
Line: 'line',
WrappedLine: 'wrappedLine',
Character: 'character',
HalfLine: 'halfLine'
};
function parse(args) {
if (!args.to) {
// illegal arguments
return null;
}
var direction;
switch (args.to) {
case CursorMove.RawDirection.Left:
direction = 0 /* Left */;
break;
case CursorMove.RawDirection.Right:
direction = 1 /* Right */;
break;
case CursorMove.RawDirection.Up:
direction = 2 /* Up */;
break;
case CursorMove.RawDirection.Down:
direction = 3 /* Down */;
break;
case CursorMove.RawDirection.WrappedLineStart:
direction = 4 /* WrappedLineStart */;
break;
case CursorMove.RawDirection.WrappedLineFirstNonWhitespaceCharacter:
direction = 5 /* WrappedLineFirstNonWhitespaceCharacter */;
break;
case CursorMove.RawDirection.WrappedLineColumnCenter:
direction = 6 /* WrappedLineColumnCenter */;
break;
case CursorMove.RawDirection.WrappedLineEnd:
direction = 7 /* WrappedLineEnd */;
break;
case CursorMove.RawDirection.WrappedLineLastNonWhitespaceCharacter:
direction = 8 /* WrappedLineLastNonWhitespaceCharacter */;
break;
case CursorMove.RawDirection.ViewPortTop:
direction = 9 /* ViewPortTop */;
break;
case CursorMove.RawDirection.ViewPortBottom:
direction = 11 /* ViewPortBottom */;
break;
case CursorMove.RawDirection.ViewPortCenter:
direction = 10 /* ViewPortCenter */;
break;
case CursorMove.RawDirection.ViewPortIfOutside:
direction = 12 /* ViewPortIfOutside */;
break;
default:
// illegal arguments
return null;
}
var unit = 0 /* None */;
switch (args.by) {
case CursorMove.RawUnit.Line:
unit = 1 /* Line */;
break;
case CursorMove.RawUnit.WrappedLine:
unit = 2 /* WrappedLine */;
break;
case CursorMove.RawUnit.Character:
unit = 3 /* Character */;
break;
case CursorMove.RawUnit.HalfLine:
unit = 4 /* HalfLine */;
break;
}
return {
direction: direction,
unit: unit,
select: (!!args.select),
value: (args.value || 1)
};
}
CursorMove.parse = parse;
})(CursorMove = exports.CursorMove || (exports.CursorMove = {}));
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[484/*vs/editor/common/controller/oneCursor*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/]), function (require, exports, cursorCommon_1, position_1, range_1, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var OneCursor = /** @class */ (function () {
function OneCursor(context) {
this._selTrackedRange = null;
this._trackSelection = true;
this._setState(context, new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 0, new position_1.Position(1, 1), 0), new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 0, new position_1.Position(1, 1), 0));
}
OneCursor.prototype.dispose = function (context) {
this._removeTrackedRange(context);
};
OneCursor.prototype.startTrackingSelection = function (context) {
this._trackSelection = true;
this._updateTrackedRange(context);
};
OneCursor.prototype.stopTrackingSelection = function (context) {
this._trackSelection = false;
this._removeTrackedRange(context);
};
OneCursor.prototype._updateTrackedRange = function (context) {
if (!this._trackSelection) {
// don't track the selection
return;
}
this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, this.modelState.selection, 0 /* AlwaysGrowsWhenTypingAtEdges */);
};
OneCursor.prototype._removeTrackedRange = function (context) {
this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, null, 0 /* AlwaysGrowsWhenTypingAtEdges */);
};
OneCursor.prototype.asCursorState = function () {
return new cursorCommon_1.CursorState(this.modelState, this.viewState);
};
OneCursor.prototype.readSelectionFromMarkers = function (context) {
var range = context.model._getTrackedRange(this._selTrackedRange);
if (this.modelState.selection.getDirection() === 0 /* LTR */) {
return new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
}
return new selection_1.Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn);
};
OneCursor.prototype.ensureValidState = function (context) {
this._setState(context, this.modelState, this.viewState);
};
OneCursor.prototype.setState = function (context, modelState, viewState) {
this._setState(context, modelState, viewState);
};
OneCursor.prototype._setState = function (context, modelState, viewState) {
if (!modelState) {
if (!viewState) {
return;
}
// We only have the view state => compute the model state
var selectionStart = context.model.validateRange(context.convertViewRangeToModelRange(viewState.selectionStart));
var position = context.model.validatePosition(context.convertViewPositionToModelPosition(viewState.position.lineNumber, viewState.position.column));
modelState = new cursorCommon_1.SingleCursorState(selectionStart, viewState.selectionStartLeftoverVisibleColumns, position, viewState.leftoverVisibleColumns);
}
else {
// Validate new model state
var selectionStart = context.model.validateRange(modelState.selectionStart);
var selectionStartLeftoverVisibleColumns = modelState.selectionStart.equalsRange(selectionStart) ? modelState.selectionStartLeftoverVisibleColumns : 0;
var position = context.model.validatePosition(modelState.position);
var leftoverVisibleColumns = modelState.position.equals(position) ? modelState.leftoverVisibleColumns : 0;
modelState = new cursorCommon_1.SingleCursorState(selectionStart, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns);
}
if (!viewState) {
// We only have the model state => compute the view state
var viewSelectionStart1 = context.convertModelPositionToViewPosition(new position_1.Position(modelState.selectionStart.startLineNumber, modelState.selectionStart.startColumn));
var viewSelectionStart2 = context.convertModelPositionToViewPosition(new position_1.Position(modelState.selectionStart.endLineNumber, modelState.selectionStart.endColumn));
var viewSelectionStart = new range_1.Range(viewSelectionStart1.lineNumber, viewSelectionStart1.column, viewSelectionStart2.lineNumber, viewSelectionStart2.column);
var viewPosition = context.convertModelPositionToViewPosition(modelState.position);
viewState = new cursorCommon_1.SingleCursorState(viewSelectionStart, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
}
else {
// Validate new view state
var viewSelectionStart = context.validateViewRange(viewState.selectionStart, modelState.selectionStart);
var viewPosition = context.validateViewPosition(viewState.position, modelState.position);
viewState = new cursorCommon_1.SingleCursorState(viewSelectionStart, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
}
this.modelState = modelState;
this.viewState = viewState;
this._updateTrackedRange(context);
};
return OneCursor;
}());
exports.OneCursor = OneCursor;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[485/*vs/editor/common/controller/cursorCollection*/], __M([0/*require*/,1/*exports*/,40/*vs/editor/common/controller/cursorCommon*/,484/*vs/editor/common/controller/oneCursor*/,22/*vs/editor/common/core/selection*/]), function (require, exports, cursorCommon_1, oneCursor_1, selection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CursorCollection = /** @class */ (function () {
function CursorCollection(context) {
this.context = context;
this.primaryCursor = new oneCursor_1.OneCursor(context);
this.secondaryCursors = [];
this.lastAddedCursorIndex = 0;
}
CursorCollection.prototype.dispose = function () {
this.primaryCursor.dispose(this.context);
this.killSecondaryCursors();
};
CursorCollection.prototype.startTrackingSelections = function () {
this.primaryCursor.startTrackingSelection(this.context);
for (var i = 0, len = this.secondaryCursors.length; i < len; i++) {
this.secondaryCursors[i].startTrackingSelection(this.context);
}
};
CursorCollection.prototype.stopTrackingSelections = function () {
this.primaryCursor.stopTrackingSelection(this.context);
for (var i = 0, len = this.secondaryCursors.length; i < len; i++) {
this.secondaryCursors[i].stopTrackingSelection(this.context);
}
};
CursorCollection.prototype.updateContext = function (context) {
this.context = context;
};
CursorCollection.prototype.ensureValidState = function () {
this.primaryCursor.ensureValidState(this.context);
for (var i = 0, len = this.secondaryCursors.length; i < len; i++) {
this.secondaryCursors[i].ensureValidState(this.context);
}
};
CursorCollection.prototype.readSelectionFromMarkers = function () {
var result = [];
result[0] = this.primaryCursor.readSelectionFromMarkers(this.context);
for (var i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].readSelectionFromMarkers(this.context);
}
return result;
};
CursorCollection.prototype.getAll = function () {
var result = [];
result[0] = this.primaryCursor.asCursorState();
for (var i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].asCursorState();
}
return result;
};
CursorCollection.prototype.getViewPositions = function () {
var result = [];
result[0] = this.primaryCursor.viewState.position;
for (var i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].viewState.position;
}
return result;
};
CursorCollection.prototype.getSelections = function () {
var result = [];
result[0] = this.primaryCursor.modelState.selection;
for (var i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].modelState.selection;
}
return result;
};
CursorCollection.prototype.getViewSelections = function () {
var result = [];
result[0] = this.primaryCursor.viewState.selection;
for (var i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i].viewState.selection;
}
return result;
};
CursorCollection.prototype.setSelections = function (selections) {
this.setStates(cursorCommon_1.CursorState.fromModelSelections(selections));
};
CursorCollection.prototype.getPrimaryCursor = function () {
return this.primaryCursor.asCursorState();
};
CursorCollection.prototype.setStates = function (states) {
if (states === null) {
return;
}
this.primaryCursor.setState(this.context, states[0].modelState, states[0].viewState);
this._setSecondaryStates(states.slice(1));
};
/**
* Creates or disposes secondary cursors as necessary to match the number of `secondarySelections`.
*/
CursorCollection.prototype._setSecondaryStates = function (secondaryStates) {
var secondaryCursorsLength = this.secondaryCursors.length;
var secondaryStatesLength = secondaryStates.length;
if (secondaryCursorsLength < secondaryStatesLength) {
var createCnt = secondaryStatesLength - secondaryCursorsLength;
for (var i = 0; i < createCnt; i++) {
this._addSecondaryCursor();
}
}
else if (secondaryCursorsLength > secondaryStatesLength) {
var removeCnt = secondaryCursorsLength - secondaryStatesLength;
for (var i = 0; i < removeCnt; i++) {
this._removeSecondaryCursor(this.secondaryCursors.length - 1);
}
}
for (var i = 0; i < secondaryStatesLength; i++) {
this.secondaryCursors[i].setState(this.context, secondaryStates[i].modelState, secondaryStates[i].viewState);
}
};
CursorCollection.prototype.killSecondaryCursors = function () {
this._setSecondaryStates([]);
};
CursorCollection.prototype._addSecondaryCursor = function () {
this.secondaryCursors.push(new oneCursor_1.OneCursor(this.context));
this.lastAddedCursorIndex = this.secondaryCursors.length;
};
CursorCollection.prototype.getLastAddedCursorIndex = function () {
if (this.secondaryCursors.length === 0 || this.lastAddedCursorIndex === 0) {
return 0;
}
return this.lastAddedCursorIndex;
};
CursorCollection.prototype._removeSecondaryCursor = function (removeIndex) {
if (this.lastAddedCursorIndex >= removeIndex + 1) {
this.lastAddedCursorIndex--;
}
this.secondaryCursors[removeIndex].dispose(this.context);
this.secondaryCursors.splice(removeIndex, 1);
};
CursorCollection.prototype._getAll = function () {
var result = [];
result[0] = this.primaryCursor;
for (var i = 0, len = this.secondaryCursors.length; i < len; i++) {
result[i + 1] = this.secondaryCursors[i];
}
return result;
};
CursorCollection.prototype.normalize = function () {
if (this.secondaryCursors.length === 0) {
return;
}
var cursors = this._getAll();
var sortedCursors = [];
for (var i = 0, len = cursors.length; i < len; i++) {
sortedCursors.push({
index: i,
selection: cursors[i].modelState.selection,
});
}
sortedCursors.sort(function (a, b) {
if (a.selection.startLineNumber === b.selection.startLineNumber) {
return a.selection.startColumn - b.selection.startColumn;
}
return a.selection.startLineNumber - b.selection.startLineNumber;
});
for (var sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) {
var current = sortedCursors[sortedCursorIndex];
var next = sortedCursors[sortedCursorIndex + 1];
var currentSelection = current.selection;
var nextSelection = next.selection;
if (!this.context.config.multiCursorMergeOverlapping) {
continue;
}
var shouldMergeCursors = void 0;
if (nextSelection.isEmpty() || currentSelection.isEmpty()) {
// Merge touching cursors if one of them is collapsed
shouldMergeCursors = nextSelection.getStartPosition().isBeforeOrEqual(currentSelection.getEndPosition());
}
else {
// Merge only overlapping cursors (i.e. allow touching ranges)
shouldMergeCursors = nextSelection.getStartPosition().isBefore(currentSelection.getEndPosition());
}
if (shouldMergeCursors) {
var winnerSortedCursorIndex = current.index < next.index ? sortedCursorIndex : sortedCursorIndex + 1;
var looserSortedCursorIndex = current.index < next.index ? sortedCursorIndex + 1 : sortedCursorIndex;
var looserIndex = sortedCursors[looserSortedCursorIndex].index;
var winnerIndex = sortedCursors[winnerSortedCursorIndex].index;
var looserSelection = sortedCursors[looserSortedCursorIndex].selection;
var winnerSelection = sortedCursors[winnerSortedCursorIndex].selection;
if (!looserSelection.equalsSelection(winnerSelection)) {
var resultingRange = looserSelection.plusRange(winnerSelection);
var looserSelectionIsLTR = (looserSelection.selectionStartLineNumber === looserSelection.startLineNumber && looserSelection.selectionStartColumn === looserSelection.startColumn);
var winnerSelectionIsLTR = (winnerSelection.selectionStartLineNumber === winnerSelection.startLineNumber && winnerSelection.selectionStartColumn === winnerSelection.startColumn);
// Give more importance to the last added cursor (think Ctrl-dragging + hitting another cursor)
var resultingSelectionIsLTR = void 0;
if (looserIndex === this.lastAddedCursorIndex) {
resultingSelectionIsLTR = looserSelectionIsLTR;
this.lastAddedCursorIndex = winnerIndex;
}
else {
// Winner takes it all
resultingSelectionIsLTR = winnerSelectionIsLTR;
}
var resultingSelection = void 0;
if (resultingSelectionIsLTR) {
resultingSelection = new selection_1.Selection(resultingRange.startLineNumber, resultingRange.startColumn, resultingRange.endLineNumber, resultingRange.endColumn);
}
else {
resultingSelection = new selection_1.Selection(resultingRange.endLineNumber, resultingRange.endColumn, resultingRange.startLineNumber, resultingRange.startColumn);
}
sortedCursors[winnerSortedCursorIndex].selection = resultingSelection;
var resultingState = cursorCommon_1.CursorState.fromModelSelection(resultingSelection);
cursors[winnerIndex].setState(this.context, resultingState.modelState, resultingState.viewState);
}
for (var _i = 0, sortedCursors_1 = sortedCursors; _i < sortedCursors_1.length; _i++) {
var sortedCursor = sortedCursors_1[_i];
if (sortedCursor.index > looserIndex) {
sortedCursor.index--;
}
}
cursors.splice(looserIndex, 1);
sortedCursors.splice(looserSortedCursorIndex, 1);
this._removeSecondaryCursor(looserIndex - 1);
sortedCursorIndex--;
}
}
};
return CursorCollection;
}());
exports.CursorCollection = CursorCollection;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[486/*vs/editor/common/controller/cursor*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,4/*vs/base/common/event*/,5/*vs/base/common/strings*/,485/*vs/editor/common/controller/cursorCollection*/,40/*vs/editor/common/controller/cursorCommon*/,212/*vs/editor/common/controller/cursorDeleteOperations*/,159/*vs/editor/common/controller/cursorTypeOperations*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,68/*vs/editor/common/editorCommon*/,81/*vs/editor/common/view/viewEvents*/,2/*vs/base/common/lifecycle*/]), function (require, exports, errors_1, event_1, strings, cursorCollection_1, cursorCommon_1, cursorDeleteOperations_1, cursorTypeOperations_1, range_1, selection_1, editorCommon, viewEvents, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function containsLineMappingChanged(events) {
for (var i = 0, len = events.length; i < len; i++) {
if (events[i].type === 8 /* ViewLineMappingChanged */) {
return true;
}
}
return false;
}
var CursorStateChangedEvent = /** @class */ (function () {
function CursorStateChangedEvent(selections, modelVersionId, oldSelections, oldModelVersionId, source, reason) {
this.selections = selections;
this.modelVersionId = modelVersionId;
this.oldSelections = oldSelections;
this.oldModelVersionId = oldModelVersionId;
this.source = source;
this.reason = reason;
}
return CursorStateChangedEvent;
}());
exports.CursorStateChangedEvent = CursorStateChangedEvent;
/**
* A snapshot of the cursor and the model state
*/
var CursorModelState = /** @class */ (function () {
function CursorModelState(model, cursor) {
this.modelVersionId = model.getVersionId();
this.cursorState = cursor.getAll();
}
CursorModelState.prototype.equals = function (other) {
if (!other) {
return false;
}
if (this.modelVersionId !== other.modelVersionId) {
return false;
}
if (this.cursorState.length !== other.cursorState.length) {
return false;
}
for (var i = 0, len = this.cursorState.length; i < len; i++) {
if (!this.cursorState[i].equals(other.cursorState[i])) {
return false;
}
}
return true;
};
return CursorModelState;
}());
exports.CursorModelState = CursorModelState;
var AutoClosedAction = /** @class */ (function () {
function AutoClosedAction(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) {
this._model = model;
this._autoClosedCharactersDecorations = autoClosedCharactersDecorations;
this._autoClosedEnclosingDecorations = autoClosedEnclosingDecorations;
}
AutoClosedAction.getAllAutoClosedCharacters = function (autoClosedActions) {
var autoClosedCharacters = [];
for (var _i = 0, autoClosedActions_1 = autoClosedActions; _i < autoClosedActions_1.length; _i++) {
var autoClosedAction = autoClosedActions_1[_i];
autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges());
}
return autoClosedCharacters;
};
AutoClosedAction.prototype.dispose = function () {
this._autoClosedCharactersDecorations = this._model.deltaDecorations(this._autoClosedCharactersDecorations, []);
this._autoClosedEnclosingDecorations = this._model.deltaDecorations(this._autoClosedEnclosingDecorations, []);
};
AutoClosedAction.prototype.getAutoClosedCharactersRanges = function () {
var result = [];
for (var i = 0; i < this._autoClosedCharactersDecorations.length; i++) {
var decorationRange = this._model.getDecorationRange(this._autoClosedCharactersDecorations[i]);
if (decorationRange) {
result.push(decorationRange);
}
}
return result;
};
AutoClosedAction.prototype.isValid = function (selections) {
var enclosingRanges = [];
for (var i = 0; i < this._autoClosedEnclosingDecorations.length; i++) {
var decorationRange = this._model.getDecorationRange(this._autoClosedEnclosingDecorations[i]);
if (decorationRange) {
enclosingRanges.push(decorationRange);
if (decorationRange.startLineNumber !== decorationRange.endLineNumber) {
// Stop tracking if the range becomes multiline...
return false;
}
}
}
enclosingRanges.sort(range_1.Range.compareRangesUsingStarts);
selections.sort(range_1.Range.compareRangesUsingStarts);
for (var i = 0; i < selections.length; i++) {
if (i >= enclosingRanges.length) {
return false;
}
if (!enclosingRanges[i].strictContainsRange(selections[i])) {
return false;
}
}
return true;
};
return AutoClosedAction;
}());
var Cursor = /** @class */ (function (_super) {
__extends(Cursor, _super);
function Cursor(configuration, model, viewModel) {
var _this = _super.call(this) || this;
_this._onDidReachMaxCursorCount = _this._register(new event_1.Emitter());
_this.onDidReachMaxCursorCount = _this._onDidReachMaxCursorCount.event;
_this._onDidAttemptReadOnlyEdit = _this._register(new event_1.Emitter());
_this.onDidAttemptReadOnlyEdit = _this._onDidAttemptReadOnlyEdit.event;
_this._onDidChange = _this._register(new event_1.Emitter());
_this.onDidChange = _this._onDidChange.event;
_this._configuration = configuration;
_this._model = model;
_this._knownModelVersionId = _this._model.getVersionId();
_this._viewModel = viewModel;
_this.context = new cursorCommon_1.CursorContext(_this._configuration, _this._model, _this._viewModel);
_this._cursors = new cursorCollection_1.CursorCollection(_this.context);
_this._isHandling = false;
_this._isDoingComposition = false;
_this._selectionsWhenCompositionStarted = null;
_this._columnSelectData = null;
_this._autoClosedActions = [];
_this._prevEditOperationType = 0 /* Other */;
_this._register(_this._model.onDidChangeRawContent(function (e) {
_this._knownModelVersionId = e.versionId;
if (_this._isHandling) {
return;
}
var hadFlushEvent = e.containsEvent(1 /* Flush */);
_this._onModelContentChanged(hadFlushEvent);
}));
_this._register(viewModel.addEventListener(function (events) {
if (!containsLineMappingChanged(events)) {
return;
}
if (_this._knownModelVersionId !== _this._model.getVersionId()) {
// There are model change events that I didn't yet receive.
//
// This can happen when editing the model, and the view model receives the change events first,
// and the view model emits line mapping changed events, all before the cursor gets a chance to
// recover from markers.
//
// The model change listener above will be called soon and we'll ensure a valid cursor state there.
return;
}
// Ensure valid state
_this.setStates('viewModel', 0 /* NotSet */, _this.getAll());
}));
var updateCursorContext = function () {
_this.context = new cursorCommon_1.CursorContext(_this._configuration, _this._model, _this._viewModel);
_this._cursors.updateContext(_this.context);
};
_this._register(_this._model.onDidChangeLanguage(function (e) {
updateCursorContext();
}));
_this._register(_this._model.onDidChangeLanguageConfiguration(function () {
updateCursorContext();
}));
_this._register(_this._model.onDidChangeOptions(function () {
updateCursorContext();
}));
_this._register(_this._configuration.onDidChange(function (e) {
if (cursorCommon_1.CursorConfiguration.shouldRecreate(e)) {
updateCursorContext();
}
}));
return _this;
}
Cursor.prototype.dispose = function () {
this._cursors.dispose();
this._autoClosedActions = lifecycle_1.dispose(this._autoClosedActions);
_super.prototype.dispose.call(this);
};
Cursor.prototype._validateAutoClosedActions = function () {
if (this._autoClosedActions.length > 0) {
var selections = this._cursors.getSelections();
for (var i = 0; i < this._autoClosedActions.length; i++) {
var autoClosedAction = this._autoClosedActions[i];
if (!autoClosedAction.isValid(selections)) {
autoClosedAction.dispose();
this._autoClosedActions.splice(i, 1);
i--;
}
}
}
};
// ------ some getters/setters
Cursor.prototype.getPrimaryCursor = function () {
return this._cursors.getPrimaryCursor();
};
Cursor.prototype.getLastAddedCursorIndex = function () {
return this._cursors.getLastAddedCursorIndex();
};
Cursor.prototype.getAll = function () {
return this._cursors.getAll();
};
Cursor.prototype.setStates = function (source, reason, states) {
if (states !== null && states.length > Cursor.MAX_CURSOR_COUNT) {
states = states.slice(0, Cursor.MAX_CURSOR_COUNT);
this._onDidReachMaxCursorCount.fire(undefined);
}
var oldState = new CursorModelState(this._model, this);
this._cursors.setStates(states);
this._cursors.normalize();
this._columnSelectData = null;
this._validateAutoClosedActions();
this._emitStateChangedIfNecessary(source, reason, oldState);
};
Cursor.prototype.setColumnSelectData = function (columnSelectData) {
this._columnSelectData = columnSelectData;
};
Cursor.prototype.reveal = function (source, horizontal, target, scrollType) {
this._revealRange(source, target, 0 /* Simple */, horizontal, scrollType);
};
Cursor.prototype.revealRange = function (source, revealHorizontal, viewRange, verticalType, scrollType) {
this.emitCursorRevealRange(source, viewRange, verticalType, revealHorizontal, scrollType);
};
Cursor.prototype.scrollTo = function (desiredScrollTop) {
this._viewModel.viewLayout.setScrollPositionSmooth({
scrollTop: desiredScrollTop
});
};
Cursor.prototype.saveState = function () {
var result = [];
var selections = this._cursors.getSelections();
for (var i = 0, len = selections.length; i < len; i++) {
var selection = selections[i];
result.push({
inSelectionMode: !selection.isEmpty(),
selectionStart: {
lineNumber: selection.selectionStartLineNumber,
column: selection.selectionStartColumn,
},
position: {
lineNumber: selection.positionLineNumber,
column: selection.positionColumn,
}
});
}
return result;
};
Cursor.prototype.restoreState = function (states) {
var desiredSelections = [];
for (var i = 0, len = states.length; i < len; i++) {
var state = states[i];
var positionLineNumber = 1;
var positionColumn = 1;
// Avoid missing properties on the literal
if (state.position && state.position.lineNumber) {
positionLineNumber = state.position.lineNumber;
}
if (state.position && state.position.column) {
positionColumn = state.position.column;
}
var selectionStartLineNumber = positionLineNumber;
var selectionStartColumn = positionColumn;
// Avoid missing properties on the literal
if (state.selectionStart && state.selectionStart.lineNumber) {
selectionStartLineNumber = state.selectionStart.lineNumber;
}
if (state.selectionStart && state.selectionStart.column) {
selectionStartColumn = state.selectionStart.column;
}
desiredSelections.push({
selectionStartLineNumber: selectionStartLineNumber,
selectionStartColumn: selectionStartColumn,
positionLineNumber: positionLineNumber,
positionColumn: positionColumn
});
}
this.setStates('restoreState', 0 /* NotSet */, cursorCommon_1.CursorState.fromModelSelections(desiredSelections));
this.reveal('restoreState', true, 0 /* Primary */, 1 /* Immediate */);
};
Cursor.prototype._onModelContentChanged = function (hadFlushEvent) {
this._prevEditOperationType = 0 /* Other */;
if (hadFlushEvent) {
// a model.setValue() was called
this._cursors.dispose();
this._cursors = new cursorCollection_1.CursorCollection(this.context);
this._validateAutoClosedActions();
this._emitStateChangedIfNecessary('model', 1 /* ContentFlush */, null);
}
else {
var selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
this.setStates('modelChange', 2 /* RecoverFromMarkers */, cursorCommon_1.CursorState.fromModelSelections(selectionsFromMarkers));
}
};
Cursor.prototype.getSelection = function () {
return this._cursors.getPrimaryCursor().modelState.selection;
};
Cursor.prototype.getColumnSelectData = function () {
if (this._columnSelectData) {
return this._columnSelectData;
}
var primaryCursor = this._cursors.getPrimaryCursor();
var primaryPos = primaryCursor.viewState.selectionStart.getStartPosition();
var viewLineNumber = primaryPos.lineNumber;
var viewVisualColumn = cursorCommon_1.CursorColumns.visibleColumnFromColumn2(this.context.config, this.context.viewModel, primaryPos);
return {
isReal: false,
fromViewLineNumber: viewLineNumber,
fromViewVisualColumn: viewVisualColumn,
toViewLineNumber: viewLineNumber,
toViewVisualColumn: viewVisualColumn,
};
};
Cursor.prototype.getSelections = function () {
return this._cursors.getSelections();
};
Cursor.prototype.getViewSelections = function () {
return this._cursors.getViewSelections();
};
Cursor.prototype.getPosition = function () {
return this._cursors.getPrimaryCursor().modelState.position;
};
Cursor.prototype.setSelections = function (source, selections) {
this.setStates(source, 0 /* NotSet */, cursorCommon_1.CursorState.fromModelSelections(selections));
};
Cursor.prototype.getPrevEditOperationType = function () {
return this._prevEditOperationType;
};
Cursor.prototype.setPrevEditOperationType = function (type) {
this._prevEditOperationType = type;
};
// ------ auxiliary handling logic
Cursor.prototype._pushAutoClosedAction = function (autoClosedCharactersRanges, autoClosedEnclosingRanges) {
var autoClosedCharactersDeltaDecorations = [];
var autoClosedEnclosingDeltaDecorations = [];
for (var i = 0, len = autoClosedCharactersRanges.length; i < len; i++) {
autoClosedCharactersDeltaDecorations.push({
range: autoClosedCharactersRanges[i],
options: {
inlineClassName: 'auto-closed-character',
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */
}
});
autoClosedEnclosingDeltaDecorations.push({
range: autoClosedEnclosingRanges[i],
options: {
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */
}
});
}
var autoClosedCharactersDecorations = this._model.deltaDecorations([], autoClosedCharactersDeltaDecorations);
var autoClosedEnclosingDecorations = this._model.deltaDecorations([], autoClosedEnclosingDeltaDecorations);
this._autoClosedActions.push(new AutoClosedAction(this._model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations));
};
Cursor.prototype._executeEditOperation = function (opResult) {
if (!opResult) {
// Nothing to execute
return;
}
if (opResult.shouldPushStackElementBefore) {
this._model.pushStackElement();
}
var result = CommandExecutor.executeCommands(this._model, this._cursors.getSelections(), opResult.commands);
if (result) {
// The commands were applied correctly
this._interpretCommandResult(result);
// Check for auto-closing closed characters
var autoClosedCharactersRanges = [];
var autoClosedEnclosingRanges = [];
for (var i = 0; i < opResult.commands.length; i++) {
var command = opResult.commands[i];
if (command instanceof cursorTypeOperations_1.TypeWithAutoClosingCommand && command.enclosingRange && command.closeCharacterRange) {
autoClosedCharactersRanges.push(command.closeCharacterRange);
autoClosedEnclosingRanges.push(command.enclosingRange);
}
}
if (autoClosedCharactersRanges.length > 0) {
this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
}
this._prevEditOperationType = opResult.type;
}
if (opResult.shouldPushStackElementAfter) {
this._model.pushStackElement();
}
};
Cursor.prototype._interpretCommandResult = function (cursorState) {
if (!cursorState || cursorState.length === 0) {
cursorState = this._cursors.readSelectionFromMarkers();
}
this._columnSelectData = null;
this._cursors.setSelections(cursorState);
this._cursors.normalize();
};
// -----------------------------------------------------------------------------------------------------------
// ----- emitting events
Cursor.prototype._emitStateChangedIfNecessary = function (source, reason, oldState) {
var newState = new CursorModelState(this._model, this);
if (newState.equals(oldState)) {
return false;
}
var selections = this._cursors.getSelections();
var viewSelections = this._cursors.getViewSelections();
// Let the view get the event first.
try {
var eventsCollector = this._beginEmit();
eventsCollector.emit(new viewEvents.ViewCursorStateChangedEvent(viewSelections, selections));
}
finally {
this._endEmit();
}
// Only after the view has been notified, let the rest of the world know...
if (!oldState
|| oldState.cursorState.length !== newState.cursorState.length
|| newState.cursorState.some(function (newCursorState, i) { return !newCursorState.modelState.equals(oldState.cursorState[i].modelState); })) {
var oldSelections = oldState ? oldState.cursorState.map(function (s) { return s.modelState.selection; }) : null;
var oldModelVersionId = oldState ? oldState.modelVersionId : 0;
this._onDidChange.fire(new CursorStateChangedEvent(selections, newState.modelVersionId, oldSelections, oldModelVersionId, source || 'keyboard', reason));
}
return true;
};
Cursor.prototype._revealRange = function (source, revealTarget, verticalType, revealHorizontal, scrollType) {
var viewPositions = this._cursors.getViewPositions();
var viewPosition = viewPositions[0];
if (revealTarget === 1 /* TopMost */) {
for (var i = 1; i < viewPositions.length; i++) {
if (viewPositions[i].isBefore(viewPosition)) {
viewPosition = viewPositions[i];
}
}
}
else if (revealTarget === 2 /* BottomMost */) {
for (var i = 1; i < viewPositions.length; i++) {
if (viewPosition.isBeforeOrEqual(viewPositions[i])) {
viewPosition = viewPositions[i];
}
}
}
else {
if (viewPositions.length > 1) {
// no revealing!
return;
}
}
var viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
this.emitCursorRevealRange(source, viewRange, verticalType, revealHorizontal, scrollType);
};
Cursor.prototype.emitCursorRevealRange = function (source, viewRange, verticalType, revealHorizontal, scrollType) {
try {
var eventsCollector = this._beginEmit();
eventsCollector.emit(new viewEvents.ViewRevealRangeRequestEvent(source, viewRange, verticalType, revealHorizontal, scrollType));
}
finally {
this._endEmit();
}
};
// -----------------------------------------------------------------------------------------------------------
// ----- handlers beyond this point
Cursor.prototype._findAutoClosingPairs = function (edits) {
if (!edits.length) {
return null;
}
var indices = [];
for (var i = 0, len = edits.length; i < len; i++) {
var edit = edits[i];
if (!edit.text || edit.text.indexOf('\n') >= 0) {
return null;
}
var m = edit.text.match(/([)\]}>'"`])([^)\]}>'"`]*)$/);
if (!m) {
return null;
}
var closeChar = m[1];
var autoClosingPairsCandidates = this.context.config.autoClosingPairsClose2.get(closeChar);
if (!autoClosingPairsCandidates || autoClosingPairsCandidates.length !== 1) {
return null;
}
var openChar = autoClosingPairsCandidates[0].open;
var closeCharIndex = edit.text.length - m[2].length - 1;
var openCharIndex = edit.text.lastIndexOf(openChar, closeCharIndex - 1);
if (openCharIndex === -1) {
return null;
}
indices.push([openCharIndex, closeCharIndex]);
}
return indices;
};
Cursor.prototype.executeEdits = function (source, edits, cursorStateComputer) {
var _this = this;
var autoClosingIndices = null;
if (source === 'snippet') {
autoClosingIndices = this._findAutoClosingPairs(edits);
}
if (autoClosingIndices) {
edits[0]._isTracked = true;
}
var autoClosedCharactersRanges = [];
var autoClosedEnclosingRanges = [];
var selections = this._model.pushEditOperations(this.getSelections(), edits, function (undoEdits) {
if (autoClosingIndices) {
for (var i = 0, len = autoClosingIndices.length; i < len; i++) {
var _a = autoClosingIndices[i], openCharInnerIndex = _a[0], closeCharInnerIndex = _a[1];
var undoEdit = undoEdits[i];
var lineNumber = undoEdit.range.startLineNumber;
var openCharIndex = undoEdit.range.startColumn - 1 + openCharInnerIndex;
var closeCharIndex = undoEdit.range.startColumn - 1 + closeCharInnerIndex;
autoClosedCharactersRanges.push(new range_1.Range(lineNumber, closeCharIndex + 1, lineNumber, closeCharIndex + 2));
autoClosedEnclosingRanges.push(new range_1.Range(lineNumber, openCharIndex + 1, lineNumber, closeCharIndex + 2));
}
}
var selections = cursorStateComputer(undoEdits);
if (selections) {
// Don't recover the selection from markers because
// we know what it should be.
_this._isHandling = true;
}
return selections;
});
if (selections) {
this._isHandling = false;
this.setSelections(source, selections);
}
if (autoClosedCharactersRanges.length > 0) {
this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
}
};
Cursor.prototype.trigger = function (source, handlerId, payload) {
var H = editorCommon.Handler;
if (handlerId === H.CompositionStart) {
this._isDoingComposition = true;
this._selectionsWhenCompositionStarted = this.getSelections().slice(0);
return;
}
if (handlerId === H.CompositionEnd) {
this._isDoingComposition = false;
}
if (this._configuration.options.get(68 /* readOnly */)) {
// All the remaining handlers will try to edit the model,
// but we cannot edit when read only...
this._onDidAttemptReadOnlyEdit.fire(undefined);
return;
}
var oldState = new CursorModelState(this._model, this);
var cursorChangeReason = 0 /* NotSet */;
if (handlerId !== H.Undo && handlerId !== H.Redo) {
// TODO@Alex: if the undo/redo stack contains non-null selections
// it would also be OK to stop tracking selections here
this._cursors.stopTrackingSelections();
}
// ensure valid state on all cursors
this._cursors.ensureValidState();
this._isHandling = true;
try {
switch (handlerId) {
case H.Type:
this._type(source, payload.text);
break;
case H.ReplacePreviousChar:
this._replacePreviousChar(payload.text, payload.replaceCharCnt);
break;
case H.Paste:
cursorChangeReason = 4 /* Paste */;
this._paste(payload.text, payload.pasteOnNewLine, payload.multicursorText || []);
break;
case H.Cut:
this._cut();
break;
case H.Undo:
cursorChangeReason = 5 /* Undo */;
this._interpretCommandResult(this._model.undo());
break;
case H.Redo:
cursorChangeReason = 6 /* Redo */;
this._interpretCommandResult(this._model.redo());
break;
case H.ExecuteCommand:
this._externalExecuteCommand(payload);
break;
case H.ExecuteCommands:
this._externalExecuteCommands(payload);
break;
case H.CompositionEnd:
this._interpretCompositionEnd(source);
break;
}
}
catch (err) {
errors_1.onUnexpectedError(err);
}
this._isHandling = false;
if (handlerId !== H.Undo && handlerId !== H.Redo) {
this._cursors.startTrackingSelections();
}
this._validateAutoClosedActions();
if (this._emitStateChangedIfNecessary(source, cursorChangeReason, oldState)) {
this._revealRange(source, 0 /* Primary */, 0 /* Simple */, true, 0 /* Smooth */);
}
};
Cursor.prototype._interpretCompositionEnd = function (source) {
if (!this._isDoingComposition && source === 'keyboard') {
// composition finishes, let's check if we need to auto complete if necessary.
var autoClosedCharacters = AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions);
this._executeEditOperation(cursorTypeOperations_1.TypeOperations.compositionEndWithInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this._selectionsWhenCompositionStarted, this.getSelections(), autoClosedCharacters));
this._selectionsWhenCompositionStarted = null;
}
};
Cursor.prototype._type = function (source, text) {
if (!this._isDoingComposition && source === 'keyboard') {
// If this event is coming straight from the keyboard, look for electric characters and enter
var len = text.length;
var offset = 0;
while (offset < len) {
var charLength = strings.nextCharLength(text, offset);
var chr = text.substr(offset, charLength);
// Here we must interpret each typed character individually
var autoClosedCharacters = AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions);
this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), autoClosedCharacters, chr));
offset += charLength;
}
}
else {
this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), text));
}
};
Cursor.prototype._replacePreviousChar = function (text, replaceCharCnt) {
this._executeEditOperation(cursorTypeOperations_1.TypeOperations.replacePreviousChar(this._prevEditOperationType, this.context.config, this.context.model, this.getSelections(), text, replaceCharCnt));
};
Cursor.prototype._paste = function (text, pasteOnNewLine, multicursorText) {
this._executeEditOperation(cursorTypeOperations_1.TypeOperations.paste(this.context.config, this.context.model, this.getSelections(), text, pasteOnNewLine, multicursorText));
};
Cursor.prototype._cut = function () {
this._executeEditOperation(cursorDeleteOperations_1.DeleteOperations.cut(this.context.config, this.context.model, this.getSelections()));
};
Cursor.prototype._externalExecuteCommand = function (command) {
this._cursors.killSecondaryCursors();
this._executeEditOperation(new cursorCommon_1.EditOperationResult(0 /* Other */, [command], {
shouldPushStackElementBefore: false,
shouldPushStackElementAfter: false
}));
};
Cursor.prototype._externalExecuteCommands = function (commands) {
this._executeEditOperation(new cursorCommon_1.EditOperationResult(0 /* Other */, commands, {
shouldPushStackElementBefore: false,
shouldPushStackElementAfter: false
}));
};
Cursor.MAX_CURSOR_COUNT = 10000;
return Cursor;
}(viewEvents.ViewEventEmitter));
exports.Cursor = Cursor;
var CommandExecutor = /** @class */ (function () {
function CommandExecutor() {
}
CommandExecutor.executeCommands = function (model, selectionsBefore, commands) {
var ctx = {
model: model,
selectionsBefore: selectionsBefore,
trackedRanges: [],
trackedRangesDirection: []
};
var result = this._innerExecuteCommands(ctx, commands);
for (var i = 0, len = ctx.trackedRanges.length; i < len; i++) {
ctx.model._setTrackedRange(ctx.trackedRanges[i], null, 0 /* AlwaysGrowsWhenTypingAtEdges */);
}
return result;
};
CommandExecutor._innerExecuteCommands = function (ctx, commands) {
if (this._arrayIsEmpty(commands)) {
return null;
}
var commandsData = this._getEditOperations(ctx, commands);
if (commandsData.operations.length === 0) {
return null;
}
var rawOperations = commandsData.operations;
var loserCursorsMap = this._getLoserCursorMap(rawOperations);
if (loserCursorsMap.hasOwnProperty('0')) {
// These commands are very messed up
console.warn('Ignoring commands');
return null;
}
// Remove operations belonging to losing cursors
var filteredOperations = [];
for (var i = 0, len = rawOperations.length; i < len; i++) {
if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) {
filteredOperations.push(rawOperations[i]);
}
}
// TODO@Alex: find a better way to do this.
// give the hint that edit operations are tracked to the model
if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) {
filteredOperations[0]._isTracked = true;
}
var selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, function (inverseEditOperations) {
var groupedInverseEditOperations = [];
for (var i = 0; i < ctx.selectionsBefore.length; i++) {
groupedInverseEditOperations[i] = [];
}
for (var _i = 0, inverseEditOperations_1 = inverseEditOperations; _i < inverseEditOperations_1.length; _i++) {
var op = inverseEditOperations_1[_i];
if (!op.identifier) {
// perhaps auto whitespace trim edits
continue;
}
groupedInverseEditOperations[op.identifier.major].push(op);
}
var minorBasedSorter = function (a, b) {
return a.identifier.minor - b.identifier.minor;
};
var cursorSelections = [];
var _loop_1 = function (i) {
if (groupedInverseEditOperations[i].length > 0) {
groupedInverseEditOperations[i].sort(minorBasedSorter);
cursorSelections[i] = commands[i].computeCursorState(ctx.model, {
getInverseEditOperations: function () {
return groupedInverseEditOperations[i];
},
getTrackedSelection: function (id) {
var idx = parseInt(id, 10);
var range = ctx.model._getTrackedRange(ctx.trackedRanges[idx]);
if (ctx.trackedRangesDirection[idx] === 0 /* LTR */) {
return new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
}
return new selection_1.Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn);
}
});
}
else {
cursorSelections[i] = ctx.selectionsBefore[i];
}
};
for (var i = 0; i < ctx.selectionsBefore.length; i++) {
_loop_1(i);
}
return cursorSelections;
});
if (!selectionsAfter) {
selectionsAfter = ctx.selectionsBefore;
}
// Extract losing cursors
var losingCursors = [];
for (var losingCursorIndex in loserCursorsMap) {
if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) {
losingCursors.push(parseInt(losingCursorIndex, 10));
}
}
// Sort losing cursors descending
losingCursors.sort(function (a, b) {
return b - a;
});
// Remove losing cursors
for (var _i = 0, losingCursors_1 = losingCursors; _i < losingCursors_1.length; _i++) {
var losingCursor = losingCursors_1[_i];
selectionsAfter.splice(losingCursor, 1);
}
return selectionsAfter;
};
CommandExecutor._arrayIsEmpty = function (commands) {
for (var i = 0, len = commands.length; i < len; i++) {
if (commands[i]) {
return false;
}
}
return true;
};
CommandExecutor._getEditOperations = function (ctx, commands) {
var operations = [];
var hadTrackedEditOperation = false;
for (var i = 0, len = commands.length; i < len; i++) {
var command = commands[i];
if (command) {
var r = this._getEditOperationsFromCommand(ctx, i, command);
operations = operations.concat(r.operations);
hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation;
}
}
return {
operations: operations,
hadTrackedEditOperation: hadTrackedEditOperation
};
};
CommandExecutor._getEditOperationsFromCommand = function (ctx, majorIdentifier, command) {
// This method acts as a transaction, if the command fails
// everything it has done is ignored
var operations = [];
var operationMinor = 0;
var addEditOperation = function (selection, text, forceMoveMarkers) {
if (forceMoveMarkers === void 0) { forceMoveMarkers = false; }
if (selection.isEmpty() && text === '') {
// This command wants to add a no-op => no thank you
return;
}
operations.push({
identifier: {
major: majorIdentifier,
minor: operationMinor++
},
range: selection,
text: text,
forceMoveMarkers: forceMoveMarkers,
isAutoWhitespaceEdit: command.insertsAutoWhitespace
});
};
var hadTrackedEditOperation = false;
var addTrackedEditOperation = function (selection, text, forceMoveMarkers) {
hadTrackedEditOperation = true;
addEditOperation(selection, text, forceMoveMarkers);
};
var trackSelection = function (selection, trackPreviousOnEmpty) {
var stickiness;
if (selection.isEmpty()) {
if (typeof trackPreviousOnEmpty === 'boolean') {
if (trackPreviousOnEmpty) {
stickiness = 2 /* GrowsOnlyWhenTypingBefore */;
}
else {
stickiness = 3 /* GrowsOnlyWhenTypingAfter */;
}
}
else {
// Try to lock it with surrounding text
var maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber);
if (selection.startColumn === maxLineColumn) {
stickiness = 2 /* GrowsOnlyWhenTypingBefore */;
}
else {
stickiness = 3 /* GrowsOnlyWhenTypingAfter */;
}
}
}
else {
stickiness = 1 /* NeverGrowsWhenTypingAtEdges */;
}
var l = ctx.trackedRanges.length;
var id = ctx.model._setTrackedRange(null, selection, stickiness);
ctx.trackedRanges[l] = id;
ctx.trackedRangesDirection[l] = selection.getDirection();
return l.toString();
};
var editOperationBuilder = {
addEditOperation: addEditOperation,
addTrackedEditOperation: addTrackedEditOperation,
trackSelection: trackSelection
};
try {
command.getEditOperations(ctx.model, editOperationBuilder);
}
catch (e) {
// TODO@Alex use notification service if this should be user facing
// e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command.");
errors_1.onUnexpectedError(e);
return {
operations: [],
hadTrackedEditOperation: false
};
}
return {
operations: operations,
hadTrackedEditOperation: hadTrackedEditOperation
};
};
CommandExecutor._getLoserCursorMap = function (operations) {
// This is destructive on the array
operations = operations.slice(0);
// Sort operations with last one first
operations.sort(function (a, b) {
// Note the minus!
return -(range_1.Range.compareRangesUsingEnds(a.range, b.range));
});
// Operations can not overlap!
var loserCursorsMap = {};
for (var i = 1; i < operations.length; i++) {
var previousOp = operations[i - 1];
var currentOp = operations[i];
if (previousOp.range.getStartPosition().isBefore(currentOp.range.getEndPosition())) {
var loserMajor = void 0;
if (previousOp.identifier.major > currentOp.identifier.major) {
// previousOp loses the battle
loserMajor = previousOp.identifier.major;
}
else {
loserMajor = currentOp.identifier.major;
}
loserCursorsMap[loserMajor.toString()] = true;
for (var j = 0; j < operations.length; j++) {
if (operations[j].identifier.major === loserMajor) {
operations.splice(j, 1);
if (j < i) {
i--;
}
j--;
}
}
if (i > 0) {
i--;
}
}
}
return loserCursorsMap;
};
return CommandExecutor;
}());
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[214/*vs/editor/common/modes/textToHtmlTokenizer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,93/*vs/editor/common/core/lineTokens*/,63/*vs/editor/common/modes/nullMode*/]), function (require, exports, strings, lineTokens_1, nullMode_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fallback = {
getInitialState: function () { return nullMode_1.NULL_STATE; },
tokenize2: function (buffer, state, deltaOffset) { return nullMode_1.nullTokenize2(0 /* Null */, buffer, state, deltaOffset); }
};
function tokenizeToString(text, tokenizationSupport) {
if (tokenizationSupport === void 0) { tokenizationSupport = fallback; }
return _tokenizeToString(text, tokenizationSupport || fallback);
}
exports.tokenizeToString = tokenizeToString;
function tokenizeLineToHTML(text, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) {
var result = "
";
var charIndex = startOffset;
var tabsCharDelta = 0;
for (var tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) {
var tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex);
if (tokenEndIndex <= startOffset) {
continue;
}
var partContent = '';
for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) {
var charCode = text.charCodeAt(charIndex);
switch (charCode) {
case 9 /* Tab */:
var insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
tabsCharDelta += insertSpacesCount - 1;
while (insertSpacesCount > 0) {
partContent += useNbsp ? ' ' : ' ';
insertSpacesCount--;
}
break;
case 60 /* LessThan */:
partContent += '<';
break;
case 62 /* GreaterThan */:
partContent += '>';
break;
case 38 /* Ampersand */:
partContent += '&';
break;
case 0 /* Null */:
partContent += '';
break;
case 65279 /* UTF8_BOM */:
case 8232 /* LINE_SEPARATOR_2028 */:
partContent += '\ufffd';
break;
case 13 /* CarriageReturn */:
// zero width space, because carriage return would introduce a line break
partContent += '';
break;
case 32 /* Space */:
partContent += useNbsp ? ' ' : ' ';
break;
default:
partContent += String.fromCharCode(charCode);
}
}
result += "" + partContent + "";
if (tokenEndIndex > endOffset || charIndex >= endOffset) {
break;
}
}
result += "
";
return result;
}
exports.tokenizeLineToHTML = tokenizeLineToHTML;
function _tokenizeToString(text, tokenizationSupport) {
var result = "
";
var lines = text.split(/\r\n|\r|\n/);
var currentState = tokenizationSupport.getInitialState();
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (i > 0) {
result += " ";
}
var tokenizationResult = tokenizationSupport.tokenize2(line, currentState, 0);
lineTokens_1.LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length);
var lineTokens = new lineTokens_1.LineTokens(tokenizationResult.tokens, line);
var viewLineTokens = lineTokens.inflate();
var startOffset = 0;
for (var j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) {
var type = viewLineTokens.getClassName(j);
var endIndex = viewLineTokens.getEndOffset(j);
result += "" + strings.escape(line.substring(startOffset, endIndex)) + "";
startOffset = endIndex;
}
currentState = tokenizationResult.endState;
}
result += "
";
return result;
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[84/*vs/editor/common/services/resolverService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ITextModelService = instantiation_1.createDecorator('textModelService');
});
define(__m[114/*vs/editor/common/services/textResourceConfigurationService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ITextResourceConfigurationService = instantiation_1.createDecorator('textResourceConfigurationService');
exports.ITextResourcePropertiesService = instantiation_1.createDecorator('textResourcePropertiesService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[215/*vs/editor/common/viewModel/minimapTokensColorTracker*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,339/*vs/editor/common/core/rgba*/,17/*vs/editor/common/modes*/]), function (require, exports, event_1, rgba_1, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MinimapTokensColorTracker = /** @class */ (function () {
function MinimapTokensColorTracker() {
var _this = this;
this._onDidChange = new event_1.Emitter();
this.onDidChange = this._onDidChange.event;
this._updateColorMap();
modes_1.TokenizationRegistry.onDidChange(function (e) {
if (e.changedColorMap) {
_this._updateColorMap();
}
});
}
MinimapTokensColorTracker.getInstance = function () {
if (!this._INSTANCE) {
this._INSTANCE = new MinimapTokensColorTracker();
}
return this._INSTANCE;
};
MinimapTokensColorTracker.prototype._updateColorMap = function () {
var colorMap = modes_1.TokenizationRegistry.getColorMap();
if (!colorMap) {
this._colors = [rgba_1.RGBA8.Empty];
this._backgroundIsLight = true;
return;
}
this._colors = [rgba_1.RGBA8.Empty];
for (var colorId = 1; colorId < colorMap.length; colorId++) {
var source = colorMap[colorId].rgba;
// Use a VM friendly data-type
this._colors[colorId] = new rgba_1.RGBA8(source.r, source.g, source.b, Math.round(source.a * 255));
}
var backgroundLuminosity = colorMap[2 /* DefaultBackground */].getRelativeLuminance();
this._backgroundIsLight = backgroundLuminosity >= 0.5;
this._onDidChange.fire(undefined);
};
MinimapTokensColorTracker.prototype.getColor = function (colorId) {
if (colorId < 1 || colorId >= this._colors.length) {
// background color (basically invisible)
colorId = 2 /* DefaultBackground */;
}
return this._colors[colorId];
};
MinimapTokensColorTracker.prototype.backgroundIsLight = function () {
return this._backgroundIsLight;
};
MinimapTokensColorTracker._INSTANCE = null;
return MinimapTokensColorTracker;
}());
exports.MinimapTokensColorTracker = MinimapTokensColorTracker;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[161/*vs/editor/common/viewModel/splitLinesCollection*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,30/*vs/editor/common/model/textModel*/,81/*vs/editor/common/view/viewEvents*/,194/*vs/editor/common/viewModel/prefixSumComputer*/,69/*vs/editor/common/viewModel/viewModel*/]), function (require, exports, arrays, position_1, range_1, textModel_1, viewEvents, prefixSumComputer_1, viewModel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var OutputPosition = /** @class */ (function () {
function OutputPosition(outputLineIndex, outputOffset) {
this.outputLineIndex = outputLineIndex;
this.outputOffset = outputOffset;
}
return OutputPosition;
}());
exports.OutputPosition = OutputPosition;
var LineBreakData = /** @class */ (function () {
function LineBreakData(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength) {
this.breakOffsets = breakOffsets;
this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn;
this.wrappedTextIndentLength = wrappedTextIndentLength;
}
LineBreakData.getInputOffsetOfOutputPosition = function (breakOffsets, outputLineIndex, outputOffset) {
if (outputLineIndex === 0) {
return outputOffset;
}
else {
return breakOffsets[outputLineIndex - 1] + outputOffset;
}
};
LineBreakData.getOutputPositionOfInputOffset = function (breakOffsets, inputOffset) {
var low = 0;
var high = breakOffsets.length - 1;
var mid = 0;
var midStart = 0;
while (low <= high) {
mid = low + ((high - low) / 2) | 0;
var midStop = breakOffsets[mid];
midStart = mid > 0 ? breakOffsets[mid - 1] : 0;
if (inputOffset < midStart) {
high = mid - 1;
}
else if (inputOffset >= midStop) {
low = mid + 1;
}
else {
break;
}
}
return new OutputPosition(mid, inputOffset - midStart);
};
return LineBreakData;
}());
exports.LineBreakData = LineBreakData;
var CoordinatesConverter = /** @class */ (function () {
function CoordinatesConverter(lines) {
this._lines = lines;
}
// View -> Model conversion and related methods
CoordinatesConverter.prototype.convertViewPositionToModelPosition = function (viewPosition) {
return this._lines.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column);
};
CoordinatesConverter.prototype.convertViewRangeToModelRange = function (viewRange) {
return this._lines.convertViewRangeToModelRange(viewRange);
};
CoordinatesConverter.prototype.validateViewPosition = function (viewPosition, expectedModelPosition) {
return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition);
};
CoordinatesConverter.prototype.validateViewRange = function (viewRange, expectedModelRange) {
return this._lines.validateViewRange(viewRange, expectedModelRange);
};
// Model -> View conversion and related methods
CoordinatesConverter.prototype.convertModelPositionToViewPosition = function (modelPosition) {
return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column);
};
CoordinatesConverter.prototype.convertModelRangeToViewRange = function (modelRange) {
return this._lines.convertModelRangeToViewRange(modelRange);
};
CoordinatesConverter.prototype.modelPositionIsVisible = function (modelPosition) {
return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column);
};
return CoordinatesConverter;
}());
exports.CoordinatesConverter = CoordinatesConverter;
var LineNumberMapper = /** @class */ (function () {
function LineNumberMapper(viewLineCounts) {
this._counts = viewLineCounts;
this._isValid = false;
this._validEndIndex = -1;
this._modelToView = [];
this._viewToModel = [];
}
LineNumberMapper.prototype._invalidate = function (index) {
this._isValid = false;
this._validEndIndex = Math.min(this._validEndIndex, index - 1);
};
LineNumberMapper.prototype._ensureValid = function () {
if (this._isValid) {
return;
}
for (var i = this._validEndIndex + 1, len = this._counts.length; i < len; i++) {
var viewLineCount = this._counts[i];
var viewLinesAbove = (i > 0 ? this._modelToView[i - 1] : 0);
this._modelToView[i] = viewLinesAbove + viewLineCount;
for (var j = 0; j < viewLineCount; j++) {
this._viewToModel[viewLinesAbove + j] = i;
}
}
// trim things
this._modelToView.length = this._counts.length;
this._viewToModel.length = this._modelToView[this._modelToView.length - 1];
// mark as valid
this._isValid = true;
this._validEndIndex = this._counts.length - 1;
};
LineNumberMapper.prototype.changeValue = function (index, value) {
if (this._counts[index] === value) {
// no change
return;
}
this._counts[index] = value;
this._invalidate(index);
};
LineNumberMapper.prototype.removeValues = function (start, deleteCount) {
this._counts.splice(start, deleteCount);
this._invalidate(start);
};
LineNumberMapper.prototype.insertValues = function (insertIndex, insertArr) {
this._counts = arrays.arrayInsert(this._counts, insertIndex, insertArr);
this._invalidate(insertIndex);
};
LineNumberMapper.prototype.getTotalValue = function () {
this._ensureValid();
return this._viewToModel.length;
};
LineNumberMapper.prototype.getAccumulatedValue = function (index) {
this._ensureValid();
return this._modelToView[index];
};
LineNumberMapper.prototype.getIndexOf = function (accumulatedValue) {
this._ensureValid();
var modelLineIndex = this._viewToModel[accumulatedValue];
var viewLinesAbove = (modelLineIndex > 0 ? this._modelToView[modelLineIndex - 1] : 0);
return new prefixSumComputer_1.PrefixSumIndexOfResult(modelLineIndex, accumulatedValue - viewLinesAbove);
};
return LineNumberMapper;
}());
var SplitLinesCollection = /** @class */ (function () {
function SplitLinesCollection(model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent) {
this.model = model;
this._validModelVersionId = -1;
this._domLineBreaksComputerFactory = domLineBreaksComputerFactory;
this._monospaceLineBreaksComputerFactory = monospaceLineBreaksComputerFactory;
this.fontInfo = fontInfo;
this.tabSize = tabSize;
this.wrappingStrategy = wrappingStrategy;
this.wrappingColumn = wrappingColumn;
this.wrappingIndent = wrappingIndent;
this._constructLines(/*resetHiddenAreas*/ true, null);
}
SplitLinesCollection.prototype.dispose = function () {
this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, []);
};
SplitLinesCollection.prototype.createCoordinatesConverter = function () {
return new CoordinatesConverter(this);
};
SplitLinesCollection.prototype._constructLines = function (resetHiddenAreas, previousLineBreaks) {
var _this = this;
this.lines = [];
if (resetHiddenAreas) {
this.hiddenAreasIds = [];
}
var linesContent = this.model.getLinesContent();
var lineCount = linesContent.length;
var lineBreaksComputer = this.createLineBreaksComputer();
for (var i = 0; i < lineCount; i++) {
lineBreaksComputer.addRequest(linesContent[i], previousLineBreaks ? previousLineBreaks[i] : null);
}
var linesBreaks = lineBreaksComputer.finalize();
var values = [];
var hiddenAreas = this.hiddenAreasIds.map(function (areaId) { return _this.model.getDecorationRange(areaId); }).sort(range_1.Range.compareRangesUsingStarts);
var hiddenAreaStart = 1, hiddenAreaEnd = 0;
var hiddenAreaIdx = -1;
var nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2;
for (var i = 0; i < lineCount; i++) {
var lineNumber = i + 1;
if (lineNumber === nextLineNumberToUpdateHiddenArea) {
hiddenAreaIdx++;
hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2;
}
var isInHiddenArea = (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd);
var line = createSplitLine(linesBreaks[i], !isInHiddenArea);
values[i] = line.getViewLineCount();
this.lines[i] = line;
}
this._validModelVersionId = this.model.getVersionId();
this.prefixSumComputer = new LineNumberMapper(values);
};
SplitLinesCollection.prototype.getHiddenAreas = function () {
var _this = this;
return this.hiddenAreasIds.map(function (decId) {
return _this.model.getDecorationRange(decId);
});
};
SplitLinesCollection.prototype._reduceRanges = function (_ranges) {
var _this = this;
if (_ranges.length === 0) {
return [];
}
var ranges = _ranges.map(function (r) { return _this.model.validateRange(r); }).sort(range_1.Range.compareRangesUsingStarts);
var result = [];
var currentRangeStart = ranges[0].startLineNumber;
var currentRangeEnd = ranges[0].endLineNumber;
for (var i = 1, len = ranges.length; i < len; i++) {
var range = ranges[i];
if (range.startLineNumber > currentRangeEnd + 1) {
result.push(new range_1.Range(currentRangeStart, 1, currentRangeEnd, 1));
currentRangeStart = range.startLineNumber;
currentRangeEnd = range.endLineNumber;
}
else if (range.endLineNumber > currentRangeEnd) {
currentRangeEnd = range.endLineNumber;
}
}
result.push(new range_1.Range(currentRangeStart, 1, currentRangeEnd, 1));
return result;
};
SplitLinesCollection.prototype.setHiddenAreas = function (_ranges) {
var _this = this;
var newRanges = this._reduceRanges(_ranges);
// BEGIN TODO@Martin: Please stop calling this method on each model change!
var oldRanges = this.hiddenAreasIds.map(function (areaId) { return _this.model.getDecorationRange(areaId); }).sort(range_1.Range.compareRangesUsingStarts);
if (newRanges.length === oldRanges.length) {
var hasDifference = false;
for (var i = 0; i < newRanges.length; i++) {
if (!newRanges[i].equalsRange(oldRanges[i])) {
hasDifference = true;
break;
}
}
if (!hasDifference) {
return false;
}
}
// END TODO@Martin: Please stop calling this method on each model change!
var newDecorations = [];
for (var _i = 0, newRanges_1 = newRanges; _i < newRanges_1.length; _i++) {
var newRange = newRanges_1[_i];
newDecorations.push({
range: newRange,
options: textModel_1.ModelDecorationOptions.EMPTY
});
}
this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, newDecorations);
var hiddenAreas = newRanges;
var hiddenAreaStart = 1, hiddenAreaEnd = 0;
var hiddenAreaIdx = -1;
var nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.lines.length + 2;
var hasVisibleLine = false;
for (var i = 0; i < this.lines.length; i++) {
var lineNumber = i + 1;
if (lineNumber === nextLineNumberToUpdateHiddenArea) {
hiddenAreaIdx++;
hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.lines.length + 2;
}
var lineChanged = false;
if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) {
// Line should be hidden
if (this.lines[i].isVisible()) {
this.lines[i] = this.lines[i].setVisible(false);
lineChanged = true;
}
}
else {
hasVisibleLine = true;
// Line should be visible
if (!this.lines[i].isVisible()) {
this.lines[i] = this.lines[i].setVisible(true);
lineChanged = true;
}
}
if (lineChanged) {
var newOutputLineCount = this.lines[i].getViewLineCount();
this.prefixSumComputer.changeValue(i, newOutputLineCount);
}
}
if (!hasVisibleLine) {
// Cannot have everything be hidden => reveal everything!
this.setHiddenAreas([]);
}
return true;
};
SplitLinesCollection.prototype.modelPositionIsVisible = function (modelLineNumber, _modelColumn) {
if (modelLineNumber < 1 || modelLineNumber > this.lines.length) {
// invalid arguments
return false;
}
return this.lines[modelLineNumber - 1].isVisible();
};
SplitLinesCollection.prototype.setTabSize = function (newTabSize) {
if (this.tabSize === newTabSize) {
return false;
}
this.tabSize = newTabSize;
this._constructLines(/*resetHiddenAreas*/ false, null);
return true;
};
SplitLinesCollection.prototype.setWrappingSettings = function (fontInfo, wrappingStrategy, wrappingColumn, wrappingIndent) {
var equalFontInfo = this.fontInfo.equals(fontInfo);
var equalWrappingStrategy = (this.wrappingStrategy === wrappingStrategy);
var equalWrappingColumn = (this.wrappingColumn === wrappingColumn);
var equalWrappingIndent = (this.wrappingIndent === wrappingIndent);
if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent) {
return false;
}
var onlyWrappingColumnChanged = (equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent);
this.fontInfo = fontInfo;
this.wrappingStrategy = wrappingStrategy;
this.wrappingColumn = wrappingColumn;
this.wrappingIndent = wrappingIndent;
var previousLineBreaks = null;
if (onlyWrappingColumnChanged) {
previousLineBreaks = [];
for (var i = 0, len = this.lines.length; i < len; i++) {
previousLineBreaks[i] = this.lines[i].getLineBreakData();
}
}
this._constructLines(/*resetHiddenAreas*/ false, previousLineBreaks);
return true;
};
SplitLinesCollection.prototype.createLineBreaksComputer = function () {
var lineBreaksComputerFactory = (this.wrappingStrategy === 'advanced'
? this._domLineBreaksComputerFactory
: this._monospaceLineBreaksComputerFactory);
return lineBreaksComputerFactory.createLineBreaksComputer(this.fontInfo, this.tabSize, this.wrappingColumn, this.wrappingIndent);
};
SplitLinesCollection.prototype.onModelFlushed = function () {
this._constructLines(/*resetHiddenAreas*/ true, null);
};
SplitLinesCollection.prototype.onModelLinesDeleted = function (versionId, fromLineNumber, toLineNumber) {
if (versionId <= this._validModelVersionId) {
// Here we check for versionId in case the lines were reconstructed in the meantime.
// We don't want to apply stale change events on top of a newer read model state.
return null;
}
var outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1);
var outputToLineNumber = this.prefixSumComputer.getAccumulatedValue(toLineNumber - 1);
this.lines.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
this.prefixSumComputer.removeValues(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
return new viewEvents.ViewLinesDeletedEvent(outputFromLineNumber, outputToLineNumber);
};
SplitLinesCollection.prototype.onModelLinesInserted = function (versionId, fromLineNumber, _toLineNumber, lineBreaks) {
if (versionId <= this._validModelVersionId) {
// Here we check for versionId in case the lines were reconstructed in the meantime.
// We don't want to apply stale change events on top of a newer read model state.
return null;
}
var hiddenAreas = this.getHiddenAreas();
var isInHiddenArea = false;
var testPosition = new position_1.Position(fromLineNumber, 1);
for (var _i = 0, hiddenAreas_1 = hiddenAreas; _i < hiddenAreas_1.length; _i++) {
var hiddenArea = hiddenAreas_1[_i];
if (hiddenArea.containsPosition(testPosition)) {
isInHiddenArea = true;
break;
}
}
var outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1);
var totalOutputLineCount = 0;
var insertLines = [];
var insertPrefixSumValues = [];
for (var i = 0, len = lineBreaks.length; i < len; i++) {
var line = createSplitLine(lineBreaks[i], !isInHiddenArea);
insertLines.push(line);
var outputLineCount = line.getViewLineCount();
totalOutputLineCount += outputLineCount;
insertPrefixSumValues[i] = outputLineCount;
}
// TODO@Alex: use arrays.arrayInsert
this.lines = this.lines.slice(0, fromLineNumber - 1).concat(insertLines).concat(this.lines.slice(fromLineNumber - 1));
this.prefixSumComputer.insertValues(fromLineNumber - 1, insertPrefixSumValues);
return new viewEvents.ViewLinesInsertedEvent(outputFromLineNumber, outputFromLineNumber + totalOutputLineCount - 1);
};
SplitLinesCollection.prototype.onModelLineChanged = function (versionId, lineNumber, lineBreakData) {
if (versionId <= this._validModelVersionId) {
// Here we check for versionId in case the lines were reconstructed in the meantime.
// We don't want to apply stale change events on top of a newer read model state.
return [false, null, null, null];
}
var lineIndex = lineNumber - 1;
var oldOutputLineCount = this.lines[lineIndex].getViewLineCount();
var isVisible = this.lines[lineIndex].isVisible();
var line = createSplitLine(lineBreakData, isVisible);
this.lines[lineIndex] = line;
var newOutputLineCount = this.lines[lineIndex].getViewLineCount();
var lineMappingChanged = false;
var changeFrom = 0;
var changeTo = -1;
var insertFrom = 0;
var insertTo = -1;
var deleteFrom = 0;
var deleteTo = -1;
if (oldOutputLineCount > newOutputLineCount) {
changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1);
changeTo = changeFrom + newOutputLineCount - 1;
deleteFrom = changeTo + 1;
deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1;
lineMappingChanged = true;
}
else if (oldOutputLineCount < newOutputLineCount) {
changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1);
changeTo = changeFrom + oldOutputLineCount - 1;
insertFrom = changeTo + 1;
insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1;
lineMappingChanged = true;
}
else {
changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1);
changeTo = changeFrom + newOutputLineCount - 1;
}
this.prefixSumComputer.changeValue(lineIndex, newOutputLineCount);
var viewLinesChangedEvent = (changeFrom <= changeTo ? new viewEvents.ViewLinesChangedEvent(changeFrom, changeTo) : null);
var viewLinesInsertedEvent = (insertFrom <= insertTo ? new viewEvents.ViewLinesInsertedEvent(insertFrom, insertTo) : null);
var viewLinesDeletedEvent = (deleteFrom <= deleteTo ? new viewEvents.ViewLinesDeletedEvent(deleteFrom, deleteTo) : null);
return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent];
};
SplitLinesCollection.prototype.acceptVersionId = function (versionId) {
this._validModelVersionId = versionId;
if (this.lines.length === 1 && !this.lines[0].isVisible()) {
// At least one line must be visible => reset hidden areas
this.setHiddenAreas([]);
}
};
SplitLinesCollection.prototype.getViewLineCount = function () {
return this.prefixSumComputer.getTotalValue();
};
SplitLinesCollection.prototype._toValidViewLineNumber = function (viewLineNumber) {
if (viewLineNumber < 1) {
return 1;
}
var viewLineCount = this.getViewLineCount();
if (viewLineNumber > viewLineCount) {
return viewLineCount;
}
return viewLineNumber | 0;
};
SplitLinesCollection.prototype.getActiveIndentGuide = function (viewLineNumber, minLineNumber, maxLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
minLineNumber = this._toValidViewLineNumber(minLineNumber);
maxLineNumber = this._toValidViewLineNumber(maxLineNumber);
var modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, this.getViewLineMinColumn(viewLineNumber));
var modelMinPosition = this.convertViewPositionToModelPosition(minLineNumber, this.getViewLineMinColumn(minLineNumber));
var modelMaxPosition = this.convertViewPositionToModelPosition(maxLineNumber, this.getViewLineMinColumn(maxLineNumber));
var result = this.model.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber);
var viewStartPosition = this.convertModelPositionToViewPosition(result.startLineNumber, 1);
var viewEndPosition = this.convertModelPositionToViewPosition(result.endLineNumber, this.model.getLineMaxColumn(result.endLineNumber));
return {
startLineNumber: viewStartPosition.lineNumber,
endLineNumber: viewEndPosition.lineNumber,
indent: result.indent
};
};
SplitLinesCollection.prototype.getViewLinesIndentGuides = function (viewStartLineNumber, viewEndLineNumber) {
viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
var modelStart = this.convertViewPositionToModelPosition(viewStartLineNumber, this.getViewLineMinColumn(viewStartLineNumber));
var modelEnd = this.convertViewPositionToModelPosition(viewEndLineNumber, this.getViewLineMaxColumn(viewEndLineNumber));
var result = [];
var resultRepeatCount = [];
var resultRepeatOption = [];
var modelStartLineIndex = modelStart.lineNumber - 1;
var modelEndLineIndex = modelEnd.lineNumber - 1;
var reqStart = null;
for (var modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
var line = this.lines[modelLineIndex];
if (line.isVisible()) {
var viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
var viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1));
var count = viewLineEndIndex - viewLineStartIndex + 1;
var option = 0 /* BlockNone */;
if (count > 1 && line.getViewLineMinColumn(this.model, modelLineIndex + 1, viewLineEndIndex) === 1) {
// wrapped lines should block indent guides
option = (viewLineStartIndex === 0 ? 1 /* BlockSubsequent */ : 2 /* BlockAll */);
}
resultRepeatCount.push(count);
resultRepeatOption.push(option);
// merge into previous request
if (reqStart === null) {
reqStart = new position_1.Position(modelLineIndex + 1, 0);
}
}
else {
// hit invisible line => flush request
if (reqStart !== null) {
result = result.concat(this.model.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex));
reqStart = null;
}
}
}
if (reqStart !== null) {
result = result.concat(this.model.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber));
reqStart = null;
}
var viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
var viewIndents = new Array(viewLineCount);
var currIndex = 0;
for (var i = 0, len = result.length; i < len; i++) {
var value = result[i];
var count = Math.min(viewLineCount - currIndex, resultRepeatCount[i]);
var option = resultRepeatOption[i];
var blockAtIndex = void 0;
if (option === 2 /* BlockAll */) {
blockAtIndex = 0;
}
else if (option === 1 /* BlockSubsequent */) {
blockAtIndex = 1;
}
else {
blockAtIndex = count;
}
for (var j = 0; j < count; j++) {
if (j === blockAtIndex) {
value = 0;
}
viewIndents[currIndex++] = value;
}
}
return viewIndents;
};
SplitLinesCollection.prototype.getViewLineContent = function (viewLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
var lineIndex = r.index;
var remainder = r.remainder;
return this.lines[lineIndex].getViewLineContent(this.model, lineIndex + 1, remainder);
};
SplitLinesCollection.prototype.getViewLineLength = function (viewLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
var lineIndex = r.index;
var remainder = r.remainder;
return this.lines[lineIndex].getViewLineLength(this.model, lineIndex + 1, remainder);
};
SplitLinesCollection.prototype.getViewLineMinColumn = function (viewLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
var lineIndex = r.index;
var remainder = r.remainder;
return this.lines[lineIndex].getViewLineMinColumn(this.model, lineIndex + 1, remainder);
};
SplitLinesCollection.prototype.getViewLineMaxColumn = function (viewLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
var lineIndex = r.index;
var remainder = r.remainder;
return this.lines[lineIndex].getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
};
SplitLinesCollection.prototype.getViewLineData = function (viewLineNumber) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
var lineIndex = r.index;
var remainder = r.remainder;
return this.lines[lineIndex].getViewLineData(this.model, lineIndex + 1, remainder);
};
SplitLinesCollection.prototype.getViewLinesData = function (viewStartLineNumber, viewEndLineNumber, needed) {
viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
var start = this.prefixSumComputer.getIndexOf(viewStartLineNumber - 1);
var viewLineNumber = viewStartLineNumber;
var startModelLineIndex = start.index;
var startRemainder = start.remainder;
var result = [];
for (var modelLineIndex = startModelLineIndex, len = this.model.getLineCount(); modelLineIndex < len; modelLineIndex++) {
var line = this.lines[modelLineIndex];
if (!line.isVisible()) {
continue;
}
var fromViewLineIndex = (modelLineIndex === startModelLineIndex ? startRemainder : 0);
var remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex;
var lastLine = false;
if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) {
lastLine = true;
remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1;
}
var toViewLineIndex = fromViewLineIndex + remainingViewLineCount;
line.getViewLinesData(this.model, modelLineIndex + 1, fromViewLineIndex, toViewLineIndex, viewLineNumber - viewStartLineNumber, needed, result);
viewLineNumber += remainingViewLineCount;
if (lastLine) {
break;
}
}
return result;
};
SplitLinesCollection.prototype.validateViewPosition = function (viewLineNumber, viewColumn, expectedModelPosition) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
var lineIndex = r.index;
var remainder = r.remainder;
var line = this.lines[lineIndex];
var minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder);
var maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
if (viewColumn < minColumn) {
viewColumn = minColumn;
}
if (viewColumn > maxColumn) {
viewColumn = maxColumn;
}
var computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn);
var computedModelPosition = this.model.validatePosition(new position_1.Position(lineIndex + 1, computedModelColumn));
if (computedModelPosition.equals(expectedModelPosition)) {
return new position_1.Position(viewLineNumber, viewColumn);
}
return this.convertModelPositionToViewPosition(expectedModelPosition.lineNumber, expectedModelPosition.column);
};
SplitLinesCollection.prototype.validateViewRange = function (viewRange, expectedModelRange) {
var validViewStart = this.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition());
var validViewEnd = this.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition());
return new range_1.Range(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column);
};
SplitLinesCollection.prototype.convertViewPositionToModelPosition = function (viewLineNumber, viewColumn) {
viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);
var lineIndex = r.index;
var remainder = r.remainder;
var inputColumn = this.lines[lineIndex].getModelColumnOfViewPosition(remainder, viewColumn);
// console.log('out -> in ' + viewLineNumber + ',' + viewColumn + ' ===> ' + (lineIndex+1) + ',' + inputColumn);
return this.model.validatePosition(new position_1.Position(lineIndex + 1, inputColumn));
};
SplitLinesCollection.prototype.convertViewRangeToModelRange = function (viewRange) {
var start = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn);
var end = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn);
return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column);
};
SplitLinesCollection.prototype.convertModelPositionToViewPosition = function (_modelLineNumber, _modelColumn) {
var validPosition = this.model.validatePosition(new position_1.Position(_modelLineNumber, _modelColumn));
var inputLineNumber = validPosition.lineNumber;
var inputColumn = validPosition.column;
var lineIndex = inputLineNumber - 1, lineIndexChanged = false;
while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) {
lineIndex--;
lineIndexChanged = true;
}
if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) {
// Could not reach a real line
// console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + 1 + ',' + 1);
return new position_1.Position(1, 1);
}
var deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));
var r;
if (lineIndexChanged) {
r = this.lines[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));
}
else {
r = this.lines[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn);
}
// console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + r.lineNumber + ',' + r);
return r;
};
SplitLinesCollection.prototype.convertModelRangeToViewRange = function (modelRange) {
var start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn);
var end = this.convertModelPositionToViewPosition(modelRange.endLineNumber, modelRange.endColumn);
if (modelRange.startLineNumber === modelRange.endLineNumber && start.lineNumber !== end.lineNumber) {
// This is a single line range that ends up taking more lines due to wrapping
if (end.column === this.getViewLineMinColumn(end.lineNumber)) {
// the end column lands on the first column of the next line
return new range_1.Range(start.lineNumber, start.column, end.lineNumber - 1, this.getViewLineMaxColumn(end.lineNumber - 1));
}
}
return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column);
};
SplitLinesCollection.prototype._getViewLineNumberForModelPosition = function (inputLineNumber, inputColumn) {
var lineIndex = inputLineNumber - 1;
if (this.lines[lineIndex].isVisible()) {
// this model line is visible
var deltaLineNumber_1 = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));
return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber_1, inputColumn);
}
// this model line is not visible
while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) {
lineIndex--;
}
if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) {
// Could not reach a real line
return 1;
}
var deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));
return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));
};
SplitLinesCollection.prototype.getAllOverviewRulerDecorations = function (ownerId, filterOutValidation, theme) {
var decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation);
var result = new OverviewRulerDecorations();
for (var _i = 0, decorations_1 = decorations; _i < decorations_1.length; _i++) {
var decoration = decorations_1[_i];
var opts = decoration.options.overviewRuler;
var lane = opts ? opts.position : 0;
if (lane === 0) {
continue;
}
var color = opts.getColor(theme);
var viewStartLineNumber = this._getViewLineNumberForModelPosition(decoration.range.startLineNumber, decoration.range.startColumn);
var viewEndLineNumber = this._getViewLineNumberForModelPosition(decoration.range.endLineNumber, decoration.range.endColumn);
result.accept(color, viewStartLineNumber, viewEndLineNumber, lane);
}
return result.result;
};
SplitLinesCollection.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) {
var modelStart = this.convertViewPositionToModelPosition(range.startLineNumber, range.startColumn);
var modelEnd = this.convertViewPositionToModelPosition(range.endLineNumber, range.endColumn);
if (modelEnd.lineNumber - modelStart.lineNumber <= range.endLineNumber - range.startLineNumber) {
// most likely there are no hidden lines => fast path
// fetch decorations from column 1 to cover the case of wrapped lines that have whole line decorations at column 1
return this.model.getDecorationsInRange(new range_1.Range(modelStart.lineNumber, 1, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation);
}
var result = [];
var modelStartLineIndex = modelStart.lineNumber - 1;
var modelEndLineIndex = modelEnd.lineNumber - 1;
var reqStart = null;
for (var modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
var line = this.lines[modelLineIndex];
if (line.isVisible()) {
// merge into previous request
if (reqStart === null) {
reqStart = new position_1.Position(modelLineIndex + 1, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
}
}
else {
// hit invisible line => flush request
if (reqStart !== null) {
var maxLineColumn = this.model.getLineMaxColumn(modelLineIndex);
result = result.concat(this.model.getDecorationsInRange(new range_1.Range(reqStart.lineNumber, reqStart.column, modelLineIndex, maxLineColumn), ownerId, filterOutValidation));
reqStart = null;
}
}
}
if (reqStart !== null) {
result = result.concat(this.model.getDecorationsInRange(new range_1.Range(reqStart.lineNumber, reqStart.column, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation));
reqStart = null;
}
result.sort(function (a, b) {
var res = range_1.Range.compareRangesUsingStarts(a.range, b.range);
if (res === 0) {
if (a.id < b.id) {
return -1;
}
if (a.id > b.id) {
return 1;
}
return 0;
}
return res;
});
// Eliminate duplicate decorations that might have intersected our visible ranges multiple times
var finalResult = [], finalResultLen = 0;
var prevDecId = null;
for (var _i = 0, result_1 = result; _i < result_1.length; _i++) {
var dec = result_1[_i];
var decId = dec.id;
if (prevDecId === decId) {
// skip
continue;
}
prevDecId = decId;
finalResult[finalResultLen++] = dec;
}
return finalResult;
};
return SplitLinesCollection;
}());
exports.SplitLinesCollection = SplitLinesCollection;
var VisibleIdentitySplitLine = /** @class */ (function () {
function VisibleIdentitySplitLine() {
}
VisibleIdentitySplitLine.prototype.isVisible = function () {
return true;
};
VisibleIdentitySplitLine.prototype.setVisible = function (isVisible) {
if (isVisible) {
return this;
}
return InvisibleIdentitySplitLine.INSTANCE;
};
VisibleIdentitySplitLine.prototype.getLineBreakData = function () {
return null;
};
VisibleIdentitySplitLine.prototype.getViewLineCount = function () {
return 1;
};
VisibleIdentitySplitLine.prototype.getViewLineContent = function (model, modelLineNumber, _outputLineIndex) {
return model.getLineContent(modelLineNumber);
};
VisibleIdentitySplitLine.prototype.getViewLineLength = function (model, modelLineNumber, _outputLineIndex) {
return model.getLineLength(modelLineNumber);
};
VisibleIdentitySplitLine.prototype.getViewLineMinColumn = function (model, modelLineNumber, _outputLineIndex) {
return model.getLineMinColumn(modelLineNumber);
};
VisibleIdentitySplitLine.prototype.getViewLineMaxColumn = function (model, modelLineNumber, _outputLineIndex) {
return model.getLineMaxColumn(modelLineNumber);
};
VisibleIdentitySplitLine.prototype.getViewLineData = function (model, modelLineNumber, _outputLineIndex) {
var lineTokens = model.getLineTokens(modelLineNumber);
var lineContent = lineTokens.getLineContent();
return new viewModel_1.ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate());
};
VisibleIdentitySplitLine.prototype.getViewLinesData = function (model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result) {
if (!needed[globalStartIndex]) {
result[globalStartIndex] = null;
return;
}
result[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0);
};
VisibleIdentitySplitLine.prototype.getModelColumnOfViewPosition = function (_outputLineIndex, outputColumn) {
return outputColumn;
};
VisibleIdentitySplitLine.prototype.getViewPositionOfModelPosition = function (deltaLineNumber, inputColumn) {
return new position_1.Position(deltaLineNumber, inputColumn);
};
VisibleIdentitySplitLine.prototype.getViewLineNumberOfModelPosition = function (deltaLineNumber, _inputColumn) {
return deltaLineNumber;
};
VisibleIdentitySplitLine.INSTANCE = new VisibleIdentitySplitLine();
return VisibleIdentitySplitLine;
}());
var InvisibleIdentitySplitLine = /** @class */ (function () {
function InvisibleIdentitySplitLine() {
}
InvisibleIdentitySplitLine.prototype.isVisible = function () {
return false;
};
InvisibleIdentitySplitLine.prototype.setVisible = function (isVisible) {
if (!isVisible) {
return this;
}
return VisibleIdentitySplitLine.INSTANCE;
};
InvisibleIdentitySplitLine.prototype.getLineBreakData = function () {
return null;
};
InvisibleIdentitySplitLine.prototype.getViewLineCount = function () {
return 0;
};
InvisibleIdentitySplitLine.prototype.getViewLineContent = function (_model, _modelLineNumber, _outputLineIndex) {
throw new Error('Not supported');
};
InvisibleIdentitySplitLine.prototype.getViewLineLength = function (_model, _modelLineNumber, _outputLineIndex) {
throw new Error('Not supported');
};
InvisibleIdentitySplitLine.prototype.getViewLineMinColumn = function (_model, _modelLineNumber, _outputLineIndex) {
throw new Error('Not supported');
};
InvisibleIdentitySplitLine.prototype.getViewLineMaxColumn = function (_model, _modelLineNumber, _outputLineIndex) {
throw new Error('Not supported');
};
InvisibleIdentitySplitLine.prototype.getViewLineData = function (_model, _modelLineNumber, _outputLineIndex) {
throw new Error('Not supported');
};
InvisibleIdentitySplitLine.prototype.getViewLinesData = function (_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) {
throw new Error('Not supported');
};
InvisibleIdentitySplitLine.prototype.getModelColumnOfViewPosition = function (_outputLineIndex, _outputColumn) {
throw new Error('Not supported');
};
InvisibleIdentitySplitLine.prototype.getViewPositionOfModelPosition = function (_deltaLineNumber, _inputColumn) {
throw new Error('Not supported');
};
InvisibleIdentitySplitLine.prototype.getViewLineNumberOfModelPosition = function (_deltaLineNumber, _inputColumn) {
throw new Error('Not supported');
};
InvisibleIdentitySplitLine.INSTANCE = new InvisibleIdentitySplitLine();
return InvisibleIdentitySplitLine;
}());
var SplitLine = /** @class */ (function () {
function SplitLine(lineBreakData, isVisible) {
this._lineBreakData = lineBreakData;
this._isVisible = isVisible;
}
SplitLine.prototype.isVisible = function () {
return this._isVisible;
};
SplitLine.prototype.setVisible = function (isVisible) {
this._isVisible = isVisible;
return this;
};
SplitLine.prototype.getLineBreakData = function () {
return this._lineBreakData;
};
SplitLine.prototype.getViewLineCount = function () {
if (!this._isVisible) {
return 0;
}
return this._lineBreakData.breakOffsets.length;
};
SplitLine.prototype.getInputStartOffsetOfOutputLineIndex = function (outputLineIndex) {
return LineBreakData.getInputOffsetOfOutputPosition(this._lineBreakData.breakOffsets, outputLineIndex, 0);
};
SplitLine.prototype.getInputEndOffsetOfOutputLineIndex = function (model, modelLineNumber, outputLineIndex) {
if (outputLineIndex + 1 === this._lineBreakData.breakOffsets.length) {
return model.getLineMaxColumn(modelLineNumber) - 1;
}
return LineBreakData.getInputOffsetOfOutputPosition(this._lineBreakData.breakOffsets, outputLineIndex + 1, 0);
};
SplitLine.prototype.getViewLineContent = function (model, modelLineNumber, outputLineIndex) {
if (!this._isVisible) {
throw new Error('Not supported');
}
var startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);
var endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);
var r = model.getValueInRange({
startLineNumber: modelLineNumber,
startColumn: startOffset + 1,
endLineNumber: modelLineNumber,
endColumn: endOffset + 1
});
if (outputLineIndex > 0) {
r = spaces(this._lineBreakData.wrappedTextIndentLength) + r;
}
return r;
};
SplitLine.prototype.getViewLineLength = function (model, modelLineNumber, outputLineIndex) {
if (!this._isVisible) {
throw new Error('Not supported');
}
var startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);
var endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);
var r = endOffset - startOffset;
if (outputLineIndex > 0) {
r = this._lineBreakData.wrappedTextIndentLength + r;
}
return r;
};
SplitLine.prototype.getViewLineMinColumn = function (_model, _modelLineNumber, outputLineIndex) {
if (!this._isVisible) {
throw new Error('Not supported');
}
if (outputLineIndex > 0) {
return this._lineBreakData.wrappedTextIndentLength + 1;
}
return 1;
};
SplitLine.prototype.getViewLineMaxColumn = function (model, modelLineNumber, outputLineIndex) {
if (!this._isVisible) {
throw new Error('Not supported');
}
return this.getViewLineContent(model, modelLineNumber, outputLineIndex).length + 1;
};
SplitLine.prototype.getViewLineData = function (model, modelLineNumber, outputLineIndex) {
if (!this._isVisible) {
throw new Error('Not supported');
}
var startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);
var endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);
var lineContent = model.getValueInRange({
startLineNumber: modelLineNumber,
startColumn: startOffset + 1,
endLineNumber: modelLineNumber,
endColumn: endOffset + 1
});
if (outputLineIndex > 0) {
lineContent = spaces(this._lineBreakData.wrappedTextIndentLength) + lineContent;
}
var minColumn = (outputLineIndex > 0 ? this._lineBreakData.wrappedTextIndentLength + 1 : 1);
var maxColumn = lineContent.length + 1;
var continuesWithWrappedLine = (outputLineIndex + 1 < this.getViewLineCount());
var deltaStartIndex = 0;
if (outputLineIndex > 0) {
deltaStartIndex = this._lineBreakData.wrappedTextIndentLength;
}
var lineTokens = model.getLineTokens(modelLineNumber);
var startVisibleColumn = (outputLineIndex === 0 ? 0 : this._lineBreakData.breakOffsetsVisibleColumn[outputLineIndex - 1]);
return new viewModel_1.ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, lineTokens.sliceAndInflate(startOffset, endOffset, deltaStartIndex));
};
SplitLine.prototype.getViewLinesData = function (model, modelLineNumber, fromOuputLineIndex, toOutputLineIndex, globalStartIndex, needed, result) {
if (!this._isVisible) {
throw new Error('Not supported');
}
for (var outputLineIndex = fromOuputLineIndex; outputLineIndex < toOutputLineIndex; outputLineIndex++) {
var globalIndex = globalStartIndex + outputLineIndex - fromOuputLineIndex;
if (!needed[globalIndex]) {
result[globalIndex] = null;
continue;
}
result[globalIndex] = this.getViewLineData(model, modelLineNumber, outputLineIndex);
}
};
SplitLine.prototype.getModelColumnOfViewPosition = function (outputLineIndex, outputColumn) {
if (!this._isVisible) {
throw new Error('Not supported');
}
var adjustedColumn = outputColumn - 1;
if (outputLineIndex > 0) {
if (adjustedColumn < this._lineBreakData.wrappedTextIndentLength) {
adjustedColumn = 0;
}
else {
adjustedColumn -= this._lineBreakData.wrappedTextIndentLength;
}
}
return LineBreakData.getInputOffsetOfOutputPosition(this._lineBreakData.breakOffsets, outputLineIndex, adjustedColumn) + 1;
};
SplitLine.prototype.getViewPositionOfModelPosition = function (deltaLineNumber, inputColumn) {
if (!this._isVisible) {
throw new Error('Not supported');
}
var r = LineBreakData.getOutputPositionOfInputOffset(this._lineBreakData.breakOffsets, inputColumn - 1);
var outputLineIndex = r.outputLineIndex;
var outputColumn = r.outputOffset + 1;
if (outputLineIndex > 0) {
outputColumn += this._lineBreakData.wrappedTextIndentLength;
}
// console.log('in -> out ' + deltaLineNumber + ',' + inputColumn + ' ===> ' + (deltaLineNumber+outputLineIndex) + ',' + outputColumn);
return new position_1.Position(deltaLineNumber + outputLineIndex, outputColumn);
};
SplitLine.prototype.getViewLineNumberOfModelPosition = function (deltaLineNumber, inputColumn) {
if (!this._isVisible) {
throw new Error('Not supported');
}
var r = LineBreakData.getOutputPositionOfInputOffset(this._lineBreakData.breakOffsets, inputColumn - 1);
return (deltaLineNumber + r.outputLineIndex);
};
return SplitLine;
}());
exports.SplitLine = SplitLine;
var _spaces = [''];
function spaces(count) {
if (count >= _spaces.length) {
for (var i = 1; i <= count; i++) {
_spaces[i] = _makeSpaces(i);
}
}
return _spaces[count];
}
function _makeSpaces(count) {
return new Array(count + 1).join(' ');
}
function createSplitLine(lineBreakData, isVisible) {
if (lineBreakData === null) {
// No mapping needed
if (isVisible) {
return VisibleIdentitySplitLine.INSTANCE;
}
return InvisibleIdentitySplitLine.INSTANCE;
}
else {
return new SplitLine(lineBreakData, isVisible);
}
}
var IdentityCoordinatesConverter = /** @class */ (function () {
function IdentityCoordinatesConverter(lines) {
this._lines = lines;
}
IdentityCoordinatesConverter.prototype._validPosition = function (pos) {
return this._lines.model.validatePosition(pos);
};
IdentityCoordinatesConverter.prototype._validRange = function (range) {
return this._lines.model.validateRange(range);
};
// View -> Model conversion and related methods
IdentityCoordinatesConverter.prototype.convertViewPositionToModelPosition = function (viewPosition) {
return this._validPosition(viewPosition);
};
IdentityCoordinatesConverter.prototype.convertViewRangeToModelRange = function (viewRange) {
return this._validRange(viewRange);
};
IdentityCoordinatesConverter.prototype.validateViewPosition = function (_viewPosition, expectedModelPosition) {
return this._validPosition(expectedModelPosition);
};
IdentityCoordinatesConverter.prototype.validateViewRange = function (_viewRange, expectedModelRange) {
return this._validRange(expectedModelRange);
};
// Model -> View conversion and related methods
IdentityCoordinatesConverter.prototype.convertModelPositionToViewPosition = function (modelPosition) {
return this._validPosition(modelPosition);
};
IdentityCoordinatesConverter.prototype.convertModelRangeToViewRange = function (modelRange) {
return this._validRange(modelRange);
};
IdentityCoordinatesConverter.prototype.modelPositionIsVisible = function (modelPosition) {
var lineCount = this._lines.model.getLineCount();
if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) {
// invalid arguments
return false;
}
return true;
};
return IdentityCoordinatesConverter;
}());
exports.IdentityCoordinatesConverter = IdentityCoordinatesConverter;
var IdentityLinesCollection = /** @class */ (function () {
function IdentityLinesCollection(model) {
this.model = model;
}
IdentityLinesCollection.prototype.dispose = function () {
};
IdentityLinesCollection.prototype.createCoordinatesConverter = function () {
return new IdentityCoordinatesConverter(this);
};
IdentityLinesCollection.prototype.getHiddenAreas = function () {
return [];
};
IdentityLinesCollection.prototype.setHiddenAreas = function (_ranges) {
return false;
};
IdentityLinesCollection.prototype.setTabSize = function (_newTabSize) {
return false;
};
IdentityLinesCollection.prototype.setWrappingSettings = function (_fontInfo, _wrappingStrategy, _wrappingColumn, _wrappingIndent) {
return false;
};
IdentityLinesCollection.prototype.createLineBreaksComputer = function () {
var result = [];
return {
addRequest: function (lineText, previousLineBreakData) {
result.push(null);
},
finalize: function () {
return result;
}
};
};
IdentityLinesCollection.prototype.onModelFlushed = function () {
};
IdentityLinesCollection.prototype.onModelLinesDeleted = function (_versionId, fromLineNumber, toLineNumber) {
return new viewEvents.ViewLinesDeletedEvent(fromLineNumber, toLineNumber);
};
IdentityLinesCollection.prototype.onModelLinesInserted = function (_versionId, fromLineNumber, toLineNumber, lineBreaks) {
return new viewEvents.ViewLinesInsertedEvent(fromLineNumber, toLineNumber);
};
IdentityLinesCollection.prototype.onModelLineChanged = function (_versionId, lineNumber, lineBreakData) {
return [false, new viewEvents.ViewLinesChangedEvent(lineNumber, lineNumber), null, null];
};
IdentityLinesCollection.prototype.acceptVersionId = function (_versionId) {
};
IdentityLinesCollection.prototype.getViewLineCount = function () {
return this.model.getLineCount();
};
IdentityLinesCollection.prototype.getActiveIndentGuide = function (viewLineNumber, _minLineNumber, _maxLineNumber) {
return {
startLineNumber: viewLineNumber,
endLineNumber: viewLineNumber,
indent: 0
};
};
IdentityLinesCollection.prototype.getViewLinesIndentGuides = function (viewStartLineNumber, viewEndLineNumber) {
var viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
var result = new Array(viewLineCount);
for (var i = 0; i < viewLineCount; i++) {
result[i] = 0;
}
return result;
};
IdentityLinesCollection.prototype.getViewLineContent = function (viewLineNumber) {
return this.model.getLineContent(viewLineNumber);
};
IdentityLinesCollection.prototype.getViewLineLength = function (viewLineNumber) {
return this.model.getLineLength(viewLineNumber);
};
IdentityLinesCollection.prototype.getViewLineMinColumn = function (viewLineNumber) {
return this.model.getLineMinColumn(viewLineNumber);
};
IdentityLinesCollection.prototype.getViewLineMaxColumn = function (viewLineNumber) {
return this.model.getLineMaxColumn(viewLineNumber);
};
IdentityLinesCollection.prototype.getViewLineData = function (viewLineNumber) {
var lineTokens = this.model.getLineTokens(viewLineNumber);
var lineContent = lineTokens.getLineContent();
return new viewModel_1.ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate());
};
IdentityLinesCollection.prototype.getViewLinesData = function (viewStartLineNumber, viewEndLineNumber, needed) {
var lineCount = this.model.getLineCount();
viewStartLineNumber = Math.min(Math.max(1, viewStartLineNumber), lineCount);
viewEndLineNumber = Math.min(Math.max(1, viewEndLineNumber), lineCount);
var result = [];
for (var lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) {
var idx = lineNumber - viewStartLineNumber;
if (!needed[idx]) {
result[idx] = null;
}
result[idx] = this.getViewLineData(lineNumber);
}
return result;
};
IdentityLinesCollection.prototype.getAllOverviewRulerDecorations = function (ownerId, filterOutValidation, theme) {
var decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation);
var result = new OverviewRulerDecorations();
for (var _i = 0, decorations_2 = decorations; _i < decorations_2.length; _i++) {
var decoration = decorations_2[_i];
var opts = decoration.options.overviewRuler;
var lane = opts ? opts.position : 0;
if (lane === 0) {
continue;
}
var color = opts.getColor(theme);
var viewStartLineNumber = decoration.range.startLineNumber;
var viewEndLineNumber = decoration.range.endLineNumber;
result.accept(color, viewStartLineNumber, viewEndLineNumber, lane);
}
return result.result;
};
IdentityLinesCollection.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) {
return this.model.getDecorationsInRange(range, ownerId, filterOutValidation);
};
return IdentityLinesCollection;
}());
exports.IdentityLinesCollection = IdentityLinesCollection;
var OverviewRulerDecorations = /** @class */ (function () {
function OverviewRulerDecorations() {
this.result = Object.create(null);
}
OverviewRulerDecorations.prototype.accept = function (color, startLineNumber, endLineNumber, lane) {
var prev = this.result[color];
if (prev) {
var prevLane = prev[prev.length - 3];
var prevEndLineNumber = prev[prev.length - 1];
if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) {
// merge into prev
if (endLineNumber > prevEndLineNumber) {
prev[prev.length - 1] = endLineNumber;
}
return;
}
// push
prev.push(lane, startLineNumber, endLineNumber);
}
else {
this.result[color] = [lane, startLineNumber, endLineNumber];
}
};
return OverviewRulerDecorations;
}());
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[487/*vs/editor/common/viewModel/monospaceLineBreaksComputer*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,79/*vs/editor/common/core/characterClassifier*/,161/*vs/editor/common/viewModel/splitLinesCollection*/]), function (require, exports, strings, characterClassifier_1, splitLinesCollection_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var WrappingCharacterClassifier = /** @class */ (function (_super) {
__extends(WrappingCharacterClassifier, _super);
function WrappingCharacterClassifier(BREAK_BEFORE, BREAK_AFTER) {
var _this = _super.call(this, 0 /* NONE */) || this;
for (var i = 0; i < BREAK_BEFORE.length; i++) {
_this.set(BREAK_BEFORE.charCodeAt(i), 1 /* BREAK_BEFORE */);
}
for (var i = 0; i < BREAK_AFTER.length; i++) {
_this.set(BREAK_AFTER.charCodeAt(i), 2 /* BREAK_AFTER */);
}
return _this;
}
WrappingCharacterClassifier.prototype.get = function (charCode) {
if (charCode >= 0 && charCode < 256) {
return this._asciiMap[charCode];
}
else {
// Initialize CharacterClass.BREAK_IDEOGRAPHIC for these Unicode ranges:
// 1. CJK Unified Ideographs (0x4E00 -- 0x9FFF)
// 2. CJK Unified Ideographs Extension A (0x3400 -- 0x4DBF)
// 3. Hiragana and Katakana (0x3040 -- 0x30FF)
if ((charCode >= 0x3040 && charCode <= 0x30FF)
|| (charCode >= 0x3400 && charCode <= 0x4DBF)
|| (charCode >= 0x4E00 && charCode <= 0x9FFF)) {
return 3 /* BREAK_IDEOGRAPHIC */;
}
return (this._map.get(charCode) || this._defaultValue);
}
};
return WrappingCharacterClassifier;
}(characterClassifier_1.CharacterClassifier));
var arrPool1 = [];
var arrPool2 = [];
var MonospaceLineBreaksComputerFactory = /** @class */ (function () {
function MonospaceLineBreaksComputerFactory(breakBeforeChars, breakAfterChars) {
this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars);
}
MonospaceLineBreaksComputerFactory.create = function (options) {
return new MonospaceLineBreaksComputerFactory(options.get(99 /* wordWrapBreakBeforeCharacters */), options.get(98 /* wordWrapBreakAfterCharacters */));
};
MonospaceLineBreaksComputerFactory.prototype.createLineBreaksComputer = function (fontInfo, tabSize, wrappingColumn, wrappingIndent) {
var _this = this;
tabSize = tabSize | 0; //@perf
wrappingColumn = +wrappingColumn; //@perf
var requests = [];
var previousBreakingData = [];
return {
addRequest: function (lineText, previousLineBreakData) {
requests.push(lineText);
previousBreakingData.push(previousLineBreakData);
},
finalize: function () {
var columnsForFullWidthChar = fontInfo.typicalFullwidthCharacterWidth / fontInfo.typicalHalfwidthCharacterWidth; //@perf
var result = [];
for (var i = 0, len = requests.length; i < len; i++) {
var previousLineBreakData = previousBreakingData[i];
if (previousLineBreakData) {
result[i] = createLineBreaksFromPreviousLineBreaks(_this.classifier, previousLineBreakData, requests[i], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent);
}
else {
result[i] = createLineBreaks(_this.classifier, requests[i], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent);
}
}
arrPool1.length = 0;
arrPool2.length = 0;
return result;
}
};
};
return MonospaceLineBreaksComputerFactory;
}());
exports.MonospaceLineBreaksComputerFactory = MonospaceLineBreaksComputerFactory;
function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
if (firstLineBreakColumn === -1) {
return null;
}
var len = lineText.length;
if (len <= 1) {
return null;
}
var prevBreakingOffsets = previousBreakingData.breakOffsets;
var prevBreakingOffsetsVisibleColumn = previousBreakingData.breakOffsetsVisibleColumn;
var wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
var wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
var breakingOffsets = arrPool1;
var breakingOffsetsVisibleColumn = arrPool2;
var breakingOffsetsCount = 0;
var breakingColumn = firstLineBreakColumn;
var prevLen = prevBreakingOffsets.length;
var prevIndex = 0;
if (prevIndex >= 0) {
var bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
while (prevIndex + 1 < prevLen) {
var distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
if (distance >= bestDistance) {
break;
}
bestDistance = distance;
prevIndex++;
}
}
while (prevIndex < prevLen) {
// Allow for prevIndex to be -1 (for the case where we hit a tab when walking backwards from the first break)
var prevBreakOffset = prevIndex < 0 ? 0 : prevBreakingOffsets[prevIndex];
var prevBreakoffsetVisibleColumn = prevIndex < 0 ? 0 : prevBreakingOffsetsVisibleColumn[prevIndex];
var breakOffset = 0;
var breakOffsetVisibleColumn = 0;
var forcedBreakOffset = 0;
var forcedBreakOffsetVisibleColumn = 0;
// initially, we search as much as possible to the right (if it fits)
if (prevBreakoffsetVisibleColumn <= breakingColumn) {
var visibleColumn = prevBreakoffsetVisibleColumn;
var prevCharCode = lineText.charCodeAt(prevBreakOffset - 1);
var prevCharCodeClass = classifier.get(prevCharCode);
var entireLineFits = true;
for (var i = prevBreakOffset; i < len; i++) {
var charStartOffset = i;
var charCode = lineText.charCodeAt(i);
var charCodeClass = void 0;
var charWidth = void 0;
if (strings.isHighSurrogate(charCode)) {
// A surrogate pair must always be considered as a single unit, so it is never to be broken
i++;
charCodeClass = 0 /* NONE */;
charWidth = 2;
}
else {
charCodeClass = classifier.get(charCode);
charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
}
if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
breakOffset = charStartOffset;
breakOffsetVisibleColumn = visibleColumn;
}
visibleColumn += charWidth;
// check if adding character at `i` will go over the breaking column
if (visibleColumn > breakingColumn) {
// We need to break at least before character at `i`:
forcedBreakOffset = charStartOffset;
forcedBreakOffsetVisibleColumn = visibleColumn - charWidth;
if (visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
// Cannot break at `breakOffset` => reset it if it was set
breakOffset = 0;
}
entireLineFits = false;
break;
}
prevCharCode = charCode;
prevCharCodeClass = charCodeClass;
}
if (entireLineFits) {
// there is no more need to break => stop the outer loop!
if (breakingOffsetsCount > 0) {
// Add last segment
breakingOffsets[breakingOffsetsCount] = prevBreakingOffsets[prevBreakingOffsets.length - 1];
breakingOffsetsVisibleColumn[breakingOffsetsCount] = prevBreakingOffsetsVisibleColumn[prevBreakingOffsets.length - 1];
breakingOffsetsCount++;
}
break;
}
}
if (breakOffset === 0) {
// must search left
var visibleColumn = prevBreakoffsetVisibleColumn;
var charCode = lineText.charCodeAt(prevBreakOffset);
var charCodeClass = classifier.get(charCode);
var hitATabCharacter = false;
for (var i = prevBreakOffset - 1; i >= 0; i--) {
var charStartOffset = i + 1;
var prevCharCode = lineText.charCodeAt(i);
if (prevCharCode === 9 /* Tab */) {
// cannot determine the width of a tab when going backwards, so we must go forwards
hitATabCharacter = true;
break;
}
var prevCharCodeClass = void 0;
var prevCharWidth = void 0;
if (strings.isLowSurrogate(prevCharCode)) {
// A surrogate pair must always be considered as a single unit, so it is never to be broken
i--;
prevCharCodeClass = 0 /* NONE */;
prevCharWidth = 2;
}
else {
prevCharCodeClass = classifier.get(prevCharCode);
prevCharWidth = (strings.isFullWidthCharacter(prevCharCode) ? columnsForFullWidthChar : 1);
}
if (visibleColumn <= breakingColumn) {
if (forcedBreakOffset === 0) {
forcedBreakOffset = charStartOffset;
forcedBreakOffsetVisibleColumn = visibleColumn;
}
if (visibleColumn <= breakingColumn - wrappedLineBreakColumn) {
// went too far!
break;
}
if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
breakOffset = charStartOffset;
breakOffsetVisibleColumn = visibleColumn;
break;
}
}
visibleColumn -= prevCharWidth;
charCode = prevCharCode;
charCodeClass = prevCharCodeClass;
}
if (breakOffset !== 0) {
var remainingWidthOfNextLine = wrappedLineBreakColumn - (forcedBreakOffsetVisibleColumn - breakOffsetVisibleColumn);
if (remainingWidthOfNextLine <= tabSize) {
var charCodeAtForcedBreakOffset = lineText.charCodeAt(forcedBreakOffset);
var charWidth = void 0;
if (strings.isHighSurrogate(charCodeAtForcedBreakOffset)) {
// A surrogate pair must always be considered as a single unit, so it is never to be broken
charWidth = 2;
}
else {
charWidth = computeCharWidth(charCodeAtForcedBreakOffset, forcedBreakOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
}
if (remainingWidthOfNextLine - charWidth < 0) {
// it is not worth it to break at breakOffset, it just introduces an extra needless line!
breakOffset = 0;
}
}
}
if (hitATabCharacter) {
// cannot determine the width of a tab when going backwards, so we must go forwards from the previous break
prevIndex--;
continue;
}
}
if (breakOffset === 0) {
// Could not find a good breaking point
breakOffset = forcedBreakOffset;
breakOffsetVisibleColumn = forcedBreakOffsetVisibleColumn;
}
breakingOffsets[breakingOffsetsCount] = breakOffset;
breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
breakingOffsetsCount++;
breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
while (prevIndex < 0 || (prevIndex < prevLen && prevBreakingOffsetsVisibleColumn[prevIndex] < breakOffsetVisibleColumn)) {
prevIndex++;
}
var bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
while (prevIndex + 1 < prevLen) {
var distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
if (distance >= bestDistance) {
break;
}
bestDistance = distance;
prevIndex++;
}
}
if (breakingOffsetsCount === 0) {
return null;
}
// Doing here some object reuse which ends up helping a huge deal with GC pauses!
breakingOffsets.length = breakingOffsetsCount;
breakingOffsetsVisibleColumn.length = breakingOffsetsCount;
arrPool1 = previousBreakingData.breakOffsets;
arrPool2 = previousBreakingData.breakOffsetsVisibleColumn;
previousBreakingData.breakOffsets = breakingOffsets;
previousBreakingData.breakOffsetsVisibleColumn = breakingOffsetsVisibleColumn;
previousBreakingData.wrappedTextIndentLength = wrappedTextIndentLength;
return previousBreakingData;
}
function createLineBreaks(classifier, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
if (firstLineBreakColumn === -1) {
return null;
}
var len = lineText.length;
if (len <= 1) {
return null;
}
var wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
var wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
var breakingOffsets = [];
var breakingOffsetsVisibleColumn = [];
var breakingOffsetsCount = 0;
var breakOffset = 0;
var breakOffsetVisibleColumn = 0;
var breakingColumn = firstLineBreakColumn;
var prevCharCode = lineText.charCodeAt(0);
var prevCharCodeClass = classifier.get(prevCharCode);
var visibleColumn = computeCharWidth(prevCharCode, 0, tabSize, columnsForFullWidthChar);
var startOffset = 1;
if (strings.isHighSurrogate(prevCharCode)) {
// A surrogate pair must always be considered as a single unit, so it is never to be broken
visibleColumn += 1;
prevCharCode = lineText.charCodeAt(1);
prevCharCodeClass = classifier.get(prevCharCode);
startOffset++;
}
for (var i = startOffset; i < len; i++) {
var charStartOffset = i;
var charCode = lineText.charCodeAt(i);
var charCodeClass = void 0;
var charWidth = void 0;
if (strings.isHighSurrogate(charCode)) {
// A surrogate pair must always be considered as a single unit, so it is never to be broken
i++;
charCodeClass = 0 /* NONE */;
charWidth = 2;
}
else {
charCodeClass = classifier.get(charCode);
charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
}
if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
breakOffset = charStartOffset;
breakOffsetVisibleColumn = visibleColumn;
}
visibleColumn += charWidth;
// check if adding character at `i` will go over the breaking column
if (visibleColumn > breakingColumn) {
// We need to break at least before character at `i`:
if (breakOffset === 0 || visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
// Cannot break at `breakOffset`, must break at `i`
breakOffset = charStartOffset;
breakOffsetVisibleColumn = visibleColumn - charWidth;
}
breakingOffsets[breakingOffsetsCount] = breakOffset;
breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
breakingOffsetsCount++;
breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
breakOffset = 0;
}
prevCharCode = charCode;
prevCharCodeClass = charCodeClass;
}
if (breakingOffsetsCount === 0) {
return null;
}
// Add last segment
breakingOffsets[breakingOffsetsCount] = len;
breakingOffsetsVisibleColumn[breakingOffsetsCount] = visibleColumn;
return new splitLinesCollection_1.LineBreakData(breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength);
}
function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) {
if (charCode === 9 /* Tab */) {
return (tabSize - (visibleColumn % tabSize));
}
if (strings.isFullWidthCharacter(charCode)) {
return columnsForFullWidthChar;
}
return 1;
}
function tabCharacterWidth(visibleColumn, tabSize) {
return (tabSize - (visibleColumn % tabSize));
}
/**
* Kinsoku Shori : Don't break after a leading character, like an open bracket
* Kinsoku Shori : Don't break before a trailing character, like a period
*/
function canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass) {
return (charCode !== 32 /* Space */
&& ((prevCharCodeClass === 2 /* BREAK_AFTER */)
|| (prevCharCodeClass === 3 /* BREAK_IDEOGRAPHIC */ && charCodeClass !== 2 /* BREAK_AFTER */)
|| (charCodeClass === 1 /* BREAK_BEFORE */)
|| (charCodeClass === 3 /* BREAK_IDEOGRAPHIC */ && prevCharCodeClass !== 1 /* BREAK_BEFORE */)));
}
function computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
var wrappedTextIndentLength = 0;
if (wrappingIndent !== 0 /* None */) {
var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineText);
if (firstNonWhitespaceIndex !== -1) {
// Track existing indent
for (var i = 0; i < firstNonWhitespaceIndex; i++) {
var charWidth = (lineText.charCodeAt(i) === 9 /* Tab */ ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1);
wrappedTextIndentLength += charWidth;
}
// Increase indent of continuation lines, if desired
var numberOfAdditionalTabs = (wrappingIndent === 3 /* DeepIndent */ ? 2 : wrappingIndent === 2 /* Indent */ ? 1 : 0);
for (var i = 0; i < numberOfAdditionalTabs; i++) {
var charWidth = tabCharacterWidth(wrappedTextIndentLength, tabSize);
wrappedTextIndentLength += charWidth;
}
// Force sticking to beginning of line if no character would fit except for the indentation
if (wrappedTextIndentLength + columnsForFullWidthChar > firstLineBreakColumn) {
wrappedTextIndentLength = 0;
}
}
}
return wrappedTextIndentLength;
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[488/*vs/editor/common/viewModel/viewModelImpl*/], __M([0/*require*/,1/*exports*/,27/*vs/base/common/color*/,5/*vs/base/common/strings*/,33/*vs/editor/common/config/editorOptions*/,13/*vs/editor/common/core/position*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,214/*vs/editor/common/modes/textToHtmlTokenizer*/,215/*vs/editor/common/viewModel/minimapTokensColorTracker*/,81/*vs/editor/common/view/viewEvents*/,373/*vs/editor/common/viewLayout/viewLayout*/,161/*vs/editor/common/viewModel/splitLinesCollection*/,69/*vs/editor/common/viewModel/viewModel*/,424/*vs/editor/common/viewModel/viewModelDecorations*/,15/*vs/base/common/async*/,16/*vs/base/common/platform*/]), function (require, exports, color_1, strings, editorOptions_1, position_1, range_1, modes_1, textToHtmlTokenizer_1, minimapTokensColorTracker_1, viewEvents, viewLayout_1, splitLinesCollection_1, viewModel_1, viewModelDecorations_1, async_1, platform) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var USE_IDENTITY_LINES_COLLECTION = true;
var ViewModel = /** @class */ (function (_super) {
__extends(ViewModel, _super);
function ViewModel(editorId, configuration, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, scheduleAtNextAnimationFrame) {
var _this = _super.call(this) || this;
_this.editorId = editorId;
_this.configuration = configuration;
_this.model = model;
_this._tokenizeViewportSoon = _this._register(new async_1.RunOnceScheduler(function () { return _this.tokenizeViewport(); }, 50));
_this.hasFocus = false;
_this.viewportStartLine = -1;
_this.viewportStartLineTrackedRange = null;
_this.viewportStartLineDelta = 0;
if (USE_IDENTITY_LINES_COLLECTION && _this.model.isTooLargeForTokenization()) {
_this.lines = new splitLinesCollection_1.IdentityLinesCollection(_this.model);
}
else {
var options = _this.configuration.options;
var fontInfo = options.get(34 /* fontInfo */);
var wrappingStrategy = options.get(103 /* wrappingStrategy */);
var wrappingInfo = options.get(108 /* wrappingInfo */);
var wrappingIndent = options.get(102 /* wrappingIndent */);
_this.lines = new splitLinesCollection_1.SplitLinesCollection(_this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, _this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent);
}
_this.coordinatesConverter = _this.lines.createCoordinatesConverter();
_this.viewLayout = _this._register(new viewLayout_1.ViewLayout(_this.configuration, _this.getLineCount(), scheduleAtNextAnimationFrame));
_this._register(_this.viewLayout.onDidScroll(function (e) {
if (e.scrollTopChanged) {
_this._tokenizeViewportSoon.schedule();
}
try {
var eventsCollector = _this._beginEmit();
eventsCollector.emit(new viewEvents.ViewScrollChangedEvent(e));
}
finally {
_this._endEmit();
}
}));
_this._register(_this.viewLayout.onDidContentSizeChange(function (e) {
try {
var eventsCollector = _this._beginEmit();
eventsCollector.emit(new viewEvents.ViewContentSizeChangedEvent(e));
}
finally {
_this._endEmit();
}
}));
_this.decorations = new viewModelDecorations_1.ViewModelDecorations(_this.editorId, _this.model, _this.configuration, _this.lines, _this.coordinatesConverter);
_this._registerModelEvents();
_this._register(_this.configuration.onDidChange(function (e) {
try {
var eventsCollector = _this._beginEmit();
_this._onConfigurationChanged(eventsCollector, e);
}
finally {
_this._endEmit();
}
}));
_this._register(minimapTokensColorTracker_1.MinimapTokensColorTracker.getInstance().onDidChange(function () {
try {
var eventsCollector = _this._beginEmit();
eventsCollector.emit(new viewEvents.ViewTokensColorsChangedEvent());
}
finally {
_this._endEmit();
}
}));
return _this;
}
ViewModel.prototype.dispose = function () {
// First remove listeners, as disposing the lines might end up sending
// model decoration changed events ... and we no longer care about them ...
_super.prototype.dispose.call(this);
this.decorations.dispose();
this.lines.dispose();
this.invalidateMinimapColorCache();
this.viewportStartLineTrackedRange = this.model._setTrackedRange(this.viewportStartLineTrackedRange, null, 1 /* NeverGrowsWhenTypingAtEdges */);
};
ViewModel.prototype.tokenizeViewport = function () {
var linesViewportData = this.viewLayout.getLinesViewportData();
var startPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(linesViewportData.startLineNumber, 1));
var endPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(linesViewportData.endLineNumber, 1));
this.model.tokenizeViewport(startPosition.lineNumber, endPosition.lineNumber);
};
ViewModel.prototype.setHasFocus = function (hasFocus) {
this.hasFocus = hasFocus;
};
ViewModel.prototype._onConfigurationChanged = function (eventsCollector, e) {
// We might need to restore the current centered view range, so save it (if available)
var previousViewportStartModelPosition = null;
if (this.viewportStartLine !== -1) {
var previousViewportStartViewPosition = new position_1.Position(this.viewportStartLine, this.getLineMinColumn(this.viewportStartLine));
previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition);
}
var restorePreviousViewportStart = false;
var options = this.configuration.options;
var fontInfo = options.get(34 /* fontInfo */);
var wrappingStrategy = options.get(103 /* wrappingStrategy */);
var wrappingInfo = options.get(108 /* wrappingInfo */);
var wrappingIndent = options.get(102 /* wrappingIndent */);
if (this.lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent)) {
eventsCollector.emit(new viewEvents.ViewFlushedEvent());
eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());
eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());
this.decorations.onLineMappingChanged();
this.viewLayout.onFlushed(this.getLineCount());
if (this.viewLayout.getCurrentScrollTop() !== 0) {
// Never change the scroll position from 0 to something else...
restorePreviousViewportStart = true;
}
}
if (e.hasChanged(68 /* readOnly */)) {
// Must read again all decorations due to readOnly filtering
this.decorations.reset();
eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());
}
eventsCollector.emit(new viewEvents.ViewConfigurationChangedEvent(e));
this.viewLayout.onConfigurationChanged(e);
if (restorePreviousViewportStart && previousViewportStartModelPosition) {
var viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(previousViewportStartModelPosition);
var viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
this.viewLayout.setScrollPositionNow({ scrollTop: viewPositionTop + this.viewportStartLineDelta });
}
};
ViewModel.prototype._registerModelEvents = function () {
var _this = this;
this._register(this.model.onDidChangeRawContentFast(function (e) {
try {
var eventsCollector = _this._beginEmit();
var hadOtherModelChange = false;
var hadModelLineChangeThatChangedLineMapping = false;
var changes = e.changes;
var versionId = e.versionId;
// Do a first pass to compute line mappings, and a second pass to actually interpret them
var lineBreaksComputer = _this.lines.createLineBreaksComputer();
for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) {
var change = changes_1[_i];
switch (change.changeType) {
case 4 /* LinesInserted */: {
for (var _a = 0, _b = change.detail; _a < _b.length; _a++) {
var line = _b[_a];
lineBreaksComputer.addRequest(line, null);
}
break;
}
case 2 /* LineChanged */: {
lineBreaksComputer.addRequest(change.detail, null);
break;
}
}
}
var lineBreaks = lineBreaksComputer.finalize();
var lineBreaksOffset = 0;
for (var _c = 0, changes_2 = changes; _c < changes_2.length; _c++) {
var change = changes_2[_c];
switch (change.changeType) {
case 1 /* Flush */: {
_this.lines.onModelFlushed();
eventsCollector.emit(new viewEvents.ViewFlushedEvent());
_this.decorations.reset();
_this.viewLayout.onFlushed(_this.getLineCount());
hadOtherModelChange = true;
break;
}
case 3 /* LinesDeleted */: {
var linesDeletedEvent = _this.lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber);
if (linesDeletedEvent !== null) {
eventsCollector.emit(linesDeletedEvent);
_this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
}
hadOtherModelChange = true;
break;
}
case 4 /* LinesInserted */: {
var insertedLineBreaks = lineBreaks.slice(lineBreaksOffset, lineBreaksOffset + change.detail.length);
lineBreaksOffset += change.detail.length;
var linesInsertedEvent = _this.lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, insertedLineBreaks);
if (linesInsertedEvent !== null) {
eventsCollector.emit(linesInsertedEvent);
_this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
}
hadOtherModelChange = true;
break;
}
case 2 /* LineChanged */: {
var changedLineBreakData = lineBreaks[lineBreaksOffset];
lineBreaksOffset++;
var _d = _this.lines.onModelLineChanged(versionId, change.lineNumber, changedLineBreakData), lineMappingChanged = _d[0], linesChangedEvent = _d[1], linesInsertedEvent = _d[2], linesDeletedEvent = _d[3];
hadModelLineChangeThatChangedLineMapping = lineMappingChanged;
if (linesChangedEvent) {
eventsCollector.emit(linesChangedEvent);
}
if (linesInsertedEvent) {
eventsCollector.emit(linesInsertedEvent);
_this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
}
if (linesDeletedEvent) {
eventsCollector.emit(linesDeletedEvent);
_this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
}
break;
}
case 5 /* EOLChanged */: {
// Nothing to do. The new version will be accepted below
break;
}
}
}
_this.lines.acceptVersionId(versionId);
_this.viewLayout.onHeightMaybeChanged();
if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) {
eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());
eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());
_this.decorations.onLineMappingChanged();
}
}
finally {
_this._endEmit();
}
// Update the configuration and reset the centered view line
_this.viewportStartLine = -1;
_this.configuration.setMaxLineNumber(_this.model.getLineCount());
// Recover viewport
if (!_this.hasFocus && _this.model.getAttachedEditorCount() >= 2 && _this.viewportStartLineTrackedRange) {
var modelRange = _this.model._getTrackedRange(_this.viewportStartLineTrackedRange);
if (modelRange) {
var viewPosition = _this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition());
var viewPositionTop = _this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
_this.viewLayout.setScrollPositionNow({ scrollTop: viewPositionTop + _this.viewportStartLineDelta });
}
}
}));
this._register(this.model.onDidChangeTokens(function (e) {
var viewRanges = [];
for (var j = 0, lenJ = e.ranges.length; j < lenJ; j++) {
var modelRange = e.ranges[j];
var viewStartLineNumber = _this.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.fromLineNumber, 1)).lineNumber;
var viewEndLineNumber = _this.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.toLineNumber, _this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber;
viewRanges[j] = {
fromLineNumber: viewStartLineNumber,
toLineNumber: viewEndLineNumber
};
}
try {
var eventsCollector = _this._beginEmit();
eventsCollector.emit(new viewEvents.ViewTokensChangedEvent(viewRanges));
}
finally {
_this._endEmit();
}
if (e.tokenizationSupportChanged) {
_this._tokenizeViewportSoon.schedule();
}
}));
this._register(this.model.onDidChangeLanguageConfiguration(function (e) {
try {
var eventsCollector = _this._beginEmit();
eventsCollector.emit(new viewEvents.ViewLanguageConfigurationEvent());
}
finally {
_this._endEmit();
}
}));
this._register(this.model.onDidChangeOptions(function (e) {
// A tab size change causes a line mapping changed event => all view parts will repaint OK, no further event needed here
if (_this.lines.setTabSize(_this.model.getOptions().tabSize)) {
_this.decorations.onLineMappingChanged();
_this.viewLayout.onFlushed(_this.getLineCount());
try {
var eventsCollector = _this._beginEmit();
eventsCollector.emit(new viewEvents.ViewFlushedEvent());
eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());
eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());
}
finally {
_this._endEmit();
}
}
}));
this._register(this.model.onDidChangeDecorations(function (e) {
_this.decorations.onModelDecorationsChanged();
try {
var eventsCollector = _this._beginEmit();
eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());
}
finally {
_this._endEmit();
}
}));
};
ViewModel.prototype.setHiddenAreas = function (ranges) {
try {
var eventsCollector = this._beginEmit();
var lineMappingChanged = this.lines.setHiddenAreas(ranges);
if (lineMappingChanged) {
eventsCollector.emit(new viewEvents.ViewFlushedEvent());
eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());
eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());
this.decorations.onLineMappingChanged();
this.viewLayout.onFlushed(this.getLineCount());
this.viewLayout.onHeightMaybeChanged();
}
}
finally {
this._endEmit();
}
};
ViewModel.prototype.getVisibleRanges = function () {
var visibleViewRange = this.getCompletelyVisibleViewRange();
var visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
var hiddenAreas = this.lines.getHiddenAreas();
if (hiddenAreas.length === 0) {
return [visibleRange];
}
var result = [], resultLen = 0;
var startLineNumber = visibleRange.startLineNumber;
var startColumn = visibleRange.startColumn;
var endLineNumber = visibleRange.endLineNumber;
var endColumn = visibleRange.endColumn;
for (var i = 0, len = hiddenAreas.length; i < len; i++) {
var hiddenStartLineNumber = hiddenAreas[i].startLineNumber;
var hiddenEndLineNumber = hiddenAreas[i].endLineNumber;
if (hiddenEndLineNumber < startLineNumber) {
continue;
}
if (hiddenStartLineNumber > endLineNumber) {
continue;
}
if (startLineNumber < hiddenStartLineNumber) {
result[resultLen++] = new range_1.Range(startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1));
}
startLineNumber = hiddenEndLineNumber + 1;
startColumn = 1;
}
if (startLineNumber < endLineNumber || (startLineNumber === endLineNumber && startColumn < endColumn)) {
result[resultLen++] = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
}
return result;
};
ViewModel.prototype.getCompletelyVisibleViewRange = function () {
var partialData = this.viewLayout.getLinesViewportData();
var startViewLineNumber = partialData.completelyVisibleStartLineNumber;
var endViewLineNumber = partialData.completelyVisibleEndLineNumber;
return new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
};
ViewModel.prototype.getCompletelyVisibleViewRangeAtScrollTop = function (scrollTop) {
var partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop);
var startViewLineNumber = partialData.completelyVisibleStartLineNumber;
var endViewLineNumber = partialData.completelyVisibleEndLineNumber;
return new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
};
ViewModel.prototype.saveState = function () {
var compatViewState = this.viewLayout.saveState();
var scrollTop = compatViewState.scrollTop;
var firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop);
var firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber)));
var firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop;
return {
scrollLeft: compatViewState.scrollLeft,
firstPosition: firstPosition,
firstPositionDeltaTop: firstPositionDeltaTop
};
};
ViewModel.prototype.reduceRestoreState = function (state) {
if (typeof state.firstPosition === 'undefined') {
// This is a view state serialized by an older version
return this._reduceRestoreStateCompatibility(state);
}
var modelPosition = this.model.validatePosition(state.firstPosition);
var viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
var scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop;
return {
scrollLeft: state.scrollLeft,
scrollTop: scrollTop
};
};
ViewModel.prototype._reduceRestoreStateCompatibility = function (state) {
return {
scrollLeft: state.scrollLeft,
scrollTop: state.scrollTopWithoutViewZones
};
};
ViewModel.prototype.getTabSize = function () {
return this.model.getOptions().tabSize;
};
ViewModel.prototype.getOptions = function () {
return this.model.getOptions();
};
ViewModel.prototype.getLineCount = function () {
return this.lines.getViewLineCount();
};
/**
* Gives a hint that a lot of requests are about to come in for these line numbers.
*/
ViewModel.prototype.setViewport = function (startLineNumber, endLineNumber, centeredLineNumber) {
this.viewportStartLine = startLineNumber;
var position = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(startLineNumber, this.getLineMinColumn(startLineNumber)));
this.viewportStartLineTrackedRange = this.model._setTrackedRange(this.viewportStartLineTrackedRange, new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), 1 /* NeverGrowsWhenTypingAtEdges */);
var viewportStartLineTop = this.viewLayout.getVerticalOffsetForLineNumber(startLineNumber);
var scrollTop = this.viewLayout.getCurrentScrollTop();
this.viewportStartLineDelta = scrollTop - viewportStartLineTop;
};
ViewModel.prototype.getActiveIndentGuide = function (lineNumber, minLineNumber, maxLineNumber) {
return this.lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber);
};
ViewModel.prototype.getLinesIndentGuides = function (startLineNumber, endLineNumber) {
return this.lines.getViewLinesIndentGuides(startLineNumber, endLineNumber);
};
ViewModel.prototype.getLineContent = function (lineNumber) {
return this.lines.getViewLineContent(lineNumber);
};
ViewModel.prototype.getLineLength = function (lineNumber) {
return this.lines.getViewLineLength(lineNumber);
};
ViewModel.prototype.getLineMinColumn = function (lineNumber) {
return this.lines.getViewLineMinColumn(lineNumber);
};
ViewModel.prototype.getLineMaxColumn = function (lineNumber) {
return this.lines.getViewLineMaxColumn(lineNumber);
};
ViewModel.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) {
var result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber));
if (result === -1) {
return 0;
}
return result + 1;
};
ViewModel.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) {
var result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber));
if (result === -1) {
return 0;
}
return result + 2;
};
ViewModel.prototype.getDecorationsInViewport = function (visibleRange) {
return this.decorations.getDecorationsViewportData(visibleRange).decorations;
};
ViewModel.prototype.getViewLineRenderingData = function (visibleRange, lineNumber) {
var mightContainRTL = this.model.mightContainRTL();
var mightContainNonBasicASCII = this.model.mightContainNonBasicASCII();
var tabSize = this.getTabSize();
var lineData = this.lines.getViewLineData(lineNumber);
var allInlineDecorations = this.decorations.getDecorationsViewportData(visibleRange).inlineDecorations;
var inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber];
return new viewModel_1.ViewLineRenderingData(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn);
};
ViewModel.prototype.getViewLineData = function (lineNumber) {
return this.lines.getViewLineData(lineNumber);
};
ViewModel.prototype.getMinimapLinesRenderingData = function (startLineNumber, endLineNumber, needed) {
var result = this.lines.getViewLinesData(startLineNumber, endLineNumber, needed);
return new viewModel_1.MinimapLinesRenderingData(this.getTabSize(), result);
};
ViewModel.prototype.getAllOverviewRulerDecorations = function (theme) {
return this.lines.getAllOverviewRulerDecorations(this.editorId, editorOptions_1.filterValidationDecorations(this.configuration.options), theme);
};
ViewModel.prototype.invalidateOverviewRulerColorCache = function () {
var decorations = this.model.getOverviewRulerDecorations();
for (var _i = 0, decorations_1 = decorations; _i < decorations_1.length; _i++) {
var decoration = decorations_1[_i];
var opts = decoration.options.overviewRuler;
if (opts) {
opts.invalidateCachedColor();
}
}
};
ViewModel.prototype.invalidateMinimapColorCache = function () {
var decorations = this.model.getAllDecorations();
for (var _i = 0, decorations_2 = decorations; _i < decorations_2.length; _i++) {
var decoration = decorations_2[_i];
var opts = decoration.options.minimap;
if (opts) {
opts.invalidateCachedColor();
}
}
};
ViewModel.prototype.getValueInRange = function (range, eol) {
var modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range);
return this.model.getValueInRange(modelRange, eol);
};
ViewModel.prototype.getModelLineMaxColumn = function (modelLineNumber) {
return this.model.getLineMaxColumn(modelLineNumber);
};
ViewModel.prototype.validateModelPosition = function (position) {
return this.model.validatePosition(position);
};
ViewModel.prototype.validateModelRange = function (range) {
return this.model.validateRange(range);
};
ViewModel.prototype.deduceModelPositionRelativeToViewPosition = function (viewAnchorPosition, deltaOffset, lineFeedCnt) {
var modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition);
if (this.model.getEOL().length === 2) {
// This model uses CRLF, so the delta must take that into account
if (deltaOffset < 0) {
deltaOffset -= lineFeedCnt;
}
else {
deltaOffset += lineFeedCnt;
}
}
var modelAnchorOffset = this.model.getOffsetAt(modelAnchor);
var resultOffset = modelAnchorOffset + deltaOffset;
return this.model.getPositionAt(resultOffset);
};
ViewModel.prototype.getEOL = function () {
return this.model.getEOL();
};
ViewModel.prototype.getPlainTextToCopy = function (modelRanges, emptySelectionClipboard, forceCRLF) {
var newLineCharacter = forceCRLF ? '\r\n' : this.model.getEOL();
modelRanges = modelRanges.slice(0);
modelRanges.sort(range_1.Range.compareRangesUsingStarts);
var hasEmptyRange = false;
var hasNonEmptyRange = false;
for (var _i = 0, modelRanges_1 = modelRanges; _i < modelRanges_1.length; _i++) {
var range = modelRanges_1[_i];
if (range.isEmpty()) {
hasEmptyRange = true;
}
else {
hasNonEmptyRange = true;
}
}
if (!hasNonEmptyRange) {
// all ranges are empty
if (!emptySelectionClipboard) {
return '';
}
var modelLineNumbers = modelRanges.map(function (r) { return r.startLineNumber; });
var result_1 = '';
for (var i = 0; i < modelLineNumbers.length; i++) {
if (i > 0 && modelLineNumbers[i - 1] === modelLineNumbers[i]) {
continue;
}
result_1 += this.model.getLineContent(modelLineNumbers[i]) + newLineCharacter;
}
return result_1;
}
if (hasEmptyRange && emptySelectionClipboard) {
// mixed empty selections and non-empty selections
var result_2 = [];
var prevModelLineNumber = 0;
for (var _a = 0, modelRanges_2 = modelRanges; _a < modelRanges_2.length; _a++) {
var modelRange = modelRanges_2[_a];
var modelLineNumber = modelRange.startLineNumber;
if (modelRange.isEmpty()) {
if (modelLineNumber !== prevModelLineNumber) {
result_2.push(this.model.getLineContent(modelLineNumber));
}
}
else {
result_2.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* CRLF */ : 0 /* TextDefined */));
}
prevModelLineNumber = modelLineNumber;
}
return result_2.length === 1 ? result_2[0] : result_2;
}
var result = [];
for (var _b = 0, modelRanges_3 = modelRanges; _b < modelRanges_3.length; _b++) {
var modelRange = modelRanges_3[_b];
if (!modelRange.isEmpty()) {
result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* CRLF */ : 0 /* TextDefined */));
}
}
return result.length === 1 ? result[0] : result;
};
ViewModel.prototype.getRichTextToCopy = function (modelRanges, emptySelectionClipboard) {
var languageId = this.model.getLanguageIdentifier();
if (languageId.id === 1 /* PlainText */) {
return null;
}
if (modelRanges.length !== 1) {
// no multiple selection support at this time
return null;
}
var range = modelRanges[0];
if (range.isEmpty()) {
if (!emptySelectionClipboard) {
// nothing to copy
return null;
}
var lineNumber = range.startLineNumber;
range = new range_1.Range(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber));
}
var fontInfo = this.configuration.options.get(34 /* fontInfo */);
var colorMap = this._getColorMap();
var fontFamily = fontInfo.fontFamily === editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily ? fontInfo.fontFamily : "'" + fontInfo.fontFamily + "', " + editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily;
return {
mode: languageId.language,
html: ("
"
+ this._getHTMLToCopy(range, colorMap)
+ '
')
};
};
ViewModel.prototype._getHTMLToCopy = function (modelRange, colorMap) {
var startLineNumber = modelRange.startLineNumber;
var startColumn = modelRange.startColumn;
var endLineNumber = modelRange.endLineNumber;
var endColumn = modelRange.endColumn;
var tabSize = this.getTabSize();
var result = '';
for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
var lineTokens = this.model.getLineTokens(lineNumber);
var lineContent = lineTokens.getLineContent();
var startOffset = (lineNumber === startLineNumber ? startColumn - 1 : 0);
var endOffset = (lineNumber === endLineNumber ? endColumn - 1 : lineContent.length);
if (lineContent === '') {
result += ' ';
}
else {
result += textToHtmlTokenizer_1.tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, platform.isWindows);
}
}
return result;
};
ViewModel.prototype._getColorMap = function () {
var colorMap = modes_1.TokenizationRegistry.getColorMap();
var result = ['#000000'];
if (colorMap) {
for (var i = 1, len = colorMap.length; i < len; i++) {
result[i] = color_1.Color.Format.CSS.formatHex(colorMap[i]);
}
}
return result;
};
return ViewModel;
}(viewEvents.ViewEventEmitter));
exports.ViewModel = ViewModel;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[489/*vs/editor/contrib/documentSymbols/outlineModel*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,26/*vs/base/common/cancellation*/,87/*vs/base/common/collections*/,10/*vs/base/common/errors*/,38/*vs/base/common/map*/,17/*vs/editor/common/modes*/]), function (require, exports, arrays_1, cancellation_1, collections_1, errors_1, map_1, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TreeElement = /** @class */ (function () {
function TreeElement() {
}
TreeElement.prototype.remove = function () {
if (this.parent) {
delete this.parent.children[this.id];
}
};
TreeElement.findId = function (candidate, container) {
// complex id-computation which contains the origin/extension,
// the parent path, and some dedupe logic when names collide
var candidateId;
if (typeof candidate === 'string') {
candidateId = container.id + "/" + candidate;
}
else {
candidateId = container.id + "/" + candidate.name;
if (container.children[candidateId] !== undefined) {
candidateId = container.id + "/" + candidate.name + "_" + candidate.range.startLineNumber + "_" + candidate.range.startColumn;
}
}
var id = candidateId;
for (var i = 0; container.children[id] !== undefined; i++) {
id = candidateId + "_" + i;
}
return id;
};
TreeElement.empty = function (element) {
for (var _key in element.children) {
return false;
}
return true;
};
return TreeElement;
}());
exports.TreeElement = TreeElement;
var OutlineElement = /** @class */ (function (_super) {
__extends(OutlineElement, _super);
function OutlineElement(id, parent, symbol) {
var _this = _super.call(this) || this;
_this.id = id;
_this.parent = parent;
_this.symbol = symbol;
_this.children = Object.create(null);
return _this;
}
return OutlineElement;
}(TreeElement));
exports.OutlineElement = OutlineElement;
var OutlineGroup = /** @class */ (function (_super) {
__extends(OutlineGroup, _super);
function OutlineGroup(id, parent, provider, providerIndex) {
var _this = _super.call(this) || this;
_this.id = id;
_this.parent = parent;
_this.provider = provider;
_this.providerIndex = providerIndex;
_this.children = Object.create(null);
return _this;
}
return OutlineGroup;
}(TreeElement));
exports.OutlineGroup = OutlineGroup;
var MovingAverage = /** @class */ (function () {
function MovingAverage() {
this._n = 1;
this._val = 0;
}
MovingAverage.prototype.update = function (value) {
this._val = this._val + (value - this._val) / this._n;
this._n += 1;
return this;
};
return MovingAverage;
}());
var OutlineModel = /** @class */ (function (_super) {
__extends(OutlineModel, _super);
function OutlineModel(textModel) {
var _this = _super.call(this) || this;
_this.textModel = textModel;
_this.id = 'root';
_this.parent = undefined;
_this._groups = Object.create(null);
_this.children = Object.create(null);
_this.id = 'root';
_this.parent = undefined;
return _this;
}
OutlineModel.create = function (textModel, token) {
var _this = this;
var key = this._keys.for(textModel, true);
var data = OutlineModel._requests.get(key);
if (!data) {
var source = new cancellation_1.CancellationTokenSource();
data = {
promiseCnt: 0,
source: source,
promise: OutlineModel._create(textModel, source.token),
model: undefined,
};
OutlineModel._requests.set(key, data);
// keep moving average of request durations
var now_1 = Date.now();
data.promise.then(function () {
var key = _this._keys.for(textModel, false);
var avg = _this._requestDurations.get(key);
if (!avg) {
avg = new MovingAverage();
_this._requestDurations.set(key, avg);
}
avg.update(Date.now() - now_1);
});
}
if (data.model) {
// resolved -> return data
return Promise.resolve(data.model);
}
// increase usage counter
data.promiseCnt += 1;
token.onCancellationRequested(function () {
// last -> cancel provider request, remove cached promise
if (--data.promiseCnt === 0) {
data.source.cancel();
OutlineModel._requests.delete(key);
}
});
return new Promise(function (resolve, reject) {
data.promise.then(function (model) {
data.model = model;
resolve(model);
}, function (err) {
OutlineModel._requests.delete(key);
reject(err);
});
});
};
OutlineModel._create = function (textModel, token) {
var cts = new cancellation_1.CancellationTokenSource(token);
var result = new OutlineModel(textModel);
var provider = modes_1.DocumentSymbolProviderRegistry.ordered(textModel);
var promises = provider.map(function (provider, index) {
var id = TreeElement.findId("provider_" + index, result);
var group = new OutlineGroup(id, result, provider, index);
return Promise.resolve(provider.provideDocumentSymbols(result.textModel, cts.token)).then(function (result) {
for (var _i = 0, _a = result || []; _i < _a.length; _i++) {
var info = _a[_i];
OutlineModel._makeOutlineElement(info, group);
}
return group;
}, function (err) {
errors_1.onUnexpectedExternalError(err);
return group;
}).then(function (group) {
if (!TreeElement.empty(group)) {
result._groups[id] = group;
}
else {
group.remove();
}
});
});
var listener = modes_1.DocumentSymbolProviderRegistry.onDidChange(function () {
var newProvider = modes_1.DocumentSymbolProviderRegistry.ordered(textModel);
if (!arrays_1.equals(newProvider, provider)) {
cts.cancel();
}
});
return Promise.all(promises).then(function () {
if (cts.token.isCancellationRequested && !token.isCancellationRequested) {
return OutlineModel._create(textModel, token);
}
else {
return result._compact();
}
}).finally(function () {
listener.dispose();
});
};
OutlineModel._makeOutlineElement = function (info, container) {
var id = TreeElement.findId(info, container);
var res = new OutlineElement(id, container, info);
if (info.children) {
for (var _i = 0, _a = info.children; _i < _a.length; _i++) {
var childInfo = _a[_i];
OutlineModel._makeOutlineElement(childInfo, res);
}
}
container.children[res.id] = res;
};
OutlineModel.prototype._compact = function () {
var count = 0;
for (var key in this._groups) {
var group = this._groups[key];
if (collections_1.first(group.children) === undefined) { // empty
delete this._groups[key];
}
else {
count += 1;
}
}
if (count !== 1) {
//
this.children = this._groups;
}
else {
// adopt all elements of the first group
var group = collections_1.first(this._groups);
for (var key in group.children) {
var child = group.children[key];
child.parent = this;
this.children[child.id] = child;
}
}
return this;
};
OutlineModel._requestDurations = new map_1.LRUCache(50, 0.7);
OutlineModel._requests = new map_1.LRUCache(9, 0.75);
OutlineModel._keys = new /** @class */ (function () {
function class_1() {
this._counter = 1;
this._data = new WeakMap();
}
class_1.prototype.for = function (textModel, version) {
return textModel.id + "/" + (version ? textModel.getVersionId() : '') + "/" + this._hash(modes_1.DocumentSymbolProviderRegistry.all(textModel));
};
class_1.prototype._hash = function (providers) {
var result = '';
for (var _i = 0, providers_1 = providers; _i < providers_1.length; _i++) {
var provider = providers_1[_i];
var n = this._data.get(provider);
if (typeof n === 'undefined') {
n = this._counter++;
this._data.set(provider, n);
}
result += n;
}
return result;
};
return class_1;
}());
return OutlineModel;
}(TreeElement));
exports.OutlineModel = OutlineModel;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[490/*vs/editor/contrib/folding/foldingDecorations*/], __M([0/*require*/,1/*exports*/,30/*vs/editor/common/model/textModel*/]), function (require, exports, textModel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FoldingDecorationProvider = /** @class */ (function () {
function FoldingDecorationProvider(editor) {
this.editor = editor;
this.autoHideFoldingControls = true;
this.showFoldingHighlights = true;
}
FoldingDecorationProvider.prototype.getDecorationOption = function (isCollapsed) {
if (isCollapsed) {
return this.showFoldingHighlights ? FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION;
}
else if (this.autoHideFoldingControls) {
return FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION;
}
else {
return FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION;
}
};
FoldingDecorationProvider.prototype.deltaDecorations = function (oldDecorations, newDecorations) {
return this.editor.deltaDecorations(oldDecorations, newDecorations);
};
FoldingDecorationProvider.prototype.changeDecorations = function (callback) {
return this.editor.changeDecorations(callback);
};
FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
afterContentClassName: 'inline-folded',
linesDecorationsClassName: 'codicon codicon-chevron-right'
});
FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
afterContentClassName: 'inline-folded',
className: 'folded-background',
isWholeLine: true,
linesDecorationsClassName: 'codicon codicon-chevron-right'
});
FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
linesDecorationsClassName: 'codicon codicon-chevron-down'
});
FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
stickiness: 1 /* NeverGrowsWhenTypingAtEdges */,
linesDecorationsClassName: 'codicon codicon-chevron-down alwaysShowFoldIcons'
});
return FoldingDecorationProvider;
}());
exports.FoldingDecorationProvider = FoldingDecorationProvider;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[491/*vs/editor/contrib/folding/indentRangeProvider*/], __M([0/*require*/,1/*exports*/,150/*vs/editor/contrib/folding/foldingRanges*/,30/*vs/editor/common/model/textModel*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/]), function (require, exports, foldingRanges_1, textModel_1, languageConfigurationRegistry_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MAX_FOLDING_REGIONS_FOR_INDENT_LIMIT = 5000;
exports.ID_INDENT_PROVIDER = 'indent';
var IndentRangeProvider = /** @class */ (function () {
function IndentRangeProvider(editorModel) {
this.editorModel = editorModel;
this.id = exports.ID_INDENT_PROVIDER;
}
IndentRangeProvider.prototype.dispose = function () {
};
IndentRangeProvider.prototype.compute = function (cancelationToken) {
var foldingRules = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getFoldingRules(this.editorModel.getLanguageIdentifier().id);
var offSide = foldingRules && !!foldingRules.offSide;
var markers = foldingRules && foldingRules.markers;
return Promise.resolve(computeRanges(this.editorModel, offSide, markers));
};
return IndentRangeProvider;
}());
exports.IndentRangeProvider = IndentRangeProvider;
// public only for testing
var RangesCollector = /** @class */ (function () {
function RangesCollector(foldingRangesLimit) {
this._startIndexes = [];
this._endIndexes = [];
this._indentOccurrences = [];
this._length = 0;
this._foldingRangesLimit = foldingRangesLimit;
}
RangesCollector.prototype.insertFirst = function (startLineNumber, endLineNumber, indent) {
if (startLineNumber > foldingRanges_1.MAX_LINE_NUMBER || endLineNumber > foldingRanges_1.MAX_LINE_NUMBER) {
return;
}
var index = this._length;
this._startIndexes[index] = startLineNumber;
this._endIndexes[index] = endLineNumber;
this._length++;
if (indent < 1000) {
this._indentOccurrences[indent] = (this._indentOccurrences[indent] || 0) + 1;
}
};
RangesCollector.prototype.toIndentRanges = function (model) {
if (this._length <= this._foldingRangesLimit) {
// reverse and create arrays of the exact length
var startIndexes = new Uint32Array(this._length);
var endIndexes = new Uint32Array(this._length);
for (var i = this._length - 1, k = 0; i >= 0; i--, k++) {
startIndexes[k] = this._startIndexes[i];
endIndexes[k] = this._endIndexes[i];
}
return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes);
}
else {
var entries = 0;
var maxIndent = this._indentOccurrences.length;
for (var i = 0; i < this._indentOccurrences.length; i++) {
var n = this._indentOccurrences[i];
if (n) {
if (n + entries > this._foldingRangesLimit) {
maxIndent = i;
break;
}
entries += n;
}
}
var tabSize = model.getOptions().tabSize;
// reverse and create arrays of the exact length
var startIndexes = new Uint32Array(this._foldingRangesLimit);
var endIndexes = new Uint32Array(this._foldingRangesLimit);
for (var i = this._length - 1, k = 0; i >= 0; i--) {
var startIndex = this._startIndexes[i];
var lineContent = model.getLineContent(startIndex);
var indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize);
if (indent < maxIndent || (indent === maxIndent && entries++ < this._foldingRangesLimit)) {
startIndexes[k] = startIndex;
endIndexes[k] = this._endIndexes[i];
k++;
}
}
return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes);
}
};
return RangesCollector;
}());
exports.RangesCollector = RangesCollector;
function computeRanges(model, offSide, markers, foldingRangesLimit) {
if (foldingRangesLimit === void 0) { foldingRangesLimit = MAX_FOLDING_REGIONS_FOR_INDENT_LIMIT; }
var tabSize = model.getOptions().tabSize;
var result = new RangesCollector(foldingRangesLimit);
var pattern = undefined;
if (markers) {
pattern = new RegExp("(" + markers.start.source + ")|(?:" + markers.end.source + ")");
}
var previousRegions = [];
var line = model.getLineCount() + 1;
previousRegions.push({ indent: -1, endAbove: line, line: line }); // sentinel, to make sure there's at least one entry
for (var line_1 = model.getLineCount(); line_1 > 0; line_1--) {
var lineContent = model.getLineContent(line_1);
var indent = textModel_1.TextModel.computeIndentLevel(lineContent, tabSize);
var previous = previousRegions[previousRegions.length - 1];
if (indent === -1) {
if (offSide) {
// for offSide languages, empty lines are associated to the previous block
// note: the next block is already written to the results, so this only
// impacts the end position of the block before
previous.endAbove = line_1;
}
continue; // only whitespace
}
var m = void 0;
if (pattern && (m = lineContent.match(pattern))) {
// folding pattern match
if (m[1]) { // start pattern match
// discard all regions until the folding pattern
var i = previousRegions.length - 1;
while (i > 0 && previousRegions[i].indent !== -2) {
i--;
}
if (i > 0) {
previousRegions.length = i + 1;
previous = previousRegions[i];
// new folding range from pattern, includes the end line
result.insertFirst(line_1, previous.line, indent);
previous.line = line_1;
previous.indent = indent;
previous.endAbove = line_1;
continue;
}
else {
// no end marker found, treat line as a regular line
}
}
else { // end pattern match
previousRegions.push({ indent: -2, endAbove: line_1, line: line_1 });
continue;
}
}
if (previous.indent > indent) {
// discard all regions with larger indent
do {
previousRegions.pop();
previous = previousRegions[previousRegions.length - 1];
} while (previous.indent > indent);
// new folding range
var endLineNumber = previous.endAbove - 1;
if (endLineNumber - line_1 >= 1) { // needs at east size 1
result.insertFirst(line_1, endLineNumber, indent);
}
}
if (previous.indent === indent) {
previous.endAbove = line_1;
}
else { // previous.indent < indent
// new region with a bigger indent
previousRegions.push({ indent: indent, endAbove: line_1, line: line_1 });
}
}
return result.toIndentRanges(model);
}
exports.computeRanges = computeRanges;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[492/*vs/editor/contrib/linesOperations/moveLinesCommand*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,211/*vs/editor/common/commands/shiftCommand*/,3/*vs/editor/common/core/range*/,22/*vs/editor/common/core/selection*/,90/*vs/editor/common/modes/languageConfiguration*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,385/*vs/editor/contrib/indentation/indentUtils*/]), function (require, exports, strings, shiftCommand_1, range_1, selection_1, languageConfiguration_1, languageConfigurationRegistry_1, indentUtils) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MoveLinesCommand = /** @class */ (function () {
function MoveLinesCommand(selection, isMovingDown, autoIndent) {
this._selection = selection;
this._isMovingDown = isMovingDown;
this._autoIndent = autoIndent;
this._selectionId = null;
this._moveEndLineSelectionShrink = false;
}
MoveLinesCommand.prototype.getEditOperations = function (model, builder) {
var modelLineCount = model.getLineCount();
if (this._isMovingDown && this._selection.endLineNumber === modelLineCount) {
this._selectionId = builder.trackSelection(this._selection);
return;
}
if (!this._isMovingDown && this._selection.startLineNumber === 1) {
this._selectionId = builder.trackSelection(this._selection);
return;
}
this._moveEndPositionDown = false;
var s = this._selection;
if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
this._moveEndPositionDown = true;
s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
}
var _a = model.getOptions(), tabSize = _a.tabSize, indentSize = _a.indentSize, insertSpaces = _a.insertSpaces;
var indentConverter = this.buildIndentConverter(tabSize, indentSize, insertSpaces);
var virtualModel = {
getLineTokens: function (lineNumber) {
return model.getLineTokens(lineNumber);
},
getLanguageIdentifier: function () {
return model.getLanguageIdentifier();
},
getLanguageIdAtPosition: function (lineNumber, column) {
return model.getLanguageIdAtPosition(lineNumber, column);
},
getLineContent: null,
};
if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) {
// Current line is empty
var lineNumber = s.startLineNumber;
var otherLineNumber = (this._isMovingDown ? lineNumber + 1 : lineNumber - 1);
if (model.getLineMaxColumn(otherLineNumber) === 1) {
// Other line number is empty too, so no editing is needed
// Add a no-op to force running by the model
builder.addEditOperation(new range_1.Range(1, 1, 1, 1), null);
}
else {
// Type content from other line number on line number
builder.addEditOperation(new range_1.Range(lineNumber, 1, lineNumber, 1), model.getLineContent(otherLineNumber));
// Remove content from other line number
builder.addEditOperation(new range_1.Range(otherLineNumber, 1, otherLineNumber, model.getLineMaxColumn(otherLineNumber)), null);
}
// Track selection at the other line number
s = new selection_1.Selection(otherLineNumber, 1, otherLineNumber, 1);
}
else {
var movingLineNumber_1;
var movingLineText = void 0;
if (this._isMovingDown) {
movingLineNumber_1 = s.endLineNumber + 1;
movingLineText = model.getLineContent(movingLineNumber_1);
// Delete line that needs to be moved
builder.addEditOperation(new range_1.Range(movingLineNumber_1 - 1, model.getLineMaxColumn(movingLineNumber_1 - 1), movingLineNumber_1, model.getLineMaxColumn(movingLineNumber_1)), null);
var insertingText_1 = movingLineText;
if (this.shouldAutoIndent(model, s)) {
var movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber_1, s.startLineNumber - 1);
// if s.startLineNumber - 1 matches onEnter rule, we still honor that.
if (movingLineMatchResult !== null) {
var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber_1));
var newSpaceCnt = movingLineMatchResult + indentUtils.getSpaceCnt(oldIndentation, tabSize);
var newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
insertingText_1 = newIndentation + this.trimLeft(movingLineText);
}
else {
// no enter rule matches, let's check indentatin rules then.
virtualModel.getLineContent = function (lineNumber) {
if (lineNumber === s.startLineNumber) {
return model.getLineContent(movingLineNumber_1);
}
else {
return model.getLineContent(lineNumber);
}
};
var indentOfMovingLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber_1, 1), s.startLineNumber, indentConverter);
if (indentOfMovingLine !== null) {
var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber_1));
var newSpaceCnt = indentUtils.getSpaceCnt(indentOfMovingLine, tabSize);
var oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
if (newSpaceCnt !== oldSpaceCnt) {
var newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
insertingText_1 = newIndentation + this.trimLeft(movingLineText);
}
}
}
// add edit operations for moving line first to make sure it's executed after we make indentation change
// to s.startLineNumber
builder.addEditOperation(new range_1.Range(s.startLineNumber, 1, s.startLineNumber, 1), insertingText_1 + '\n');
var ret = this.matchEnterRule(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber, insertingText_1);
// check if the line being moved before matches onEnter rules, if so let's adjust the indentation by onEnter rules.
if (ret !== null) {
if (ret !== 0) {
this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
}
}
else {
// it doesn't match onEnter rules, let's check indentation rules then.
virtualModel.getLineContent = function (lineNumber) {
if (lineNumber === s.startLineNumber) {
return insertingText_1;
}
else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) {
return model.getLineContent(lineNumber - 1);
}
else {
return model.getLineContent(lineNumber);
}
};
var newIndentatOfMovingBlock = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber_1, 1), s.startLineNumber + 1, indentConverter);
if (newIndentatOfMovingBlock !== null) {
var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber));
var newSpaceCnt = indentUtils.getSpaceCnt(newIndentatOfMovingBlock, tabSize);
var oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
if (newSpaceCnt !== oldSpaceCnt) {
var spaceCntOffset = newSpaceCnt - oldSpaceCnt;
this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
}
}
}
}
else {
// Insert line that needs to be moved before
builder.addEditOperation(new range_1.Range(s.startLineNumber, 1, s.startLineNumber, 1), insertingText_1 + '\n');
}
}
else {
movingLineNumber_1 = s.startLineNumber - 1;
movingLineText = model.getLineContent(movingLineNumber_1);
// Delete line that needs to be moved
builder.addEditOperation(new range_1.Range(movingLineNumber_1, 1, movingLineNumber_1 + 1, 1), null);
// Insert line that needs to be moved after
builder.addEditOperation(new range_1.Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), '\n' + movingLineText);
if (this.shouldAutoIndent(model, s)) {
virtualModel.getLineContent = function (lineNumber) {
if (lineNumber === movingLineNumber_1) {
return model.getLineContent(s.startLineNumber);
}
else {
return model.getLineContent(lineNumber);
}
};
var ret = this.matchEnterRule(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber - 2);
// check if s.startLineNumber - 2 matches onEnter rules, if so adjust the moving block by onEnter rules.
if (ret !== null) {
if (ret !== 0) {
this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
}
}
else {
// it doesn't match any onEnter rule, let's check indentation rules then.
var indentOfFirstLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber_1, indentConverter);
if (indentOfFirstLine !== null) {
// adjust the indentation of the moving block
var oldIndent = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber));
var newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize);
var oldSpaceCnt = indentUtils.getSpaceCnt(oldIndent, tabSize);
if (newSpaceCnt !== oldSpaceCnt) {
var spaceCntOffset = newSpaceCnt - oldSpaceCnt;
this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
}
}
}
}
}
}
this._selectionId = builder.trackSelection(s);
};
MoveLinesCommand.prototype.buildIndentConverter = function (tabSize, indentSize, insertSpaces) {
return {
shiftIndent: function (indentation) {
return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
},
unshiftIndent: function (indentation) {
return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
}
};
};
MoveLinesCommand.prototype.matchEnterRule = function (model, indentConverter, tabSize, line, oneLineAbove, oneLineAboveText) {
var validPrecedingLine = oneLineAbove;
while (validPrecedingLine >= 1) {
// ship empty lines as empty lines just inherit indentation
var lineContent = void 0;
if (validPrecedingLine === oneLineAbove && oneLineAboveText !== undefined) {
lineContent = oneLineAboveText;
}
else {
lineContent = model.getLineContent(validPrecedingLine);
}
var nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineContent);
if (nonWhitespaceIdx >= 0) {
break;
}
validPrecedingLine--;
}
if (validPrecedingLine < 1 || line > model.getLineCount()) {
return null;
}
var maxColumn = model.getLineMaxColumn(validPrecedingLine);
var enter = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getEnterAction(this._autoIndent, model, new range_1.Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn));
if (enter) {
var enterPrefix = enter.indentation;
if (enter.indentAction === languageConfiguration_1.IndentAction.None) {
enterPrefix = enter.indentation + enter.appendText;
}
else if (enter.indentAction === languageConfiguration_1.IndentAction.Indent) {
enterPrefix = enter.indentation + enter.appendText;
}
else if (enter.indentAction === languageConfiguration_1.IndentAction.IndentOutdent) {
enterPrefix = enter.indentation;
}
else if (enter.indentAction === languageConfiguration_1.IndentAction.Outdent) {
enterPrefix = indentConverter.unshiftIndent(enter.indentation) + enter.appendText;
}
var movingLineText = model.getLineContent(line);
if (this.trimLeft(movingLineText).indexOf(this.trimLeft(enterPrefix)) >= 0) {
var oldIndentation = strings.getLeadingWhitespace(model.getLineContent(line));
var newIndentation = strings.getLeadingWhitespace(enterPrefix);
var indentMetadataOfMovelingLine = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentMetadata(model, line);
if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & 2 /* DECREASE_MASK */) {
newIndentation = indentConverter.unshiftIndent(newIndentation);
}
var newSpaceCnt = indentUtils.getSpaceCnt(newIndentation, tabSize);
var oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
return newSpaceCnt - oldSpaceCnt;
}
}
return null;
};
MoveLinesCommand.prototype.trimLeft = function (str) {
return str.replace(/^\s+/, '');
};
MoveLinesCommand.prototype.shouldAutoIndent = function (model, selection) {
if (this._autoIndent < 4 /* Full */) {
return false;
}
// if it's not easy to tokenize, we stop auto indent.
if (!model.isCheapToTokenize(selection.startLineNumber)) {
return false;
}
var languageAtSelectionStart = model.getLanguageIdAtPosition(selection.startLineNumber, 1);
var languageAtSelectionEnd = model.getLanguageIdAtPosition(selection.endLineNumber, 1);
if (languageAtSelectionStart !== languageAtSelectionEnd) {
return false;
}
if (languageConfigurationRegistry_1.LanguageConfigurationRegistry.getIndentRulesSupport(languageAtSelectionStart) === null) {
return false;
}
return true;
};
MoveLinesCommand.prototype.getIndentEditsOfMovingBlock = function (model, builder, s, tabSize, insertSpaces, offset) {
for (var i = s.startLineNumber; i <= s.endLineNumber; i++) {
var lineContent = model.getLineContent(i);
var originalIndent = strings.getLeadingWhitespace(lineContent);
var originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize);
var newSpacesCnt = originalSpacesCnt + offset;
var newIndent = indentUtils.generateIndent(newSpacesCnt, tabSize, insertSpaces);
if (newIndent !== originalIndent) {
builder.addEditOperation(new range_1.Range(i, 1, i, originalIndent.length + 1), newIndent);
if (i === s.endLineNumber && s.endColumn <= originalIndent.length + 1 && newIndent === '') {
// as users select part of the original indent white spaces
// when we adjust the indentation of endLine, we should adjust the cursor position as well.
this._moveEndLineSelectionShrink = true;
}
}
}
};
MoveLinesCommand.prototype.computeCursorState = function (model, helper) {
var result = helper.getTrackedSelection(this._selectionId);
if (this._moveEndPositionDown) {
result = result.setEndPosition(result.endLineNumber + 1, 1);
}
if (this._moveEndLineSelectionShrink && result.startLineNumber < result.endLineNumber) {
result = result.setEndPosition(result.endLineNumber, 2);
}
return result;
};
return MoveLinesCommand;
}());
exports.MoveLinesCommand = MoveLinesCommand;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[493/*vs/editor/contrib/zoneWidget/zoneWidget*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,104/*vs/base/browser/ui/sash/sash*/,27/*vs/base/common/color*/,127/*vs/base/common/idGenerator*/,2/*vs/base/common/lifecycle*/,31/*vs/base/common/objects*/,3/*vs/editor/common/core/range*/,30/*vs/editor/common/model/textModel*/,324/*vs/css!vs/editor/contrib/zoneWidget/zoneWidget*/]), function (require, exports, dom, sash_1, color_1, idGenerator_1, lifecycle_1, objects, range_1, textModel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var defaultColor = new color_1.Color(new color_1.RGBA(0, 122, 204));
var defaultOptions = {
showArrow: true,
showFrame: true,
className: '',
frameColor: defaultColor,
arrowColor: defaultColor,
keepEditorSelection: false
};
var WIDGET_ID = 'vs.editor.contrib.zoneWidget';
var ViewZoneDelegate = /** @class */ (function () {
function ViewZoneDelegate(domNode, afterLineNumber, afterColumn, heightInLines, onDomNodeTop, onComputedHeight) {
this.id = ''; // A valid zone id should be greater than 0
this.domNode = domNode;
this.afterLineNumber = afterLineNumber;
this.afterColumn = afterColumn;
this.heightInLines = heightInLines;
this._onDomNodeTop = onDomNodeTop;
this._onComputedHeight = onComputedHeight;
}
ViewZoneDelegate.prototype.onDomNodeTop = function (top) {
this._onDomNodeTop(top);
};
ViewZoneDelegate.prototype.onComputedHeight = function (height) {
this._onComputedHeight(height);
};
return ViewZoneDelegate;
}());
exports.ViewZoneDelegate = ViewZoneDelegate;
var OverlayWidgetDelegate = /** @class */ (function () {
function OverlayWidgetDelegate(id, domNode) {
this._id = id;
this._domNode = domNode;
}
OverlayWidgetDelegate.prototype.getId = function () {
return this._id;
};
OverlayWidgetDelegate.prototype.getDomNode = function () {
return this._domNode;
};
OverlayWidgetDelegate.prototype.getPosition = function () {
return null;
};
return OverlayWidgetDelegate;
}());
exports.OverlayWidgetDelegate = OverlayWidgetDelegate;
var Arrow = /** @class */ (function () {
function Arrow(_editor) {
this._editor = _editor;
this._ruleName = Arrow._IdGenerator.nextId();
this._decorations = [];
this._color = null;
this._height = -1;
//
}
Arrow.prototype.dispose = function () {
this.hide();
dom.removeCSSRulesContainingSelector(this._ruleName);
};
Object.defineProperty(Arrow.prototype, "color", {
set: function (value) {
if (this._color !== value) {
this._color = value;
this._updateStyle();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Arrow.prototype, "height", {
set: function (value) {
if (this._height !== value) {
this._height = value;
this._updateStyle();
}
},
enumerable: true,
configurable: true
});
Arrow.prototype._updateStyle = function () {
dom.removeCSSRulesContainingSelector(this._ruleName);
dom.createCSSRule(".monaco-editor " + this._ruleName, "border-style: solid; border-color: transparent; border-bottom-color: " + this._color + "; border-width: " + this._height + "px; bottom: -" + this._height + "px; margin-left: -" + this._height + "px; ");
};
Arrow.prototype.show = function (where) {
this._decorations = this._editor.deltaDecorations(this._decorations, [{ range: range_1.Range.fromPositions(where), options: { className: this._ruleName, stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ } }]);
};
Arrow.prototype.hide = function () {
this._editor.deltaDecorations(this._decorations, []);
};
Arrow._IdGenerator = new idGenerator_1.IdGenerator('.arrow-decoration-');
return Arrow;
}());
var ZoneWidget = /** @class */ (function () {
function ZoneWidget(editor, options) {
var _this = this;
if (options === void 0) { options = {}; }
this._arrow = null;
this._overlayWidget = null;
this._resizeSash = null;
this._positionMarkerId = [];
this._viewZone = null;
this._disposables = new lifecycle_1.DisposableStore();
this.container = null;
this._isShowing = false;
this.editor = editor;
this.options = objects.deepClone(options);
objects.mixin(this.options, defaultOptions, false);
this.domNode = document.createElement('div');
if (!this.options.isAccessible) {
this.domNode.setAttribute('aria-hidden', 'true');
this.domNode.setAttribute('role', 'presentation');
}
this._disposables.add(this.editor.onDidLayoutChange(function (info) {
var width = _this._getWidth(info);
_this.domNode.style.width = width + 'px';
_this.domNode.style.left = _this._getLeft(info) + 'px';
_this._onWidth(width);
}));
}
ZoneWidget.prototype.dispose = function () {
var _this = this;
if (this._overlayWidget) {
this.editor.removeOverlayWidget(this._overlayWidget);
this._overlayWidget = null;
}
if (this._viewZone) {
this.editor.changeViewZones(function (accessor) {
if (_this._viewZone) {
accessor.removeZone(_this._viewZone.id);
}
_this._viewZone = null;
});
}
this.editor.deltaDecorations(this._positionMarkerId, []);
this._positionMarkerId = [];
this._disposables.dispose();
};
ZoneWidget.prototype.create = function () {
dom.addClass(this.domNode, 'zone-widget');
if (this.options.className) {
dom.addClass(this.domNode, this.options.className);
}
this.container = document.createElement('div');
dom.addClass(this.container, 'zone-widget-container');
this.domNode.appendChild(this.container);
if (this.options.showArrow) {
this._arrow = new Arrow(this.editor);
this._disposables.add(this._arrow);
}
this._fillContainer(this.container);
this._initSash();
this._applyStyles();
};
ZoneWidget.prototype.style = function (styles) {
if (styles.frameColor) {
this.options.frameColor = styles.frameColor;
}
if (styles.arrowColor) {
this.options.arrowColor = styles.arrowColor;
}
this._applyStyles();
};
ZoneWidget.prototype._applyStyles = function () {
if (this.container && this.options.frameColor) {
var frameColor = this.options.frameColor.toString();
this.container.style.borderTopColor = frameColor;
this.container.style.borderBottomColor = frameColor;
}
if (this._arrow && this.options.arrowColor) {
var arrowColor = this.options.arrowColor.toString();
this._arrow.color = arrowColor;
}
};
ZoneWidget.prototype._getWidth = function (info) {
return info.width - info.minimapWidth - info.verticalScrollbarWidth;
};
ZoneWidget.prototype._getLeft = function (info) {
// If minimap is to the left, we move beyond it
if (info.minimapWidth > 0 && info.minimapLeft === 0) {
return info.minimapWidth;
}
return 0;
};
ZoneWidget.prototype._onViewZoneTop = function (top) {
this.domNode.style.top = top + 'px';
};
ZoneWidget.prototype._onViewZoneHeight = function (height) {
this.domNode.style.height = height + "px";
if (this.container) {
var containerHeight = height - this._decoratingElementsHeight();
this.container.style.height = containerHeight + "px";
var layoutInfo = this.editor.getLayoutInfo();
this._doLayout(containerHeight, this._getWidth(layoutInfo));
}
if (this._resizeSash) {
this._resizeSash.layout();
}
};
Object.defineProperty(ZoneWidget.prototype, "position", {
get: function () {
var id = this._positionMarkerId[0];
if (!id) {
return undefined;
}
var model = this.editor.getModel();
if (!model) {
return undefined;
}
var range = model.getDecorationRange(id);
if (!range) {
return undefined;
}
return range.getStartPosition();
},
enumerable: true,
configurable: true
});
ZoneWidget.prototype.show = function (rangeOrPos, heightInLines) {
var range = range_1.Range.isIRange(rangeOrPos) ? range_1.Range.lift(rangeOrPos) : range_1.Range.fromPositions(rangeOrPos);
this._isShowing = true;
this._showImpl(range, heightInLines);
this._isShowing = false;
this._positionMarkerId = this.editor.deltaDecorations(this._positionMarkerId, [{ range: range, options: textModel_1.ModelDecorationOptions.EMPTY }]);
};
ZoneWidget.prototype.hide = function () {
var _this = this;
if (this._viewZone) {
this.editor.changeViewZones(function (accessor) {
if (_this._viewZone) {
accessor.removeZone(_this._viewZone.id);
}
});
this._viewZone = null;
}
if (this._overlayWidget) {
this.editor.removeOverlayWidget(this._overlayWidget);
this._overlayWidget = null;
}
if (this._arrow) {
this._arrow.hide();
}
};
ZoneWidget.prototype._decoratingElementsHeight = function () {
var lineHeight = this.editor.getOption(49 /* lineHeight */);
var result = 0;
if (this.options.showArrow) {
var arrowHeight = Math.round(lineHeight / 3);
result += 2 * arrowHeight;
}
if (this.options.showFrame) {
var frameThickness = Math.round(lineHeight / 9);
result += 2 * frameThickness;
}
return result;
};
ZoneWidget.prototype._showImpl = function (where, heightInLines) {
var _this = this;
var position = where.getStartPosition();
var layoutInfo = this.editor.getLayoutInfo();
var width = this._getWidth(layoutInfo);
this.domNode.style.width = width + "px";
this.domNode.style.left = this._getLeft(layoutInfo) + 'px';
// Render the widget as zone (rendering) and widget (lifecycle)
var viewZoneDomNode = document.createElement('div');
viewZoneDomNode.style.overflow = 'hidden';
var lineHeight = this.editor.getOption(49 /* lineHeight */);
// adjust heightInLines to viewport
var maxHeightInLines = (this.editor.getLayoutInfo().height / lineHeight) * 0.8;
if (heightInLines >= maxHeightInLines) {
heightInLines = maxHeightInLines;
}
var arrowHeight = 0;
var frameThickness = 0;
// Render the arrow one 1/3 of an editor line height
if (this._arrow && this.options.showArrow) {
arrowHeight = Math.round(lineHeight / 3);
this._arrow.height = arrowHeight;
this._arrow.show(position);
}
// Render the frame as 1/9 of an editor line height
if (this.options.showFrame) {
frameThickness = Math.round(lineHeight / 9);
}
// insert zone widget
this.editor.changeViewZones(function (accessor) {
if (_this._viewZone) {
accessor.removeZone(_this._viewZone.id);
}
if (_this._overlayWidget) {
_this.editor.removeOverlayWidget(_this._overlayWidget);
_this._overlayWidget = null;
}
_this.domNode.style.top = '-1000px';
_this._viewZone = new ViewZoneDelegate(viewZoneDomNode, position.lineNumber, position.column, heightInLines, function (top) { return _this._onViewZoneTop(top); }, function (height) { return _this._onViewZoneHeight(height); });
_this._viewZone.id = accessor.addZone(_this._viewZone);
_this._overlayWidget = new OverlayWidgetDelegate(WIDGET_ID + _this._viewZone.id, _this.domNode);
_this.editor.addOverlayWidget(_this._overlayWidget);
});
if (this.container && this.options.showFrame) {
var width_1 = this.options.frameWidth ? this.options.frameWidth : frameThickness;
this.container.style.borderTopWidth = width_1 + 'px';
this.container.style.borderBottomWidth = width_1 + 'px';
}
var containerHeight = heightInLines * lineHeight - this._decoratingElementsHeight();
if (this.container) {
this.container.style.top = arrowHeight + 'px';
this.container.style.height = containerHeight + 'px';
this.container.style.overflow = 'hidden';
}
this._doLayout(containerHeight, width);
if (!this.options.keepEditorSelection) {
this.editor.setSelection(where);
}
var model = this.editor.getModel();
if (model) {
var revealLine = where.endLineNumber + 1;
if (revealLine <= model.getLineCount()) {
// reveal line below the zone widget
this.revealLine(revealLine, false);
}
else {
// reveal last line atop
this.revealLine(model.getLineCount(), true);
}
}
};
ZoneWidget.prototype.revealLine = function (lineNumber, isLastLine) {
if (isLastLine) {
this.editor.revealLineInCenter(lineNumber, 0 /* Smooth */);
}
else {
this.editor.revealLine(lineNumber, 0 /* Smooth */);
}
};
ZoneWidget.prototype.setCssClass = function (className, classToReplace) {
if (!this.container) {
return;
}
if (classToReplace) {
this.container.classList.remove(classToReplace);
}
dom.addClass(this.container, className);
};
ZoneWidget.prototype._onWidth = function (widthInPixel) {
// implement in subclass
};
ZoneWidget.prototype._doLayout = function (heightInPixel, widthInPixel) {
// implement in subclass
};
ZoneWidget.prototype._relayout = function (newHeightInLines) {
var _this = this;
if (this._viewZone && this._viewZone.heightInLines !== newHeightInLines) {
this.editor.changeViewZones(function (accessor) {
if (_this._viewZone) {
_this._viewZone.heightInLines = newHeightInLines;
accessor.layoutZone(_this._viewZone.id);
}
});
}
};
// --- sash
ZoneWidget.prototype._initSash = function () {
var _this = this;
if (this._resizeSash) {
return;
}
this._resizeSash = this._disposables.add(new sash_1.Sash(this.domNode, this, { orientation: 1 /* HORIZONTAL */ }));
if (!this.options.isResizeable) {
this._resizeSash.hide();
this._resizeSash.state = 0 /* Disabled */;
}
var data;
this._disposables.add(this._resizeSash.onDidStart(function (e) {
if (_this._viewZone) {
data = {
startY: e.startY,
heightInLines: _this._viewZone.heightInLines,
};
}
}));
this._disposables.add(this._resizeSash.onDidEnd(function () {
data = undefined;
}));
this._disposables.add(this._resizeSash.onDidChange(function (evt) {
if (data) {
var lineDelta = (evt.currentY - data.startY) / _this.editor.getOption(49 /* lineHeight */);
var roundedLineDelta = lineDelta < 0 ? Math.ceil(lineDelta) : Math.floor(lineDelta);
var newHeightInLines = data.heightInLines + roundedLineDelta;
if (newHeightInLines > 5 && newHeightInLines < 35) {
_this._relayout(newHeightInLines);
}
}
}));
};
ZoneWidget.prototype.getHorizontalSashLeft = function () {
return 0;
};
ZoneWidget.prototype.getHorizontalSashTop = function () {
return (this.domNode.style.height === null ? 0 : parseInt(this.domNode.style.height)) - (this._decoratingElementsHeight() / 2);
};
ZoneWidget.prototype.getHorizontalSashWidth = function () {
var layoutInfo = this.editor.getLayoutInfo();
return layoutInfo.width - layoutInfo.minimapWidth;
};
return ZoneWidget;
}());
exports.ZoneWidget = ZoneWidget;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[216/*vs/editor/standalone/common/monarch/monarchLexer*/], __M([0/*require*/,1/*exports*/,107/*vs/editor/common/core/token*/,17/*vs/editor/common/modes*/,63/*vs/editor/common/modes/nullMode*/,203/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, token_1, modes, nullMode_1, monarchCommon) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CACHE_STACK_DEPTH = 5;
/**
* Reuse the same stack elements up to a certain depth.
*/
var MonarchStackElementFactory = /** @class */ (function () {
function MonarchStackElementFactory(maxCacheDepth) {
this._maxCacheDepth = maxCacheDepth;
this._entries = Object.create(null);
}
MonarchStackElementFactory.create = function (parent, state) {
return this._INSTANCE.create(parent, state);
};
MonarchStackElementFactory.prototype.create = function (parent, state) {
if (parent !== null && parent.depth >= this._maxCacheDepth) {
// no caching above a certain depth
return new MonarchStackElement(parent, state);
}
var stackElementId = MonarchStackElement.getStackElementId(parent);
if (stackElementId.length > 0) {
stackElementId += '|';
}
stackElementId += state;
var result = this._entries[stackElementId];
if (result) {
return result;
}
result = new MonarchStackElement(parent, state);
this._entries[stackElementId] = result;
return result;
};
MonarchStackElementFactory._INSTANCE = new MonarchStackElementFactory(CACHE_STACK_DEPTH);
return MonarchStackElementFactory;
}());
var MonarchStackElement = /** @class */ (function () {
function MonarchStackElement(parent, state) {
this.parent = parent;
this.state = state;
this.depth = (this.parent ? this.parent.depth : 0) + 1;
}
MonarchStackElement.getStackElementId = function (element) {
var result = '';
while (element !== null) {
if (result.length > 0) {
result += '|';
}
result += element.state;
element = element.parent;
}
return result;
};
MonarchStackElement._equals = function (a, b) {
while (a !== null && b !== null) {
if (a === b) {
return true;
}
if (a.state !== b.state) {
return false;
}
a = a.parent;
b = b.parent;
}
if (a === null && b === null) {
return true;
}
return false;
};
MonarchStackElement.prototype.equals = function (other) {
return MonarchStackElement._equals(this, other);
};
MonarchStackElement.prototype.push = function (state) {
return MonarchStackElementFactory.create(this, state);
};
MonarchStackElement.prototype.pop = function () {
return this.parent;
};
MonarchStackElement.prototype.popall = function () {
var result = this;
while (result.parent) {
result = result.parent;
}
return result;
};
MonarchStackElement.prototype.switchTo = function (state) {
return MonarchStackElementFactory.create(this.parent, state);
};
return MonarchStackElement;
}());
var EmbeddedModeData = /** @class */ (function () {
function EmbeddedModeData(modeId, state) {
this.modeId = modeId;
this.state = state;
}
EmbeddedModeData.prototype.equals = function (other) {
return (this.modeId === other.modeId
&& this.state.equals(other.state));
};
EmbeddedModeData.prototype.clone = function () {
var stateClone = this.state.clone();
// save an object
if (stateClone === this.state) {
return this;
}
return new EmbeddedModeData(this.modeId, this.state);
};
return EmbeddedModeData;
}());
/**
* Reuse the same line states up to a certain depth.
*/
var MonarchLineStateFactory = /** @class */ (function () {
function MonarchLineStateFactory(maxCacheDepth) {
this._maxCacheDepth = maxCacheDepth;
this._entries = Object.create(null);
}
MonarchLineStateFactory.create = function (stack, embeddedModeData) {
return this._INSTANCE.create(stack, embeddedModeData);
};
MonarchLineStateFactory.prototype.create = function (stack, embeddedModeData) {
if (embeddedModeData !== null) {
// no caching when embedding
return new MonarchLineState(stack, embeddedModeData);
}
if (stack !== null && stack.depth >= this._maxCacheDepth) {
// no caching above a certain depth
return new MonarchLineState(stack, embeddedModeData);
}
var stackElementId = MonarchStackElement.getStackElementId(stack);
var result = this._entries[stackElementId];
if (result) {
return result;
}
result = new MonarchLineState(stack, null);
this._entries[stackElementId] = result;
return result;
};
MonarchLineStateFactory._INSTANCE = new MonarchLineStateFactory(CACHE_STACK_DEPTH);
return MonarchLineStateFactory;
}());
var MonarchLineState = /** @class */ (function () {
function MonarchLineState(stack, embeddedModeData) {
this.stack = stack;
this.embeddedModeData = embeddedModeData;
}
MonarchLineState.prototype.clone = function () {
var embeddedModeDataClone = this.embeddedModeData ? this.embeddedModeData.clone() : null;
// save an object
if (embeddedModeDataClone === this.embeddedModeData) {
return this;
}
return MonarchLineStateFactory.create(this.stack, this.embeddedModeData);
};
MonarchLineState.prototype.equals = function (other) {
if (!(other instanceof MonarchLineState)) {
return false;
}
if (!this.stack.equals(other.stack)) {
return false;
}
if (this.embeddedModeData === null && other.embeddedModeData === null) {
return true;
}
if (this.embeddedModeData === null || other.embeddedModeData === null) {
return false;
}
return this.embeddedModeData.equals(other.embeddedModeData);
};
return MonarchLineState;
}());
var MonarchClassicTokensCollector = /** @class */ (function () {
function MonarchClassicTokensCollector() {
this._tokens = [];
this._language = null;
this._lastTokenType = null;
this._lastTokenLanguage = null;
}
MonarchClassicTokensCollector.prototype.enterMode = function (startOffset, modeId) {
this._language = modeId;
};
MonarchClassicTokensCollector.prototype.emit = function (startOffset, type) {
if (this._lastTokenType === type && this._lastTokenLanguage === this._language) {
return;
}
this._lastTokenType = type;
this._lastTokenLanguage = this._language;
this._tokens.push(new token_1.Token(startOffset, type, this._language));
};
MonarchClassicTokensCollector.prototype.nestedModeTokenize = function (embeddedModeLine, embeddedModeData, offsetDelta) {
var nestedModeId = embeddedModeData.modeId;
var embeddedModeState = embeddedModeData.state;
var nestedModeTokenizationSupport = modes.TokenizationRegistry.get(nestedModeId);
if (!nestedModeTokenizationSupport) {
this.enterMode(offsetDelta, nestedModeId);
this.emit(offsetDelta, '');
return embeddedModeState;
}
var nestedResult = nestedModeTokenizationSupport.tokenize(embeddedModeLine, embeddedModeState, offsetDelta);
this._tokens = this._tokens.concat(nestedResult.tokens);
this._lastTokenType = null;
this._lastTokenLanguage = null;
this._language = null;
return nestedResult.endState;
};
MonarchClassicTokensCollector.prototype.finalize = function (endState) {
return new token_1.TokenizationResult(this._tokens, endState);
};
return MonarchClassicTokensCollector;
}());
var MonarchModernTokensCollector = /** @class */ (function () {
function MonarchModernTokensCollector(modeService, theme) {
this._modeService = modeService;
this._theme = theme;
this._prependTokens = null;
this._tokens = [];
this._currentLanguageId = 0 /* Null */;
this._lastTokenMetadata = 0;
}
MonarchModernTokensCollector.prototype.enterMode = function (startOffset, modeId) {
this._currentLanguageId = this._modeService.getLanguageIdentifier(modeId).id;
};
MonarchModernTokensCollector.prototype.emit = function (startOffset, type) {
var metadata = this._theme.match(this._currentLanguageId, type);
if (this._lastTokenMetadata === metadata) {
return;
}
this._lastTokenMetadata = metadata;
this._tokens.push(startOffset);
this._tokens.push(metadata);
};
MonarchModernTokensCollector._merge = function (a, b, c) {
var aLen = (a !== null ? a.length : 0);
var bLen = b.length;
var cLen = (c !== null ? c.length : 0);
if (aLen === 0 && bLen === 0 && cLen === 0) {
return new Uint32Array(0);
}
if (aLen === 0 && bLen === 0) {
return c;
}
if (bLen === 0 && cLen === 0) {
return a;
}
var result = new Uint32Array(aLen + bLen + cLen);
if (a !== null) {
result.set(a);
}
for (var i = 0; i < bLen; i++) {
result[aLen + i] = b[i];
}
if (c !== null) {
result.set(c, aLen + bLen);
}
return result;
};
MonarchModernTokensCollector.prototype.nestedModeTokenize = function (embeddedModeLine, embeddedModeData, offsetDelta) {
var nestedModeId = embeddedModeData.modeId;
var embeddedModeState = embeddedModeData.state;
var nestedModeTokenizationSupport = modes.TokenizationRegistry.get(nestedModeId);
if (!nestedModeTokenizationSupport) {
this.enterMode(offsetDelta, nestedModeId);
this.emit(offsetDelta, '');
return embeddedModeState;
}
var nestedResult = nestedModeTokenizationSupport.tokenize2(embeddedModeLine, embeddedModeState, offsetDelta);
this._prependTokens = MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, nestedResult.tokens);
this._tokens = [];
this._currentLanguageId = 0;
this._lastTokenMetadata = 0;
return nestedResult.endState;
};
MonarchModernTokensCollector.prototype.finalize = function (endState) {
return new token_1.TokenizationResult2(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState);
};
return MonarchModernTokensCollector;
}());
var MonarchTokenizer = /** @class */ (function () {
function MonarchTokenizer(modeService, standaloneThemeService, modeId, lexer) {
var _this = this;
this._modeService = modeService;
this._standaloneThemeService = standaloneThemeService;
this._modeId = modeId;
this._lexer = lexer;
this._embeddedModes = Object.create(null);
this.embeddedLoaded = Promise.resolve(undefined);
// Set up listening for embedded modes
var emitting = false;
this._tokenizationRegistryListener = modes.TokenizationRegistry.onDidChange(function (e) {
if (emitting) {
return;
}
var isOneOfMyEmbeddedModes = false;
for (var i = 0, len = e.changedLanguages.length; i < len; i++) {
var language = e.changedLanguages[i];
if (_this._embeddedModes[language]) {
isOneOfMyEmbeddedModes = true;
break;
}
}
if (isOneOfMyEmbeddedModes) {
emitting = true;
modes.TokenizationRegistry.fire([_this._modeId]);
emitting = false;
}
});
}
MonarchTokenizer.prototype.dispose = function () {
this._tokenizationRegistryListener.dispose();
};
MonarchTokenizer.prototype.getLoadStatus = function () {
var promises = [];
for (var nestedModeId in this._embeddedModes) {
var tokenizationSupport = modes.TokenizationRegistry.get(nestedModeId);
if (tokenizationSupport) {
// The nested mode is already loaded
if (tokenizationSupport instanceof MonarchTokenizer) {
var nestedModeStatus = tokenizationSupport.getLoadStatus();
if (nestedModeStatus.loaded === false) {
promises.push(nestedModeStatus.promise);
}
}
continue;
}
var tokenizationSupportPromise = modes.TokenizationRegistry.getPromise(nestedModeId);
if (tokenizationSupportPromise) {
// The nested mode is in the process of being loaded
promises.push(tokenizationSupportPromise);
}
}
if (promises.length === 0) {
return {
loaded: true
};
}
return {
loaded: false,
promise: Promise.all(promises).then(function (_) { return undefined; })
};
};
MonarchTokenizer.prototype.getInitialState = function () {
var rootState = MonarchStackElementFactory.create(null, this._lexer.start);
return MonarchLineStateFactory.create(rootState, null);
};
MonarchTokenizer.prototype.tokenize = function (line, lineState, offsetDelta) {
var tokensCollector = new MonarchClassicTokensCollector();
var endLineState = this._tokenize(line, lineState, offsetDelta, tokensCollector);
return tokensCollector.finalize(endLineState);
};
MonarchTokenizer.prototype.tokenize2 = function (line, lineState, offsetDelta) {
var tokensCollector = new MonarchModernTokensCollector(this._modeService, this._standaloneThemeService.getTheme().tokenTheme);
var endLineState = this._tokenize(line, lineState, offsetDelta, tokensCollector);
return tokensCollector.finalize(endLineState);
};
MonarchTokenizer.prototype._tokenize = function (line, lineState, offsetDelta, collector) {
if (lineState.embeddedModeData) {
return this._nestedTokenize(line, lineState, offsetDelta, collector);
}
else {
return this._myTokenize(line, lineState, offsetDelta, collector);
}
};
MonarchTokenizer.prototype._findLeavingNestedModeOffset = function (line, state) {
var rules = this._lexer.tokenizer[state.stack.state];
if (!rules) {
rules = monarchCommon.findRules(this._lexer, state.stack.state); // do parent matching
if (!rules) {
throw monarchCommon.createError(this._lexer, 'tokenizer state is not defined: ' + state.stack.state);
}
}
var popOffset = -1;
var hasEmbeddedPopRule = false;
for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
var rule = rules_1[_i];
if (!monarchCommon.isIAction(rule.action) || rule.action.nextEmbedded !== '@pop') {
continue;
}
hasEmbeddedPopRule = true;
var regex = rule.regex;
var regexSource = rule.regex.source;
if (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') {
regex = new RegExp(regexSource.substr(4, regexSource.length - 5), regex.ignoreCase ? 'i' : '');
}
var result = line.search(regex);
if (result === -1 || (result !== 0 && rule.matchOnlyAtLineStart)) {
continue;
}
if (popOffset === -1 || result < popOffset) {
popOffset = result;
}
}
if (!hasEmbeddedPopRule) {
throw monarchCommon.createError(this._lexer, 'no rule containing nextEmbedded: "@pop" in tokenizer embedded state: ' + state.stack.state);
}
return popOffset;
};
MonarchTokenizer.prototype._nestedTokenize = function (line, lineState, offsetDelta, tokensCollector) {
var popOffset = this._findLeavingNestedModeOffset(line, lineState);
if (popOffset === -1) {
// tokenization will not leave nested mode
var nestedEndState = tokensCollector.nestedModeTokenize(line, lineState.embeddedModeData, offsetDelta);
return MonarchLineStateFactory.create(lineState.stack, new EmbeddedModeData(lineState.embeddedModeData.modeId, nestedEndState));
}
var nestedModeLine = line.substring(0, popOffset);
if (nestedModeLine.length > 0) {
// tokenize with the nested mode
tokensCollector.nestedModeTokenize(nestedModeLine, lineState.embeddedModeData, offsetDelta);
}
var restOfTheLine = line.substring(popOffset);
return this._myTokenize(restOfTheLine, lineState, offsetDelta + popOffset, tokensCollector);
};
MonarchTokenizer.prototype._safeRuleName = function (rule) {
if (rule) {
return rule.name;
}
return '(unknown)';
};
MonarchTokenizer.prototype._myTokenize = function (line, lineState, offsetDelta, tokensCollector) {
tokensCollector.enterMode(offsetDelta, this._modeId);
var lineLength = line.length;
var embeddedModeData = lineState.embeddedModeData;
var stack = lineState.stack;
var pos = 0;
var groupMatching = null;
// See https://github.com/Microsoft/monaco-editor/issues/1235:
// Evaluate rules at least once for an empty line
var forceEvaluation = true;
while (forceEvaluation || pos < lineLength) {
var pos0 = pos;
var stackLen0 = stack.depth;
var groupLen0 = groupMatching ? groupMatching.groups.length : 0;
var state = stack.state;
var matches = null;
var matched = null;
var action = null;
var rule = null;
var enteringEmbeddedMode = null;
// check if we need to process group matches first
if (groupMatching) {
matches = groupMatching.matches;
var groupEntry = groupMatching.groups.shift();
matched = groupEntry.matched;
action = groupEntry.action;
rule = groupMatching.rule;
// cleanup if necessary
if (groupMatching.groups.length === 0) {
groupMatching = null;
}
}
else {
// otherwise we match on the token stream
if (!forceEvaluation && pos >= lineLength) {
// nothing to do
break;
}
forceEvaluation = false;
// get the rules for this state
var rules = this._lexer.tokenizer[state];
if (!rules) {
rules = monarchCommon.findRules(this._lexer, state); // do parent matching
if (!rules) {
throw monarchCommon.createError(this._lexer, 'tokenizer state is not defined: ' + state);
}
}
// try each rule until we match
var restOfLine = line.substr(pos);
for (var _i = 0, rules_2 = rules; _i < rules_2.length; _i++) {
var rule_1 = rules_2[_i];
if (pos === 0 || !rule_1.matchOnlyAtLineStart) {
matches = restOfLine.match(rule_1.regex);
if (matches) {
matched = matches[0];
action = rule_1.action;
break;
}
}
}
}
// We matched 'rule' with 'matches' and 'action'
if (!matches) {
matches = [''];
matched = '';
}
if (!action) {
// bad: we didn't match anything, and there is no action to take
// we need to advance the stream or we get progress trouble
if (pos < lineLength) {
matches = [line.charAt(pos)];
matched = matches[0];
}
action = this._lexer.defaultToken;
}
if (matched === null) {
// should never happen, needed for strict null checking
break;
}
// advance stream
pos += matched.length;
// maybe call action function (used for 'cases')
while (monarchCommon.isFuzzyAction(action) && monarchCommon.isIAction(action) && action.test) {
action = action.test(matched, matches, state, pos === lineLength);
}
var result = null;
// set the result: either a string or an array of actions
if (typeof action === 'string' || Array.isArray(action)) {
result = action;
}
else if (action.group) {
result = action.group;
}
else if (action.token !== null && action.token !== undefined) {
// do $n replacements?
if (action.tokenSubst) {
result = monarchCommon.substituteMatches(this._lexer, action.token, matched, matches, state);
}
else {
result = action.token;
}
// enter embedded mode?
if (action.nextEmbedded) {
if (action.nextEmbedded === '@pop') {
if (!embeddedModeData) {
throw monarchCommon.createError(this._lexer, 'cannot pop embedded mode if not inside one');
}
embeddedModeData = null;
}
else if (embeddedModeData) {
throw monarchCommon.createError(this._lexer, 'cannot enter embedded mode from within an embedded mode');
}
else {
enteringEmbeddedMode = monarchCommon.substituteMatches(this._lexer, action.nextEmbedded, matched, matches, state);
}
}
// state transformations
if (action.goBack) { // back up the stream..
pos = Math.max(0, pos - action.goBack);
}
if (action.switchTo && typeof action.switchTo === 'string') {
var nextState = monarchCommon.substituteMatches(this._lexer, action.switchTo, matched, matches, state); // switch state without a push...
if (nextState[0] === '@') {
nextState = nextState.substr(1); // peel off starting '@'
}
if (!monarchCommon.findRules(this._lexer, nextState)) {
throw monarchCommon.createError(this._lexer, 'trying to switch to a state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule));
}
else {
stack = stack.switchTo(nextState);
}
}
else if (action.transform && typeof action.transform === 'function') {
throw monarchCommon.createError(this._lexer, 'action.transform not supported');
}
else if (action.next) {
if (action.next === '@push') {
if (stack.depth >= this._lexer.maxStack) {
throw monarchCommon.createError(this._lexer, 'maximum tokenizer stack size reached: [' +
stack.state + ',' + stack.parent.state + ',...]');
}
else {
stack = stack.push(state);
}
}
else if (action.next === '@pop') {
if (stack.depth <= 1) {
throw monarchCommon.createError(this._lexer, 'trying to pop an empty stack in rule: ' + this._safeRuleName(rule));
}
else {
stack = stack.pop();
}
}
else if (action.next === '@popall') {
stack = stack.popall();
}
else {
var nextState = monarchCommon.substituteMatches(this._lexer, action.next, matched, matches, state);
if (nextState[0] === '@') {
nextState = nextState.substr(1); // peel off starting '@'
}
if (!monarchCommon.findRules(this._lexer, nextState)) {
throw monarchCommon.createError(this._lexer, 'trying to set a next state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule));
}
else {
stack = stack.push(nextState);
}
}
}
if (action.log && typeof (action.log) === 'string') {
monarchCommon.log(this._lexer, this._lexer.languageId + ': ' + monarchCommon.substituteMatches(this._lexer, action.log, matched, matches, state));
}
}
// check result
if (result === null) {
throw monarchCommon.createError(this._lexer, 'lexer rule has no well-defined action in rule: ' + this._safeRuleName(rule));
}
// is the result a group match?
if (Array.isArray(result)) {
if (groupMatching && groupMatching.groups.length > 0) {
throw monarchCommon.createError(this._lexer, 'groups cannot be nested: ' + this._safeRuleName(rule));
}
if (matches.length !== result.length + 1) {
throw monarchCommon.createError(this._lexer, 'matched number of groups does not match the number of actions in rule: ' + this._safeRuleName(rule));
}
var totalLen = 0;
for (var i = 1; i < matches.length; i++) {
totalLen += matches[i].length;
}
if (totalLen !== matched.length) {
throw monarchCommon.createError(this._lexer, 'with groups, all characters should be matched in consecutive groups in rule: ' + this._safeRuleName(rule));
}
groupMatching = {
rule: rule,
matches: matches,
groups: []
};
for (var i = 0; i < result.length; i++) {
groupMatching.groups[i] = {
action: result[i],
matched: matches[i + 1]
};
}
pos -= matched.length;
// call recursively to initiate first result match
continue;
}
else {
// regular result
// check for '@rematch'
if (result === '@rematch') {
pos -= matched.length;
matched = ''; // better set the next state too..
matches = null;
result = '';
}
// check progress
if (matched.length === 0) {
if (lineLength === 0 || stackLen0 !== stack.depth || state !== stack.state || (!groupMatching ? 0 : groupMatching.groups.length) !== groupLen0) {
continue;
}
else {
throw monarchCommon.createError(this._lexer, 'no progress in tokenizer in rule: ' + this._safeRuleName(rule));
}
}
// return the result (and check for brace matching)
// todo: for efficiency we could pre-sanitize tokenPostfix and substitutions
var tokenType = null;
if (monarchCommon.isString(result) && result.indexOf('@brackets') === 0) {
var rest = result.substr('@brackets'.length);
var bracket = findBracket(this._lexer, matched);
if (!bracket) {
throw monarchCommon.createError(this._lexer, '@brackets token returned but no bracket defined as: ' + matched);
}
tokenType = monarchCommon.sanitize(bracket.token + rest);
}
else {
var token = (result === '' ? '' : result + this._lexer.tokenPostfix);
tokenType = monarchCommon.sanitize(token);
}
tokensCollector.emit(pos0 + offsetDelta, tokenType);
}
if (enteringEmbeddedMode !== null) {
// substitute language alias to known modes to support syntax highlighting
var enteringEmbeddedModeId = this._modeService.getModeIdForLanguageName(enteringEmbeddedMode);
if (enteringEmbeddedModeId) {
enteringEmbeddedMode = enteringEmbeddedModeId;
}
var embeddedModeData_1 = this._getNestedEmbeddedModeData(enteringEmbeddedMode);
if (pos < lineLength) {
// there is content from the embedded mode on this line
var restOfLine = line.substr(pos);
return this._nestedTokenize(restOfLine, MonarchLineStateFactory.create(stack, embeddedModeData_1), offsetDelta + pos, tokensCollector);
}
else {
return MonarchLineStateFactory.create(stack, embeddedModeData_1);
}
}
}
return MonarchLineStateFactory.create(stack, embeddedModeData);
};
MonarchTokenizer.prototype._getNestedEmbeddedModeData = function (mimetypeOrModeId) {
var nestedModeId = this._locateMode(mimetypeOrModeId);
if (nestedModeId) {
var tokenizationSupport = modes.TokenizationRegistry.get(nestedModeId);
if (tokenizationSupport) {
return new EmbeddedModeData(nestedModeId, tokenizationSupport.getInitialState());
}
}
return new EmbeddedModeData(nestedModeId || nullMode_1.NULL_MODE_ID, nullMode_1.NULL_STATE);
};
MonarchTokenizer.prototype._locateMode = function (mimetypeOrModeId) {
if (!mimetypeOrModeId || !this._modeService.isRegisteredMode(mimetypeOrModeId)) {
return null;
}
if (mimetypeOrModeId === this._modeId) {
// embedding myself...
return mimetypeOrModeId;
}
var modeId = this._modeService.getModeId(mimetypeOrModeId);
if (modeId) {
// Fire mode loading event
this._modeService.triggerMode(modeId);
this._embeddedModes[modeId] = true;
}
return modeId;
};
return MonarchTokenizer;
}());
exports.MonarchTokenizer = MonarchTokenizer;
/**
* Searches for a bracket in the 'brackets' attribute that matches the input.
*/
function findBracket(lexer, matched) {
if (!matched) {
return null;
}
matched = monarchCommon.fixCase(lexer, matched);
var brackets = lexer.brackets;
for (var _i = 0, brackets_1 = brackets; _i < brackets_1.length; _i++) {
var bracket = brackets_1[_i];
if (bracket.open === matched) {
return { token: bracket.token, bracketType: 1 /* Open */ };
}
else if (bracket.close === matched) {
return { token: bracket.token, bracketType: -1 /* Close */ };
}
}
return null;
}
function createTokenizationSupport(modeService, standaloneThemeService, modeId, lexer) {
return new MonarchTokenizer(modeService, standaloneThemeService, modeId, lexer);
}
exports.createTokenizationSupport = createTokenizationSupport;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[494/*vs/editor/standalone/browser/colorizer*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,5/*vs/base/common/strings*/,93/*vs/editor/common/core/lineTokens*/,17/*vs/editor/common/modes*/,110/*vs/editor/common/viewLayout/viewLineRenderer*/,69/*vs/editor/common/viewModel/viewModel*/,216/*vs/editor/standalone/common/monarch/monarchLexer*/]), function (require, exports, async_1, strings, lineTokens_1, modes_1, viewLineRenderer_1, viewModel_1, monarchLexer_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Colorizer = /** @class */ (function () {
function Colorizer() {
}
Colorizer.colorizeElement = function (themeService, modeService, domNode, options) {
options = options || {};
var theme = options.theme || 'vs';
var mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang');
if (!mimeType) {
console.error('Mode not detected');
return Promise.resolve();
}
themeService.setTheme(theme);
var text = domNode.firstChild ? domNode.firstChild.nodeValue : '';
domNode.className += ' ' + theme;
var render = function (str) {
domNode.innerHTML = str;
};
return this.colorize(modeService, text || '', mimeType, options).then(render, function (err) { return console.error(err); });
};
Colorizer.colorize = function (modeService, text, mimeType, options) {
var tabSize = 4;
if (options && typeof options.tabSize === 'number') {
tabSize = options.tabSize;
}
if (strings.startsWithUTF8BOM(text)) {
text = text.substr(1);
}
var lines = text.split(/\r\n|\r|\n/);
var language = modeService.getModeId(mimeType);
if (!language) {
return Promise.resolve(_fakeColorize(lines, tabSize));
}
// Send out the event to create the mode
modeService.triggerMode(language);
var tokenizationSupport = modes_1.TokenizationRegistry.get(language);
if (tokenizationSupport) {
return _colorize(lines, tabSize, tokenizationSupport);
}
var tokenizationSupportPromise = modes_1.TokenizationRegistry.getPromise(language);
if (tokenizationSupportPromise) {
// A tokenizer will be registered soon
return new Promise(function (resolve, reject) {
tokenizationSupportPromise.then(function (tokenizationSupport) {
_colorize(lines, tabSize, tokenizationSupport).then(resolve, reject);
}, reject);
});
}
return new Promise(function (resolve, reject) {
var listener = null;
var timeout = null;
var execute = function () {
if (listener) {
listener.dispose();
listener = null;
}
if (timeout) {
timeout.dispose();
timeout = null;
}
var tokenizationSupport = modes_1.TokenizationRegistry.get(language);
if (tokenizationSupport) {
_colorize(lines, tabSize, tokenizationSupport).then(resolve, reject);
return;
}
resolve(_fakeColorize(lines, tabSize));
};
// wait 500ms for mode to load, then give up
timeout = new async_1.TimeoutTimer();
timeout.cancelAndSet(execute, 500);
listener = modes_1.TokenizationRegistry.onDidChange(function (e) {
if (e.changedLanguages.indexOf(language) >= 0) {
execute();
}
});
});
};
Colorizer.colorizeLine = function (line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize) {
if (tabSize === void 0) { tabSize = 4; }
var isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII);
var containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, mightContainRTL);
var renderResult = viewLineRenderer_1.renderViewLine2(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, tokens, [], tabSize, 0, 0, 0, -1, 'none', false, false, null));
return renderResult.html;
};
Colorizer.colorizeModelLine = function (model, lineNumber, tabSize) {
if (tabSize === void 0) { tabSize = 4; }
var content = model.getLineContent(lineNumber);
model.forceTokenization(lineNumber);
var tokens = model.getLineTokens(lineNumber);
var inflatedTokens = tokens.inflate();
return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize);
};
return Colorizer;
}());
exports.Colorizer = Colorizer;
function _colorize(lines, tabSize, tokenizationSupport) {
return new Promise(function (c, e) {
var execute = function () {
var result = _actualColorize(lines, tabSize, tokenizationSupport);
if (tokenizationSupport instanceof monarchLexer_1.MonarchTokenizer) {
var status_1 = tokenizationSupport.getLoadStatus();
if (status_1.loaded === false) {
status_1.promise.then(execute, e);
return;
}
}
c(result);
};
execute();
});
}
function _fakeColorize(lines, tabSize) {
var html = [];
var defaultMetadata = ((0 /* None */ << 11 /* FONT_STYLE_OFFSET */)
| (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */)
| (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0;
var tokens = new Uint32Array(2);
tokens[0] = 0;
tokens[1] = defaultMetadata;
for (var i = 0, length_1 = lines.length; i < length_1; i++) {
var line = lines[i];
tokens[0] = line.length;
var lineTokens = new lineTokens_1.LineTokens(tokens, line);
var isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true);
var containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true);
var renderResult = viewLineRenderer_1.renderViewLine2(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, 0, 0, -1, 'none', false, false, null));
html = html.concat(renderResult.html);
html.push(' ');
}
return html.join('');
}
function _actualColorize(lines, tabSize, tokenizationSupport) {
var html = [];
var state = tokenizationSupport.getInitialState();
for (var i = 0, length_2 = lines.length; i < length_2; i++) {
var line = lines[i];
var tokenizeResult = tokenizationSupport.tokenize2(line, state, 0);
lineTokens_1.LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length);
var lineTokens = new lineTokens_1.LineTokens(tokenizeResult.tokens, line);
var isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true);
var containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true);
var renderResult = viewLineRenderer_1.renderViewLine2(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens.inflate(), [], tabSize, 0, 0, 0, -1, 'none', false, false, null));
html = html.concat(renderResult.html);
html.push(' ');
state = tokenizeResult.endState;
}
return html.join('');
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[94/*vs/editor/standalone/common/standaloneThemeService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IStandaloneThemeService = instantiation_1.createDecorator('themeService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[162/*vs/platform/clipboard/common/clipboardService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IClipboardService = instantiation_1.createDecorator('clipboardService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[29/*vs/platform/commands/common/commands*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/types*/,11/*vs/platform/instantiation/common/instantiation*/,4/*vs/base/common/event*/,76/*vs/base/common/linkedList*/,38/*vs/base/common/map*/]), function (require, exports, lifecycle_1, types_1, instantiation_1, event_1, linkedList_1, map_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ICommandService = instantiation_1.createDecorator('commandService');
exports.CommandsRegistry = new /** @class */ (function () {
function class_1() {
this._commands = new Map();
this._onDidRegisterCommand = new event_1.Emitter();
this.onDidRegisterCommand = this._onDidRegisterCommand.event;
}
class_1.prototype.registerCommand = function (idOrCommand, handler) {
var _this = this;
if (!idOrCommand) {
throw new Error("invalid command");
}
if (typeof idOrCommand === 'string') {
if (!handler) {
throw new Error("invalid command");
}
return this.registerCommand({ id: idOrCommand, handler: handler });
}
// add argument validation if rich command metadata is provided
if (idOrCommand.description) {
var constraints_1 = [];
for (var _i = 0, _a = idOrCommand.description.args; _i < _a.length; _i++) {
var arg = _a[_i];
constraints_1.push(arg.constraint);
}
var actualHandler_1 = idOrCommand.handler;
idOrCommand.handler = function (accessor) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
types_1.validateConstraints(args, constraints_1);
return actualHandler_1.apply(void 0, __spreadArrays([accessor], args));
};
}
// find a place to store the command
var id = idOrCommand.id;
var commands = this._commands.get(id);
if (!commands) {
commands = new linkedList_1.LinkedList();
this._commands.set(id, commands);
}
var removeFn = commands.unshift(idOrCommand);
var ret = lifecycle_1.toDisposable(function () {
removeFn();
var command = _this._commands.get(id);
if (command === null || command === void 0 ? void 0 : command.isEmpty()) {
_this._commands.delete(id);
}
});
// tell the world about this command
this._onDidRegisterCommand.fire(id);
return ret;
};
class_1.prototype.registerCommandAlias = function (oldId, newId) {
return exports.CommandsRegistry.registerCommand(oldId, function (accessor) {
var _a;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return (_a = accessor.get(exports.ICommandService)).executeCommand.apply(_a, __spreadArrays([newId], args));
});
};
class_1.prototype.getCommand = function (id) {
var list = this._commands.get(id);
if (!list || list.isEmpty()) {
return undefined;
}
return list.iterator().next().value;
};
class_1.prototype.getCommands = function () {
var result = new Map();
for (var _i = 0, _a = map_1.keys(this._commands); _i < _a.length; _i++) {
var key = _a[_i];
var command = this.getCommand(key);
if (command) {
result.set(key, command);
}
}
return result;
};
return class_1;
}());
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[495/*vs/editor/contrib/links/getLinks*/], __M([0/*require*/,1/*exports*/,26/*vs/base/common/cancellation*/,10/*vs/base/common/errors*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,49/*vs/editor/common/services/modelService*/,29/*vs/platform/commands/common/commands*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/arrays*/]), function (require, exports, cancellation_1, errors_1, uri_1, range_1, modes_1, modelService_1, commands_1, lifecycle_1, arrays_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Link = /** @class */ (function () {
function Link(link, provider) {
this._link = link;
this._provider = provider;
}
Link.prototype.toJSON = function () {
return {
range: this.range,
url: this.url,
tooltip: this.tooltip
};
};
Object.defineProperty(Link.prototype, "range", {
get: function () {
return this._link.range;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Link.prototype, "url", {
get: function () {
return this._link.url;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Link.prototype, "tooltip", {
get: function () {
return this._link.tooltip;
},
enumerable: true,
configurable: true
});
Link.prototype.resolve = function (token) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
if (this._link.url) {
return [2 /*return*/, this._link.url];
}
if (typeof this._provider.resolveLink === 'function') {
return [2 /*return*/, Promise.resolve(this._provider.resolveLink(this._link, token)).then(function (value) {
_this._link = value || _this._link;
if (_this._link.url) {
// recurse
return _this.resolve(token);
}
return Promise.reject(new Error('missing'));
})];
}
return [2 /*return*/, Promise.reject(new Error('missing'))];
});
});
};
return Link;
}());
exports.Link = Link;
var LinksList = /** @class */ (function (_super) {
__extends(LinksList, _super);
function LinksList(tuples) {
var _this = _super.call(this) || this;
var links = [];
var _loop_1 = function (list, provider) {
// merge all links
var newLinks = list.links.map(function (link) { return new Link(link, provider); });
links = LinksList._union(links, newLinks);
// register disposables
if (lifecycle_1.isDisposable(provider)) {
this_1._register(provider);
}
};
var this_1 = this;
for (var _i = 0, tuples_1 = tuples; _i < tuples_1.length; _i++) {
var _a = tuples_1[_i], list = _a[0], provider = _a[1];
_loop_1(list, provider);
}
_this.links = links;
return _this;
}
LinksList._union = function (oldLinks, newLinks) {
// reunite oldLinks with newLinks and remove duplicates
var result = [];
var oldIndex;
var oldLen;
var newIndex;
var newLen;
for (oldIndex = 0, newIndex = 0, oldLen = oldLinks.length, newLen = newLinks.length; oldIndex < oldLen && newIndex < newLen;) {
var oldLink = oldLinks[oldIndex];
var newLink = newLinks[newIndex];
if (range_1.Range.areIntersectingOrTouching(oldLink.range, newLink.range)) {
// Remove the oldLink
oldIndex++;
continue;
}
var comparisonResult = range_1.Range.compareRangesUsingStarts(oldLink.range, newLink.range);
if (comparisonResult < 0) {
// oldLink is before
result.push(oldLink);
oldIndex++;
}
else {
// newLink is before
result.push(newLink);
newIndex++;
}
}
for (; oldIndex < oldLen; oldIndex++) {
result.push(oldLinks[oldIndex]);
}
for (; newIndex < newLen; newIndex++) {
result.push(newLinks[newIndex]);
}
return result;
};
return LinksList;
}(lifecycle_1.Disposable));
exports.LinksList = LinksList;
function getLinks(model, token) {
var lists = [];
// ask all providers for links in parallel
var promises = modes_1.LinkProviderRegistry.ordered(model).reverse().map(function (provider, i) {
return Promise.resolve(provider.provideLinks(model, token)).then(function (result) {
if (result) {
lists[i] = [result, provider];
}
}, errors_1.onUnexpectedExternalError);
});
return Promise.all(promises).then(function () {
var result = new LinksList(arrays_1.coalesce(lists));
if (!token.isCancellationRequested) {
return result;
}
result.dispose();
return new LinksList([]);
});
}
exports.getLinks = getLinks;
commands_1.CommandsRegistry.registerCommand('_executeLinkProvider', function (accessor) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return __awaiter(void 0, void 0, void 0, function () {
var uri, model, list, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
uri = args[0];
if (!(uri instanceof uri_1.URI)) {
return [2 /*return*/, []];
}
model = accessor.get(modelService_1.IModelService).getModel(uri);
if (!model) {
return [2 /*return*/, []];
}
return [4 /*yield*/, getLinks(model, cancellation_1.CancellationToken.None)];
case 1:
list = _a.sent();
if (!list) {
return [2 /*return*/, []];
}
result = list.links.slice(0);
list.dispose();
return [2 /*return*/, result];
}
});
});
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[496/*vs/editor/contrib/quickOpen/quickOpen*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,3/*vs/editor/common/core/range*/,49/*vs/editor/common/services/modelService*/,26/*vs/base/common/cancellation*/,84/*vs/editor/common/services/resolverService*/,489/*vs/editor/contrib/documentSymbols/outlineModel*/,87/*vs/base/common/collections*/,29/*vs/platform/commands/common/commands*/,21/*vs/base/common/types*/]), function (require, exports, uri_1, range_1, modelService_1, cancellation_1, resolverService_1, outlineModel_1, collections_1, commands_1, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getDocumentSymbols(document, flat, token) {
return __awaiter(this, void 0, void 0, function () {
var model, roots, _i, _a, child, flatEntries;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, outlineModel_1.OutlineModel.create(document, token)];
case 1:
model = _b.sent();
roots = [];
for (_i = 0, _a = collections_1.values(model.children); _i < _a.length; _i++) {
child = _a[_i];
if (child instanceof outlineModel_1.OutlineElement) {
roots.push(child.symbol);
}
else {
roots.push.apply(roots, collections_1.values(child.children).map(function (child) { return child.symbol; }));
}
}
flatEntries = [];
if (token.isCancellationRequested) {
return [2 /*return*/, flatEntries];
}
if (flat) {
flatten(flatEntries, roots, '');
}
else {
flatEntries = roots;
}
return [2 /*return*/, flatEntries.sort(compareEntriesUsingStart)];
}
});
});
}
exports.getDocumentSymbols = getDocumentSymbols;
function compareEntriesUsingStart(a, b) {
return range_1.Range.compareRangesUsingStarts(a.range, b.range);
}
function flatten(bucket, entries, overrideContainerLabel) {
for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
var entry = entries_1[_i];
bucket.push({
kind: entry.kind,
tags: entry.tags,
name: entry.name,
detail: entry.detail,
containerName: entry.containerName || overrideContainerLabel,
range: entry.range,
selectionRange: entry.selectionRange,
children: undefined,
});
if (entry.children) {
flatten(bucket, entry.children, entry.name);
}
}
}
commands_1.CommandsRegistry.registerCommand('_executeDocumentSymbolProvider', function (accessor) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var resource, model, reference;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
resource = args[0];
types_1.assertType(uri_1.URI.isUri(resource));
model = accessor.get(modelService_1.IModelService).getModel(resource);
if (model) {
return [2 /*return*/, getDocumentSymbols(model, false, cancellation_1.CancellationToken.None)];
}
return [4 /*yield*/, accessor.get(resolverService_1.ITextModelService).createModelReference(resource)];
case 1:
reference = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, , 4, 5]);
return [4 /*yield*/, getDocumentSymbols(reference.object.textEditorModel, false, cancellation_1.CancellationToken.None)];
case 3: return [2 /*return*/, _a.sent()];
case 4:
reference.dispose();
return [7 /*endfinally*/];
case 5: return [2 /*return*/];
}
});
});
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[18/*vs/platform/contextkey/common/contextkey*/], __M([0/*require*/,1/*exports*/,5/*vs/base/common/strings*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, strings_1, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ContextKeyExpr = /** @class */ (function () {
function ContextKeyExpr() {
}
ContextKeyExpr.has = function (key) {
return ContextKeyDefinedExpr.create(key);
};
ContextKeyExpr.equals = function (key, value) {
return ContextKeyEqualsExpr.create(key, value);
};
ContextKeyExpr.regex = function (key, value) {
return ContextKeyRegexExpr.create(key, value);
};
ContextKeyExpr.not = function (key) {
return ContextKeyNotExpr.create(key);
};
ContextKeyExpr.and = function () {
var expr = [];
for (var _i = 0; _i < arguments.length; _i++) {
expr[_i] = arguments[_i];
}
return ContextKeyAndExpr.create(expr);
};
ContextKeyExpr.or = function () {
var expr = [];
for (var _i = 0; _i < arguments.length; _i++) {
expr[_i] = arguments[_i];
}
return ContextKeyOrExpr.create(expr);
};
ContextKeyExpr.deserialize = function (serialized, strict) {
if (strict === void 0) { strict = false; }
if (!serialized) {
return undefined;
}
return this._deserializeOrExpression(serialized, strict);
};
ContextKeyExpr._deserializeOrExpression = function (serialized, strict) {
var _this = this;
var pieces = serialized.split('||');
return ContextKeyOrExpr.create(pieces.map(function (p) { return _this._deserializeAndExpression(p, strict); }));
};
ContextKeyExpr._deserializeAndExpression = function (serialized, strict) {
var _this = this;
var pieces = serialized.split('&&');
return ContextKeyAndExpr.create(pieces.map(function (p) { return _this._deserializeOne(p, strict); }));
};
ContextKeyExpr._deserializeOne = function (serializedOne, strict) {
serializedOne = serializedOne.trim();
if (serializedOne.indexOf('!=') >= 0) {
var pieces = serializedOne.split('!=');
return ContextKeyNotEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict));
}
if (serializedOne.indexOf('==') >= 0) {
var pieces = serializedOne.split('==');
return ContextKeyEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict));
}
if (serializedOne.indexOf('=~') >= 0) {
var pieces = serializedOne.split('=~');
return ContextKeyRegexExpr.create(pieces[0].trim(), this._deserializeRegexValue(pieces[1], strict));
}
if (/^\!\s*/.test(serializedOne)) {
return ContextKeyNotExpr.create(serializedOne.substr(1).trim());
}
return ContextKeyDefinedExpr.create(serializedOne);
};
ContextKeyExpr._deserializeValue = function (serializedValue, strict) {
serializedValue = serializedValue.trim();
if (serializedValue === 'true') {
return true;
}
if (serializedValue === 'false') {
return false;
}
var m = /^'([^']*)'$/.exec(serializedValue);
if (m) {
return m[1].trim();
}
return serializedValue;
};
ContextKeyExpr._deserializeRegexValue = function (serializedValue, strict) {
if (strings_1.isFalsyOrWhitespace(serializedValue)) {
if (strict) {
throw new Error('missing regexp-value for =~-expression');
}
else {
console.warn('missing regexp-value for =~-expression');
}
return null;
}
var start = serializedValue.indexOf('/');
var end = serializedValue.lastIndexOf('/');
if (start === end || start < 0 /* || to < 0 */) {
if (strict) {
throw new Error("bad regexp-value '" + serializedValue + "', missing /-enclosure");
}
else {
console.warn("bad regexp-value '" + serializedValue + "', missing /-enclosure");
}
return null;
}
var value = serializedValue.slice(start + 1, end);
var caseIgnoreFlag = serializedValue[end + 1] === 'i' ? 'i' : '';
try {
return new RegExp(value, caseIgnoreFlag);
}
catch (e) {
if (strict) {
throw new Error("bad regexp-value '" + serializedValue + "', parse error: " + e);
}
else {
console.warn("bad regexp-value '" + serializedValue + "', parse error: " + e);
}
return null;
}
};
return ContextKeyExpr;
}());
exports.ContextKeyExpr = ContextKeyExpr;
function cmp(a, b) {
var aType = a.getType();
var bType = b.getType();
if (aType !== bType) {
return aType - bType;
}
switch (aType) {
case 1 /* Defined */:
return a.cmp(b);
case 2 /* Not */:
return a.cmp(b);
case 3 /* Equals */:
return a.cmp(b);
case 4 /* NotEquals */:
return a.cmp(b);
case 6 /* Regex */:
return a.cmp(b);
case 7 /* NotRegex */:
return a.cmp(b);
case 5 /* And */:
return a.cmp(b);
default:
throw new Error('Unknown ContextKeyExpr!');
}
}
var ContextKeyDefinedExpr = /** @class */ (function () {
function ContextKeyDefinedExpr(key) {
this.key = key;
}
ContextKeyDefinedExpr.create = function (key) {
return new ContextKeyDefinedExpr(key);
};
ContextKeyDefinedExpr.prototype.getType = function () {
return 1 /* Defined */;
};
ContextKeyDefinedExpr.prototype.cmp = function (other) {
if (this.key < other.key) {
return -1;
}
if (this.key > other.key) {
return 1;
}
return 0;
};
ContextKeyDefinedExpr.prototype.equals = function (other) {
if (other instanceof ContextKeyDefinedExpr) {
return (this.key === other.key);
}
return false;
};
ContextKeyDefinedExpr.prototype.evaluate = function (context) {
return (!!context.getValue(this.key));
};
ContextKeyDefinedExpr.prototype.keys = function () {
return [this.key];
};
ContextKeyDefinedExpr.prototype.negate = function () {
return ContextKeyNotExpr.create(this.key);
};
return ContextKeyDefinedExpr;
}());
exports.ContextKeyDefinedExpr = ContextKeyDefinedExpr;
var ContextKeyEqualsExpr = /** @class */ (function () {
function ContextKeyEqualsExpr(key, value) {
this.key = key;
this.value = value;
}
ContextKeyEqualsExpr.create = function (key, value) {
if (typeof value === 'boolean') {
if (value) {
return ContextKeyDefinedExpr.create(key);
}
return ContextKeyNotExpr.create(key);
}
return new ContextKeyEqualsExpr(key, value);
};
ContextKeyEqualsExpr.prototype.getType = function () {
return 3 /* Equals */;
};
ContextKeyEqualsExpr.prototype.cmp = function (other) {
if (this.key < other.key) {
return -1;
}
if (this.key > other.key) {
return 1;
}
if (this.value < other.value) {
return -1;
}
if (this.value > other.value) {
return 1;
}
return 0;
};
ContextKeyEqualsExpr.prototype.equals = function (other) {
if (other instanceof ContextKeyEqualsExpr) {
return (this.key === other.key && this.value === other.value);
}
return false;
};
ContextKeyEqualsExpr.prototype.evaluate = function (context) {
// Intentional ==
// eslint-disable-next-line eqeqeq
return (context.getValue(this.key) == this.value);
};
ContextKeyEqualsExpr.prototype.keys = function () {
return [this.key];
};
ContextKeyEqualsExpr.prototype.negate = function () {
return ContextKeyNotEqualsExpr.create(this.key, this.value);
};
return ContextKeyEqualsExpr;
}());
exports.ContextKeyEqualsExpr = ContextKeyEqualsExpr;
var ContextKeyNotEqualsExpr = /** @class */ (function () {
function ContextKeyNotEqualsExpr(key, value) {
this.key = key;
this.value = value;
}
ContextKeyNotEqualsExpr.create = function (key, value) {
if (typeof value === 'boolean') {
if (value) {
return ContextKeyNotExpr.create(key);
}
return ContextKeyDefinedExpr.create(key);
}
return new ContextKeyNotEqualsExpr(key, value);
};
ContextKeyNotEqualsExpr.prototype.getType = function () {
return 4 /* NotEquals */;
};
ContextKeyNotEqualsExpr.prototype.cmp = function (other) {
if (this.key < other.key) {
return -1;
}
if (this.key > other.key) {
return 1;
}
if (this.value < other.value) {
return -1;
}
if (this.value > other.value) {
return 1;
}
return 0;
};
ContextKeyNotEqualsExpr.prototype.equals = function (other) {
if (other instanceof ContextKeyNotEqualsExpr) {
return (this.key === other.key && this.value === other.value);
}
return false;
};
ContextKeyNotEqualsExpr.prototype.evaluate = function (context) {
// Intentional !=
// eslint-disable-next-line eqeqeq
return (context.getValue(this.key) != this.value);
};
ContextKeyNotEqualsExpr.prototype.keys = function () {
return [this.key];
};
ContextKeyNotEqualsExpr.prototype.negate = function () {
return ContextKeyEqualsExpr.create(this.key, this.value);
};
return ContextKeyNotEqualsExpr;
}());
exports.ContextKeyNotEqualsExpr = ContextKeyNotEqualsExpr;
var ContextKeyNotExpr = /** @class */ (function () {
function ContextKeyNotExpr(key) {
this.key = key;
}
ContextKeyNotExpr.create = function (key) {
return new ContextKeyNotExpr(key);
};
ContextKeyNotExpr.prototype.getType = function () {
return 2 /* Not */;
};
ContextKeyNotExpr.prototype.cmp = function (other) {
if (this.key < other.key) {
return -1;
}
if (this.key > other.key) {
return 1;
}
return 0;
};
ContextKeyNotExpr.prototype.equals = function (other) {
if (other instanceof ContextKeyNotExpr) {
return (this.key === other.key);
}
return false;
};
ContextKeyNotExpr.prototype.evaluate = function (context) {
return (!context.getValue(this.key));
};
ContextKeyNotExpr.prototype.keys = function () {
return [this.key];
};
ContextKeyNotExpr.prototype.negate = function () {
return ContextKeyDefinedExpr.create(this.key);
};
return ContextKeyNotExpr;
}());
exports.ContextKeyNotExpr = ContextKeyNotExpr;
var ContextKeyRegexExpr = /** @class */ (function () {
function ContextKeyRegexExpr(key, regexp) {
this.key = key;
this.regexp = regexp;
//
}
ContextKeyRegexExpr.create = function (key, regexp) {
return new ContextKeyRegexExpr(key, regexp);
};
ContextKeyRegexExpr.prototype.getType = function () {
return 6 /* Regex */;
};
ContextKeyRegexExpr.prototype.cmp = function (other) {
if (this.key < other.key) {
return -1;
}
if (this.key > other.key) {
return 1;
}
var thisSource = this.regexp ? this.regexp.source : '';
var otherSource = other.regexp ? other.regexp.source : '';
if (thisSource < otherSource) {
return -1;
}
if (thisSource > otherSource) {
return 1;
}
return 0;
};
ContextKeyRegexExpr.prototype.equals = function (other) {
if (other instanceof ContextKeyRegexExpr) {
var thisSource = this.regexp ? this.regexp.source : '';
var otherSource = other.regexp ? other.regexp.source : '';
return (this.key === other.key && thisSource === otherSource);
}
return false;
};
ContextKeyRegexExpr.prototype.evaluate = function (context) {
var value = context.getValue(this.key);
return this.regexp ? this.regexp.test(value) : false;
};
ContextKeyRegexExpr.prototype.keys = function () {
return [this.key];
};
ContextKeyRegexExpr.prototype.negate = function () {
return ContextKeyNotRegexExpr.create(this);
};
return ContextKeyRegexExpr;
}());
exports.ContextKeyRegexExpr = ContextKeyRegexExpr;
var ContextKeyNotRegexExpr = /** @class */ (function () {
function ContextKeyNotRegexExpr(_actual) {
this._actual = _actual;
//
}
ContextKeyNotRegexExpr.create = function (actual) {
return new ContextKeyNotRegexExpr(actual);
};
ContextKeyNotRegexExpr.prototype.getType = function () {
return 7 /* NotRegex */;
};
ContextKeyNotRegexExpr.prototype.cmp = function (other) {
return this._actual.cmp(other._actual);
};
ContextKeyNotRegexExpr.prototype.equals = function (other) {
if (other instanceof ContextKeyNotRegexExpr) {
return this._actual.equals(other._actual);
}
return false;
};
ContextKeyNotRegexExpr.prototype.evaluate = function (context) {
return !this._actual.evaluate(context);
};
ContextKeyNotRegexExpr.prototype.keys = function () {
return this._actual.keys();
};
ContextKeyNotRegexExpr.prototype.negate = function () {
return this._actual;
};
return ContextKeyNotRegexExpr;
}());
exports.ContextKeyNotRegexExpr = ContextKeyNotRegexExpr;
var ContextKeyAndExpr = /** @class */ (function () {
function ContextKeyAndExpr(expr) {
this.expr = expr;
}
ContextKeyAndExpr.create = function (_expr) {
var expr = ContextKeyAndExpr._normalizeArr(_expr);
if (expr.length === 0) {
return undefined;
}
if (expr.length === 1) {
return expr[0];
}
return new ContextKeyAndExpr(expr);
};
ContextKeyAndExpr.prototype.getType = function () {
return 5 /* And */;
};
ContextKeyAndExpr.prototype.cmp = function (other) {
if (this.expr.length < other.expr.length) {
return -1;
}
if (this.expr.length > other.expr.length) {
return 1;
}
for (var i = 0, len = this.expr.length; i < len; i++) {
var r = cmp(this.expr[i], other.expr[i]);
if (r !== 0) {
return r;
}
}
return 0;
};
ContextKeyAndExpr.prototype.equals = function (other) {
if (other instanceof ContextKeyAndExpr) {
if (this.expr.length !== other.expr.length) {
return false;
}
for (var i = 0, len = this.expr.length; i < len; i++) {
if (!this.expr[i].equals(other.expr[i])) {
return false;
}
}
return true;
}
return false;
};
ContextKeyAndExpr.prototype.evaluate = function (context) {
for (var i = 0, len = this.expr.length; i < len; i++) {
if (!this.expr[i].evaluate(context)) {
return false;
}
}
return true;
};
ContextKeyAndExpr._normalizeArr = function (arr) {
var expr = [];
if (arr) {
for (var i = 0, len = arr.length; i < len; i++) {
var e = arr[i];
if (!e) {
continue;
}
if (e instanceof ContextKeyAndExpr) {
expr = expr.concat(e.expr);
continue;
}
if (e instanceof ContextKeyOrExpr) {
// Not allowed, because we don't have parens!
throw new Error("It is not allowed to have an or expression here due to lack of parens! For example \"a && (b||c)\" is not supported, use \"(a&&b) || (a&&c)\" instead.");
}
expr.push(e);
}
expr.sort(cmp);
}
return expr;
};
ContextKeyAndExpr.prototype.keys = function () {
var result = [];
for (var _i = 0, _a = this.expr; _i < _a.length; _i++) {
var expr = _a[_i];
result.push.apply(result, expr.keys());
}
return result;
};
ContextKeyAndExpr.prototype.negate = function () {
var result = [];
for (var _i = 0, _a = this.expr; _i < _a.length; _i++) {
var expr = _a[_i];
result.push(expr.negate());
}
return ContextKeyOrExpr.create(result);
};
return ContextKeyAndExpr;
}());
exports.ContextKeyAndExpr = ContextKeyAndExpr;
var ContextKeyOrExpr = /** @class */ (function () {
function ContextKeyOrExpr(expr) {
this.expr = expr;
}
ContextKeyOrExpr.create = function (_expr) {
var expr = ContextKeyOrExpr._normalizeArr(_expr);
if (expr.length === 0) {
return undefined;
}
if (expr.length === 1) {
return expr[0];
}
return new ContextKeyOrExpr(expr);
};
ContextKeyOrExpr.prototype.getType = function () {
return 8 /* Or */;
};
ContextKeyOrExpr.prototype.equals = function (other) {
if (other instanceof ContextKeyOrExpr) {
if (this.expr.length !== other.expr.length) {
return false;
}
for (var i = 0, len = this.expr.length; i < len; i++) {
if (!this.expr[i].equals(other.expr[i])) {
return false;
}
}
return true;
}
return false;
};
ContextKeyOrExpr.prototype.evaluate = function (context) {
for (var i = 0, len = this.expr.length; i < len; i++) {
if (this.expr[i].evaluate(context)) {
return true;
}
}
return false;
};
ContextKeyOrExpr._normalizeArr = function (arr) {
var expr = [];
if (arr) {
for (var i = 0, len = arr.length; i < len; i++) {
var e = arr[i];
if (!e) {
continue;
}
if (e instanceof ContextKeyOrExpr) {
expr = expr.concat(e.expr);
continue;
}
expr.push(e);
}
expr.sort(cmp);
}
return expr;
};
ContextKeyOrExpr.prototype.keys = function () {
var result = [];
for (var _i = 0, _a = this.expr; _i < _a.length; _i++) {
var expr = _a[_i];
result.push.apply(result, expr.keys());
}
return result;
};
ContextKeyOrExpr.prototype.negate = function () {
var result = [];
for (var _i = 0, _a = this.expr; _i < _a.length; _i++) {
var expr = _a[_i];
result.push(expr.negate());
}
var terminals = function (node) {
if (node instanceof ContextKeyOrExpr) {
return node.expr;
}
return [node];
};
// We don't support parens, so here we distribute the AND over the OR terminals
// We always take the first 2 AND pairs and distribute them
while (result.length > 1) {
var LEFT = result.shift();
var RIGHT = result.shift();
var all = [];
for (var _b = 0, _c = terminals(LEFT); _b < _c.length; _b++) {
var left = _c[_b];
for (var _d = 0, _e = terminals(RIGHT); _d < _e.length; _d++) {
var right = _e[_d];
all.push(ContextKeyExpr.and(left, right));
}
}
result.unshift(ContextKeyExpr.or.apply(ContextKeyExpr, all));
}
return result[0];
};
return ContextKeyOrExpr;
}());
exports.ContextKeyOrExpr = ContextKeyOrExpr;
var RawContextKey = /** @class */ (function (_super) {
__extends(RawContextKey, _super);
function RawContextKey(key, defaultValue) {
var _this = _super.call(this, key) || this;
_this._defaultValue = defaultValue;
return _this;
}
RawContextKey.prototype.bindTo = function (target) {
return target.createKey(this.key, this._defaultValue);
};
RawContextKey.prototype.getValue = function (target) {
return target.getContextKeyValue(this.key);
};
RawContextKey.prototype.toNegated = function () {
return ContextKeyExpr.not(this.key);
};
return RawContextKey;
}(ContextKeyDefinedExpr));
exports.RawContextKey = RawContextKey;
exports.IContextKeyService = instantiation_1.createDecorator('contextKeyService');
exports.SET_CONTEXT_COMMAND_ID = 'setContext';
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[23/*vs/editor/common/editorContextKeys*/], __M([0/*require*/,1/*exports*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var EditorContextKeys;
(function (EditorContextKeys) {
EditorContextKeys.editorSimpleInput = new contextkey_1.RawContextKey('editorSimpleInput', false);
/**
* A context key that is set when the editor's text has focus (cursor is blinking).
*/
EditorContextKeys.editorTextFocus = new contextkey_1.RawContextKey('editorTextFocus', false);
/**
* A context key that is set when the editor's text or an editor's widget has focus.
*/
EditorContextKeys.focus = new contextkey_1.RawContextKey('editorFocus', false);
/**
* A context key that is set when any editor input has focus (regular editor, repl input...).
*/
EditorContextKeys.textInputFocus = new contextkey_1.RawContextKey('textInputFocus', false);
EditorContextKeys.readOnly = new contextkey_1.RawContextKey('editorReadonly', false);
EditorContextKeys.writable = EditorContextKeys.readOnly.toNegated();
EditorContextKeys.hasNonEmptySelection = new contextkey_1.RawContextKey('editorHasSelection', false);
EditorContextKeys.hasOnlyEmptySelection = EditorContextKeys.hasNonEmptySelection.toNegated();
EditorContextKeys.hasMultipleSelections = new contextkey_1.RawContextKey('editorHasMultipleSelections', false);
EditorContextKeys.hasSingleSelection = EditorContextKeys.hasMultipleSelections.toNegated();
EditorContextKeys.tabMovesFocus = new contextkey_1.RawContextKey('editorTabMovesFocus', false);
EditorContextKeys.tabDoesNotMoveFocus = EditorContextKeys.tabMovesFocus.toNegated();
EditorContextKeys.isInEmbeddedEditor = new contextkey_1.RawContextKey('isInEmbeddedEditor', false);
EditorContextKeys.canUndo = new contextkey_1.RawContextKey('canUndo', false);
EditorContextKeys.canRedo = new contextkey_1.RawContextKey('canRedo', false);
// -- mode context keys
EditorContextKeys.languageId = new contextkey_1.RawContextKey('editorLangId', '');
EditorContextKeys.hasCompletionItemProvider = new contextkey_1.RawContextKey('editorHasCompletionItemProvider', false);
EditorContextKeys.hasCodeActionsProvider = new contextkey_1.RawContextKey('editorHasCodeActionsProvider', false);
EditorContextKeys.hasCodeLensProvider = new contextkey_1.RawContextKey('editorHasCodeLensProvider', false);
EditorContextKeys.hasDefinitionProvider = new contextkey_1.RawContextKey('editorHasDefinitionProvider', false);
EditorContextKeys.hasDeclarationProvider = new contextkey_1.RawContextKey('editorHasDeclarationProvider', false);
EditorContextKeys.hasImplementationProvider = new contextkey_1.RawContextKey('editorHasImplementationProvider', false);
EditorContextKeys.hasTypeDefinitionProvider = new contextkey_1.RawContextKey('editorHasTypeDefinitionProvider', false);
EditorContextKeys.hasHoverProvider = new contextkey_1.RawContextKey('editorHasHoverProvider', false);
EditorContextKeys.hasDocumentHighlightProvider = new contextkey_1.RawContextKey('editorHasDocumentHighlightProvider', false);
EditorContextKeys.hasDocumentSymbolProvider = new contextkey_1.RawContextKey('editorHasDocumentSymbolProvider', false);
EditorContextKeys.hasReferenceProvider = new contextkey_1.RawContextKey('editorHasReferenceProvider', false);
EditorContextKeys.hasRenameProvider = new contextkey_1.RawContextKey('editorHasRenameProvider', false);
EditorContextKeys.hasSignatureHelpProvider = new contextkey_1.RawContextKey('editorHasSignatureHelpProvider', false);
// -- mode context keys: formatting
EditorContextKeys.hasDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentFormattingProvider', false);
EditorContextKeys.hasDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentSelectionFormattingProvider', false);
EditorContextKeys.hasMultipleDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentFormattingProvider', false);
EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentSelectionFormattingProvider', false);
})(EditorContextKeys = exports.EditorContextKeys || (exports.EditorContextKeys = {}));
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
define(__m[497/*vs/editor/contrib/suggest/suggestAlternatives*/], __M([0/*require*/,1/*exports*/,2/*vs/base/common/lifecycle*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, lifecycle_1, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SuggestAlternatives = /** @class */ (function () {
function SuggestAlternatives(_editor, contextKeyService) {
this._editor = _editor;
this._index = 0;
this._ckOtherSuggestions = SuggestAlternatives.OtherSuggestions.bindTo(contextKeyService);
}
SuggestAlternatives.prototype.dispose = function () {
this.reset();
};
SuggestAlternatives.prototype.reset = function () {
this._ckOtherSuggestions.reset();
lifecycle_1.dispose(this._listener);
this._model = undefined;
this._acceptNext = undefined;
this._ignore = false;
};
SuggestAlternatives.prototype.set = function (_a, acceptNext) {
var _this = this;
var model = _a.model, index = _a.index;
// no suggestions -> nothing to do
if (model.items.length === 0) {
this.reset();
return;
}
// no alternative suggestions -> nothing to do
var nextIndex = SuggestAlternatives._moveIndex(true, model, index);
if (nextIndex === index) {
this.reset();
return;
}
this._acceptNext = acceptNext;
this._model = model;
this._index = index;
this._listener = this._editor.onDidChangeCursorPosition(function () {
if (!_this._ignore) {
_this.reset();
}
});
this._ckOtherSuggestions.set(true);
};
SuggestAlternatives._moveIndex = function (fwd, model, index) {
var newIndex = index;
while (true) {
newIndex = (newIndex + model.items.length + (fwd ? +1 : -1)) % model.items.length;
if (newIndex === index) {
break;
}
if (!model.items[newIndex].completion.additionalTextEdits) {
break;
}
}
return newIndex;
};
SuggestAlternatives.prototype.next = function () {
this._move(true);
};
SuggestAlternatives.prototype.prev = function () {
this._move(false);
};
SuggestAlternatives.prototype._move = function (fwd) {
if (!this._model) {
// nothing to reason about
return;
}
try {
this._ignore = true;
this._index = SuggestAlternatives._moveIndex(fwd, this._model, this._index);
this._acceptNext({ index: this._index, item: this._model.items[this._index], model: this._model });
}
finally {
this._ignore = false;
}
};
SuggestAlternatives.OtherSuggestions = new contextkey_1.RawContextKey('hasOtherSuggestions', false);
SuggestAlternatives = __decorate([
__param(1, contextkey_1.IContextKeyService)
], SuggestAlternatives);
return SuggestAlternatives;
}());
exports.SuggestAlternatives = SuggestAlternatives;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[498/*vs/editor/contrib/suggest/wordContextKey*/], __M([0/*require*/,1/*exports*/,18/*vs/platform/contextkey/common/contextkey*/,2/*vs/base/common/lifecycle*/]), function (require, exports, contextkey_1, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var WordContextKey = /** @class */ (function (_super) {
__extends(WordContextKey, _super);
function WordContextKey(_editor, contextKeyService) {
var _this = _super.call(this) || this;
_this._editor = _editor;
_this._enabled = false;
_this._ckAtEnd = WordContextKey.AtEnd.bindTo(contextKeyService);
_this._register(_this._editor.onDidChangeConfiguration(function (e) { return e.hasChanged(94 /* tabCompletion */) && _this._update(); }));
_this._update();
return _this;
}
WordContextKey.prototype.dispose = function () {
_super.prototype.dispose.call(this);
lifecycle_1.dispose(this._selectionListener);
this._ckAtEnd.reset();
};
WordContextKey.prototype._update = function () {
var _this = this;
// only update this when tab completions are enabled
var enabled = this._editor.getOption(94 /* tabCompletion */) === 'on';
if (this._enabled === enabled) {
return;
}
this._enabled = enabled;
if (this._enabled) {
var checkForWordEnd = function () {
if (!_this._editor.hasModel()) {
_this._ckAtEnd.set(false);
return;
}
var model = _this._editor.getModel();
var selection = _this._editor.getSelection();
var word = model.getWordAtPosition(selection.getStartPosition());
if (!word) {
_this._ckAtEnd.set(false);
return;
}
_this._ckAtEnd.set(word.endColumn === selection.getStartPosition().column);
};
this._selectionListener = this._editor.onDidChangeCursorSelection(checkForWordEnd);
checkForWordEnd();
}
else if (this._selectionListener) {
this._ckAtEnd.reset();
this._selectionListener.dispose();
this._selectionListener = undefined;
}
};
WordContextKey.AtEnd = new contextkey_1.RawContextKey('atEndOfWord', false);
WordContextKey = __decorate([
__param(1, contextkey_1.IContextKeyService)
], WordContextKey);
return WordContextKey;
}(lifecycle_1.Disposable));
exports.WordContextKey = WordContextKey;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[64/*vs/platform/accessibility/common/accessibility*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, instantiation_1, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IAccessibilityService = instantiation_1.createDecorator('accessibilityService');
exports.CONTEXT_ACCESSIBILITY_MODE_ENABLED = new contextkey_1.RawContextKey('accessibilityModeEnabled', false);
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[65/*vs/platform/actions/common/actions*/], __M([0/*require*/,1/*exports*/,55/*vs/base/common/actions*/,11/*vs/platform/instantiation/common/instantiation*/,18/*vs/platform/contextkey/common/contextkey*/,29/*vs/platform/commands/common/commands*/,4/*vs/base/common/event*/]), function (require, exports, actions_1, instantiation_1, contextkey_1, commands_1, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function isIMenuItem(item) {
return item.command !== undefined;
}
exports.isIMenuItem = isIMenuItem;
exports.IMenuService = instantiation_1.createDecorator('menuService');
exports.MenuRegistry = new /** @class */ (function () {
function class_1() {
this._commands = new Map();
this._menuItems = new Map();
this._onDidChangeMenu = new event_1.Emitter();
this.onDidChangeMenu = this._onDidChangeMenu.event;
}
class_1.prototype.addCommand = function (command) {
var _this = this;
this._commands.set(command.id, command);
this._onDidChangeMenu.fire(0 /* CommandPalette */);
return {
dispose: function () {
if (_this._commands.delete(command.id)) {
_this._onDidChangeMenu.fire(0 /* CommandPalette */);
}
}
};
};
class_1.prototype.getCommand = function (id) {
return this._commands.get(id);
};
class_1.prototype.getCommands = function () {
var map = new Map();
this._commands.forEach(function (value, key) { return map.set(key, value); });
return map;
};
class_1.prototype.appendMenuItem = function (id, item) {
var _this = this;
var array = this._menuItems.get(id);
if (!array) {
array = [item];
this._menuItems.set(id, array);
}
else {
array.push(item);
}
this._onDidChangeMenu.fire(id);
return {
dispose: function () {
var idx = array.indexOf(item);
if (idx >= 0) {
array.splice(idx, 1);
_this._onDidChangeMenu.fire(id);
}
}
};
};
class_1.prototype.getMenuItems = function (id) {
var result = (this._menuItems.get(id) || []).slice(0);
if (id === 0 /* CommandPalette */) {
// CommandPalette is special because it shows
// all commands by default
this._appendImplicitItems(result);
}
return result;
};
class_1.prototype._appendImplicitItems = function (result) {
var set = new Set();
var temp = result.filter(function (item) { return isIMenuItem(item); });
for (var _i = 0, temp_1 = temp; _i < temp_1.length; _i++) {
var _a = temp_1[_i], command = _a.command, alt = _a.alt;
set.add(command.id);
if (alt) {
set.add(alt.id);
}
}
this._commands.forEach(function (command, id) {
if (!set.has(id)) {
result.push({ command: command });
}
});
};
return class_1;
}());
var ExecuteCommandAction = /** @class */ (function (_super) {
__extends(ExecuteCommandAction, _super);
function ExecuteCommandAction(id, label, _commandService) {
var _this = _super.call(this, id, label) || this;
_this._commandService = _commandService;
return _this;
}
ExecuteCommandAction.prototype.run = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return (_a = this._commandService).executeCommand.apply(_a, __spreadArrays([this.id], args));
};
ExecuteCommandAction = __decorate([
__param(2, commands_1.ICommandService)
], ExecuteCommandAction);
return ExecuteCommandAction;
}(actions_1.Action));
exports.ExecuteCommandAction = ExecuteCommandAction;
var SubmenuItemAction = /** @class */ (function (_super) {
__extends(SubmenuItemAction, _super);
function SubmenuItemAction(item) {
var _this = this;
typeof item.title === 'string' ? _this = _super.call(this, '', item.title, 'submenu') || this : _this = _super.call(this, '', item.title.value, 'submenu') || this;
_this.item = item;
return _this;
}
return SubmenuItemAction;
}(actions_1.Action));
exports.SubmenuItemAction = SubmenuItemAction;
var MenuItemAction = /** @class */ (function (_super) {
__extends(MenuItemAction, _super);
function MenuItemAction(item, alt, options, contextKeyService, commandService) {
var _this = this;
typeof item.title === 'string' ? _this = _super.call(this, item.id, item.title, commandService) || this : _this = _super.call(this, item.id, item.title.value, commandService) || this;
_this._cssClass = undefined;
_this._enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition);
_this._checked = Boolean(item.toggled && contextKeyService.contextMatchesRules(item.toggled));
_this._options = options || {};
_this.item = item;
_this.alt = alt ? new MenuItemAction(alt, undefined, _this._options, contextKeyService, commandService) : undefined;
return _this;
}
MenuItemAction.prototype.dispose = function () {
if (this.alt) {
this.alt.dispose();
}
_super.prototype.dispose.call(this);
};
MenuItemAction.prototype.run = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var runArgs = [];
if (this._options.arg) {
runArgs = __spreadArrays(runArgs, [this._options.arg]);
}
if (this._options.shouldForwardArgs) {
runArgs = __spreadArrays(runArgs, args);
}
return _super.prototype.run.apply(this, runArgs);
};
MenuItemAction = __decorate([
__param(3, contextkey_1.IContextKeyService),
__param(4, commands_1.ICommandService)
], MenuItemAction);
return MenuItemAction;
}(ExecuteCommandAction));
exports.MenuItemAction = MenuItemAction;
});
//#endregion
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[499/*vs/platform/actions/common/menuService*/], __M([0/*require*/,1/*exports*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,65/*vs/platform/actions/common/actions*/,29/*vs/platform/commands/common/commands*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, event_1, lifecycle_1, actions_1, commands_1, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MenuService = /** @class */ (function () {
function MenuService(_commandService) {
this._commandService = _commandService;
//
}
MenuService.prototype.createMenu = function (id, contextKeyService) {
return new Menu(id, this._commandService, contextKeyService);
};
MenuService = __decorate([
__param(0, commands_1.ICommandService)
], MenuService);
return MenuService;
}());
exports.MenuService = MenuService;
var Menu = /** @class */ (function () {
function Menu(_id, _commandService, _contextKeyService) {
var _this = this;
this._id = _id;
this._commandService = _commandService;
this._contextKeyService = _contextKeyService;
this._onDidChange = new event_1.Emitter();
this._dispoables = new lifecycle_1.DisposableStore();
this._menuGroups = [];
this._contextKeys = new Set();
this._build();
// rebuild this menu whenever the menu registry reports an
// event for this MenuId
this._dispoables.add(event_1.Event.debounce(event_1.Event.filter(actions_1.MenuRegistry.onDidChangeMenu, function (menuId) { return menuId === _this._id; }), function () { }, 50)(this._build, this));
// when context keys change we need to check if the menu also
// has changed
this._dispoables.add(event_1.Event.debounce(this._contextKeyService.onDidChangeContext, function (last, event) { return last || event.affectsSome(_this._contextKeys); }, 50)(function (e) { return e && _this._onDidChange.fire(undefined); }, this));
}
Menu.prototype.dispose = function () {
this._dispoables.dispose();
this._onDidChange.dispose();
};
Menu.prototype._build = function () {
// reset
this._menuGroups.length = 0;
this._contextKeys.clear();
var menuItems = actions_1.MenuRegistry.getMenuItems(this._id);
var group;
menuItems.sort(Menu._compareMenuItems);
for (var _i = 0, menuItems_1 = menuItems; _i < menuItems_1.length; _i++) {
var item = menuItems_1[_i];
// group by groupId
var groupName = item.group || '';
if (!group || group[0] !== groupName) {
group = [groupName, []];
this._menuGroups.push(group);
}
group[1].push(item);
// keep keys for eventing
Menu._fillInKbExprKeys(item.when, this._contextKeys);
// keep precondition keys for event if applicable
if (actions_1.isIMenuItem(item) && item.command.precondition) {
Menu._fillInKbExprKeys(item.command.precondition, this._contextKeys);
}
// keep toggled keys for event if applicable
if (actions_1.isIMenuItem(item) && item.command.toggled) {
Menu._fillInKbExprKeys(item.command.toggled, this._contextKeys);
}
}
this._onDidChange.fire(this);
};
Menu.prototype.getActions = function (options) {
var result = [];
for (var _i = 0, _a = this._menuGroups; _i < _a.length; _i++) {
var group = _a[_i];
var id = group[0], items = group[1];
var activeActions = [];
for (var _b = 0, items_1 = items; _b < items_1.length; _b++) {
var item = items_1[_b];
if (this._contextKeyService.contextMatchesRules(item.when)) {
var action = actions_1.isIMenuItem(item)
? new actions_1.MenuItemAction(item.command, item.alt, options, this._contextKeyService, this._commandService)
: new actions_1.SubmenuItemAction(item);
activeActions.push(action);
}
}
if (activeActions.length > 0) {
result.push([id, activeActions]);
}
}
return result;
};
Menu._fillInKbExprKeys = function (exp, set) {
if (exp) {
for (var _i = 0, _a = exp.keys(); _i < _a.length; _i++) {
var key = _a[_i];
set.add(key);
}
}
};
Menu._compareMenuItems = function (a, b) {
var aGroup = a.group;
var bGroup = b.group;
if (aGroup !== bGroup) {
// Falsy groups come last
if (!aGroup) {
return 1;
}
else if (!bGroup) {
return -1;
}
// 'navigation' group comes first
if (aGroup === 'navigation') {
return -1;
}
else if (bGroup === 'navigation') {
return 1;
}
// lexical sort for groups
var value = aGroup.localeCompare(bGroup);
if (value !== 0) {
return value;
}
}
// sort on priority - default is 0
var aPrio = a.order || 0;
var bPrio = b.order || 0;
if (aPrio < bPrio) {
return -1;
}
else if (aPrio > bPrio) {
return 1;
}
// sort on titles
return Menu._compareTitles(actions_1.isIMenuItem(a) ? a.command.title : a.title, actions_1.isIMenuItem(b) ? b.command.title : b.title);
};
Menu._compareTitles = function (a, b) {
var aStr = typeof a === 'string' ? a : a.value;
var bStr = typeof b === 'string' ? b : b.value;
return aStr.localeCompare(bStr);
};
Menu = __decorate([
__param(1, commands_1.ICommandService),
__param(2, contextkey_1.IContextKeyService)
], Menu);
return Menu;
}());
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[66/*vs/platform/contextview/browser/contextView*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IContextViewService = instantiation_1.createDecorator('contextViewService');
exports.IContextMenuService = instantiation_1.createDecorator('contextMenuService');
});
define(__m[500/*vs/platform/dialogs/common/dialogs*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IDialogService = instantiation_1.createDecorator('dialogService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[115/*vs/platform/instantiation/common/serviceCollection*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ServiceCollection = /** @class */ (function () {
function ServiceCollection() {
var entries = [];
for (var _i = 0; _i < arguments.length; _i++) {
entries[_i] = arguments[_i];
}
this._entries = new Map();
for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
var _b = entries_1[_a], id = _b[0], service = _b[1];
this.set(id, service);
}
}
ServiceCollection.prototype.set = function (id, instanceOrDescriptor) {
var result = this._entries.get(id);
this._entries.set(id, instanceOrDescriptor);
return result;
};
ServiceCollection.prototype.has = function (id) {
return this._entries.has(id);
};
ServiceCollection.prototype.get = function (id) {
return this._entries.get(id);
};
return ServiceCollection;
}());
exports.ServiceCollection = ServiceCollection;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[501/*vs/platform/instantiation/common/instantiationService*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,480/*vs/platform/instantiation/common/graph*/,209/*vs/platform/instantiation/common/descriptors*/,11/*vs/platform/instantiation/common/instantiation*/,115/*vs/platform/instantiation/common/serviceCollection*/,15/*vs/base/common/async*/]), function (require, exports, errors_1, graph_1, descriptors_1, instantiation_1, serviceCollection_1, async_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// TRACING
var _enableTracing = false;
var _canUseProxy = typeof Proxy === 'function';
var CyclicDependencyError = /** @class */ (function (_super) {
__extends(CyclicDependencyError, _super);
function CyclicDependencyError(graph) {
var _this = _super.call(this, 'cyclic dependency between services') || this;
_this.message = graph.toString();
return _this;
}
return CyclicDependencyError;
}(Error));
var InstantiationService = /** @class */ (function () {
function InstantiationService(services, strict, parent) {
if (services === void 0) { services = new serviceCollection_1.ServiceCollection(); }
if (strict === void 0) { strict = false; }
this._services = services;
this._strict = strict;
this._parent = parent;
this._services.set(instantiation_1.IInstantiationService, this);
}
InstantiationService.prototype.createChild = function (services) {
return new InstantiationService(services, this._strict, this);
};
InstantiationService.prototype.invokeFunction = function (fn) {
var _this = this;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var _trace = Trace.traceInvocation(fn);
var _done = false;
try {
var accessor = {
get: function (id, isOptional) {
if (_done) {
throw errors_1.illegalState('service accessor is only valid during the invocation of its target method');
}
var result = _this._getOrCreateServiceInstance(id, _trace);
if (!result && isOptional !== instantiation_1.optional) {
throw new Error("[invokeFunction] unknown service '" + id + "'");
}
return result;
}
};
return fn.apply(undefined, __spreadArrays([accessor], args));
}
finally {
_done = true;
_trace.stop();
}
};
InstantiationService.prototype.createInstance = function (ctorOrDescriptor) {
var rest = [];
for (var _i = 1; _i < arguments.length; _i++) {
rest[_i - 1] = arguments[_i];
}
var _trace;
var result;
if (ctorOrDescriptor instanceof descriptors_1.SyncDescriptor) {
_trace = Trace.traceCreation(ctorOrDescriptor.ctor);
result = this._createInstance(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
}
else {
_trace = Trace.traceCreation(ctorOrDescriptor);
result = this._createInstance(ctorOrDescriptor, rest, _trace);
}
_trace.stop();
return result;
};
InstantiationService.prototype._createInstance = function (ctor, args, _trace) {
if (args === void 0) { args = []; }
// arguments defined by service decorators
var serviceDependencies = instantiation_1._util.getServiceDependencies(ctor).sort(function (a, b) { return a.index - b.index; });
var serviceArgs = [];
for (var _i = 0, serviceDependencies_1 = serviceDependencies; _i < serviceDependencies_1.length; _i++) {
var dependency = serviceDependencies_1[_i];
var service = this._getOrCreateServiceInstance(dependency.id, _trace);
if (!service && this._strict && !dependency.optional) {
throw new Error("[createInstance] " + ctor.name + " depends on UNKNOWN service " + dependency.id + ".");
}
serviceArgs.push(service);
}
var firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
// check for argument mismatches, adjust static args if needed
if (args.length !== firstServiceArgPos) {
console.warn("[createInstance] First service dependency of " + ctor.name + " at position " + (firstServiceArgPos + 1) + " conflicts with " + args.length + " static arguments");
var delta = firstServiceArgPos - args.length;
if (delta > 0) {
args = args.concat(new Array(delta));
}
else {
args = args.slice(0, firstServiceArgPos);
}
}
// now create the instance
return new (ctor.bind.apply(ctor, __spreadArrays([void 0], __spreadArrays(args, serviceArgs))))();
};
InstantiationService.prototype._setServiceInstance = function (id, instance) {
if (this._services.get(id) instanceof descriptors_1.SyncDescriptor) {
this._services.set(id, instance);
}
else if (this._parent) {
this._parent._setServiceInstance(id, instance);
}
else {
throw new Error('illegalState - setting UNKNOWN service instance');
}
};
InstantiationService.prototype._getServiceInstanceOrDescriptor = function (id) {
var instanceOrDesc = this._services.get(id);
if (!instanceOrDesc && this._parent) {
return this._parent._getServiceInstanceOrDescriptor(id);
}
else {
return instanceOrDesc;
}
};
InstantiationService.prototype._getOrCreateServiceInstance = function (id, _trace) {
var thing = this._getServiceInstanceOrDescriptor(id);
if (thing instanceof descriptors_1.SyncDescriptor) {
return this._createAndCacheServiceInstance(id, thing, _trace.branch(id, true));
}
else {
_trace.branch(id, false);
return thing;
}
};
InstantiationService.prototype._createAndCacheServiceInstance = function (id, desc, _trace) {
var graph = new graph_1.Graph(function (data) { return data.id.toString(); });
var cycleCount = 0;
var stack = [{ id: id, desc: desc, _trace: _trace }];
while (stack.length) {
var item = stack.pop();
graph.lookupOrInsertNode(item);
// a weak but working heuristic for cycle checks
if (cycleCount++ > 150) {
throw new CyclicDependencyError(graph);
}
// check all dependencies for existence and if they need to be created first
for (var _i = 0, _a = instantiation_1._util.getServiceDependencies(item.desc.ctor); _i < _a.length; _i++) {
var dependency = _a[_i];
var instanceOrDesc = this._getServiceInstanceOrDescriptor(dependency.id);
if (!instanceOrDesc && !dependency.optional) {
console.warn("[createInstance] " + id + " depends on " + dependency.id + " which is NOT registered.");
}
if (instanceOrDesc instanceof descriptors_1.SyncDescriptor) {
var d = { id: dependency.id, desc: instanceOrDesc, _trace: item._trace.branch(dependency.id, true) };
graph.insertEdge(item, d);
stack.push(d);
}
}
}
while (true) {
var roots = graph.roots();
// if there is no more roots but still
// nodes in the graph we have a cycle
if (roots.length === 0) {
if (!graph.isEmpty()) {
throw new CyclicDependencyError(graph);
}
break;
}
for (var _b = 0, roots_1 = roots; _b < roots_1.length; _b++) {
var data = roots_1[_b].data;
// create instance and overwrite the service collections
var instance = this._createServiceInstanceWithOwner(data.id, data.desc.ctor, data.desc.staticArguments, data.desc.supportsDelayedInstantiation, data._trace);
this._setServiceInstance(data.id, instance);
graph.removeNode(data);
}
}
return this._getServiceInstanceOrDescriptor(id);
};
InstantiationService.prototype._createServiceInstanceWithOwner = function (id, ctor, args, supportsDelayedInstantiation, _trace) {
if (args === void 0) { args = []; }
if (this._services.get(id) instanceof descriptors_1.SyncDescriptor) {
return this._createServiceInstance(ctor, args, supportsDelayedInstantiation, _trace);
}
else if (this._parent) {
return this._parent._createServiceInstanceWithOwner(id, ctor, args, supportsDelayedInstantiation, _trace);
}
else {
throw new Error("illegalState - creating UNKNOWN service instance " + ctor.name);
}
};
InstantiationService.prototype._createServiceInstance = function (ctor, args, _supportsDelayedInstantiation, _trace) {
var _this = this;
if (args === void 0) { args = []; }
if (!_supportsDelayedInstantiation || !_canUseProxy) {
// eager instantiation or no support JS proxies (e.g. IE11)
return this._createInstance(ctor, args, _trace);
}
else {
// Return a proxy object that's backed by an idle value. That
// strategy is to instantiate services in our idle time or when actually
// needed but not when injected into a consumer
var idle_1 = new async_1.IdleValue(function () { return _this._createInstance(ctor, args, _trace); });
return new Proxy(Object.create(null), {
get: function (target, key) {
if (key in target) {
return target[key];
}
var obj = idle_1.getValue();
var prop = obj[key];
if (typeof prop !== 'function') {
return prop;
}
prop = prop.bind(obj);
target[key] = prop;
return prop;
},
set: function (_target, p, value) {
idle_1.getValue()[p] = value;
return true;
}
});
}
};
return InstantiationService;
}());
exports.InstantiationService = InstantiationService;
var Trace = /** @class */ (function () {
function Trace(type, name) {
this.type = type;
this.name = name;
this._start = Date.now();
this._dep = [];
}
Trace.traceInvocation = function (ctor) {
return !_enableTracing ? Trace._None : new Trace(1 /* Invocation */, ctor.name || ctor.toString().substring(0, 42).replace(/\n/g, ''));
};
Trace.traceCreation = function (ctor) {
return !_enableTracing ? Trace._None : new Trace(0 /* Creation */, ctor.name);
};
Trace.prototype.branch = function (id, first) {
var child = new Trace(2 /* Branch */, id.toString());
this._dep.push([id, first, child]);
return child;
};
Trace.prototype.stop = function () {
var dur = Date.now() - this._start;
Trace._totals += dur;
var causedCreation = false;
function printChild(n, trace) {
var res = [];
var prefix = new Array(n + 1).join('\t');
for (var _i = 0, _a = trace._dep; _i < _a.length; _i++) {
var _b = _a[_i], id = _b[0], first = _b[1], child = _b[2];
if (first && child) {
causedCreation = true;
res.push(prefix + "CREATES -> " + id);
var nested = printChild(n + 1, child);
if (nested) {
res.push(nested);
}
}
else {
res.push(prefix + "uses -> " + id);
}
}
return res.join('\n');
}
var lines = [
(this.type === 0 /* Creation */ ? 'CREATE' : 'CALL') + " " + this.name,
"" + printChild(1, this),
"DONE, took " + dur.toFixed(2) + "ms (grand total " + Trace._totals.toFixed(2) + "ms)"
];
if (dur > 2 || causedCreation) {
console.log(lines.join('\n'));
}
};
Trace._None = new /** @class */ (function (_super) {
__extends(class_1, _super);
function class_1() {
return _super.call(this, -1, null) || this;
}
class_1.prototype.stop = function () { };
class_1.prototype.branch = function () { return this; };
return class_1;
}(Trace));
Trace._totals = 0;
return Trace;
}());
});
//#endregion
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[502/*vs/platform/keybinding/common/abstractKeybindingService*/], __M([0/*require*/,1/*exports*/,473/*vs/nls!vs/platform/keybinding/common/abstractKeybindingService*/,15/*vs/base/common/async*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, nls, async_1, event_1, lifecycle_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var AbstractKeybindingService = /** @class */ (function (_super) {
__extends(AbstractKeybindingService, _super);
function AbstractKeybindingService(_contextKeyService, _commandService, _telemetryService, _notificationService) {
var _this = _super.call(this) || this;
_this._contextKeyService = _contextKeyService;
_this._commandService = _commandService;
_this._telemetryService = _telemetryService;
_this._notificationService = _notificationService;
_this._onDidUpdateKeybindings = _this._register(new event_1.Emitter());
_this._currentChord = null;
_this._currentChordChecker = new async_1.IntervalTimer();
_this._currentChordStatusMessage = null;
return _this;
}
Object.defineProperty(AbstractKeybindingService.prototype, "onDidUpdateKeybindings", {
get: function () {
return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : event_1.Event.None; // Sinon stubbing walks properties on prototype
},
enumerable: true,
configurable: true
});
AbstractKeybindingService.prototype.dispose = function () {
_super.prototype.dispose.call(this);
};
AbstractKeybindingService.prototype.getKeybindings = function () {
return this._getResolver().getKeybindings();
};
AbstractKeybindingService.prototype.lookupKeybinding = function (commandId) {
var result = this._getResolver().lookupPrimaryKeybinding(commandId);
if (!result) {
return undefined;
}
return result.resolvedKeybinding;
};
AbstractKeybindingService.prototype.softDispatch = function (e, target) {
var keybinding = this.resolveKeyboardEvent(e);
if (keybinding.isChord()) {
console.warn('Unexpected keyboard event mapped to a chord');
return null;
}
var firstPart = keybinding.getDispatchParts()[0];
if (firstPart === null) {
// cannot be dispatched, probably only modifier keys
return null;
}
var contextValue = this._contextKeyService.getContext(target);
var currentChord = this._currentChord ? this._currentChord.keypress : null;
return this._getResolver().resolve(contextValue, currentChord, firstPart);
};
AbstractKeybindingService.prototype._enterChordMode = function (firstPart, keypressLabel) {
var _this = this;
this._currentChord = {
keypress: firstPart,
label: keypressLabel
};
this._currentChordStatusMessage = this._notificationService.status(nls.localize(0, null, keypressLabel));
var chordEnterTime = Date.now();
this._currentChordChecker.cancelAndSet(function () {
if (!_this._documentHasFocus()) {
// Focus has been lost => leave chord mode
_this._leaveChordMode();
return;
}
if (Date.now() - chordEnterTime > 5000) {
// 5 seconds elapsed => leave chord mode
_this._leaveChordMode();
}
}, 500);
};
AbstractKeybindingService.prototype._leaveChordMode = function () {
if (this._currentChordStatusMessage) {
this._currentChordStatusMessage.dispose();
this._currentChordStatusMessage = null;
}
this._currentChordChecker.cancel();
this._currentChord = null;
};
AbstractKeybindingService.prototype._dispatch = function (e, target) {
return this._doDispatch(this.resolveKeyboardEvent(e), target);
};
AbstractKeybindingService.prototype._doDispatch = function (keybinding, target) {
var _this = this;
var shouldPreventDefault = false;
if (keybinding.isChord()) {
console.warn('Unexpected keyboard event mapped to a chord');
return false;
}
var firstPart = keybinding.getDispatchParts()[0];
if (firstPart === null) {
// cannot be dispatched, probably only modifier keys
return shouldPreventDefault;
}
var contextValue = this._contextKeyService.getContext(target);
var currentChord = this._currentChord ? this._currentChord.keypress : null;
var keypressLabel = keybinding.getLabel();
var resolveResult = this._getResolver().resolve(contextValue, currentChord, firstPart);
if (resolveResult && resolveResult.enterChord) {
shouldPreventDefault = true;
this._enterChordMode(firstPart, keypressLabel);
return shouldPreventDefault;
}
if (this._currentChord) {
if (!resolveResult || !resolveResult.commandId) {
this._notificationService.status(nls.localize(1, null, this._currentChord.label, keypressLabel), { hideAfter: 10 * 1000 /* 10s */ });
shouldPreventDefault = true;
}
}
this._leaveChordMode();
if (resolveResult && resolveResult.commandId) {
if (!resolveResult.bubble) {
shouldPreventDefault = true;
}
if (typeof resolveResult.commandArgs === 'undefined') {
this._commandService.executeCommand(resolveResult.commandId).then(undefined, function (err) { return _this._notificationService.warn(err); });
}
else {
this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(undefined, function (err) { return _this._notificationService.warn(err); });
}
this._telemetryService.publicLog2('workbenchActionExecuted', { id: resolveResult.commandId, from: 'keybinding' });
}
return shouldPreventDefault;
};
AbstractKeybindingService.prototype.mightProducePrintableCharacter = function (event) {
if (event.ctrlKey || event.metaKey) {
// ignore ctrl/cmd-combination but not shift/alt-combinatios
return false;
}
// weak check for certain ranges. this is properly implemented in a subclass
// with access to the KeyboardMapperFactory.
if ((event.keyCode >= 31 /* KEY_A */ && event.keyCode <= 56 /* KEY_Z */)
|| (event.keyCode >= 21 /* KEY_0 */ && event.keyCode <= 30 /* KEY_9 */)) {
return true;
}
return false;
};
return AbstractKeybindingService;
}(lifecycle_1.Disposable));
exports.AbstractKeybindingService = AbstractKeybindingService;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[503/*vs/platform/keybinding/common/baseResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,10/*vs/base/common/errors*/,207/*vs/base/common/keybindingLabels*/,36/*vs/base/common/keyCodes*/]), function (require, exports, errors_1, keybindingLabels_1, keyCodes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BaseResolvedKeybinding = /** @class */ (function (_super) {
__extends(BaseResolvedKeybinding, _super);
function BaseResolvedKeybinding(os, parts) {
var _this = _super.call(this) || this;
if (parts.length === 0) {
throw errors_1.illegalArgument("parts");
}
_this._os = os;
_this._parts = parts;
return _this;
}
BaseResolvedKeybinding.prototype.getLabel = function () {
var _this = this;
return keybindingLabels_1.UILabelProvider.toLabel(this._os, this._parts, function (keybinding) { return _this._getLabel(keybinding); });
};
BaseResolvedKeybinding.prototype.getAriaLabel = function () {
var _this = this;
return keybindingLabels_1.AriaLabelProvider.toLabel(this._os, this._parts, function (keybinding) { return _this._getAriaLabel(keybinding); });
};
BaseResolvedKeybinding.prototype.isChord = function () {
return (this._parts.length > 1);
};
BaseResolvedKeybinding.prototype.getParts = function () {
var _this = this;
return this._parts.map(function (keybinding) { return _this._getPart(keybinding); });
};
BaseResolvedKeybinding.prototype._getPart = function (keybinding) {
return new keyCodes_1.ResolvedKeybindingPart(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getLabel(keybinding), this._getAriaLabel(keybinding));
};
BaseResolvedKeybinding.prototype.getDispatchParts = function () {
var _this = this;
return this._parts.map(function (keybinding) { return _this._getDispatchPart(keybinding); });
};
return BaseResolvedKeybinding;
}(keyCodes_1.ResolvedKeybinding));
exports.BaseResolvedKeybinding = BaseResolvedKeybinding;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[34/*vs/platform/keybinding/common/keybinding*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IKeybindingService = instantiation_1.createDecorator('keybindingService');
});
define(__m[217/*vs/platform/keybinding/common/keybindingResolver*/], __M([0/*require*/,1/*exports*/,18/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var KeybindingResolver = /** @class */ (function () {
function KeybindingResolver(defaultKeybindings, overrides) {
this._defaultKeybindings = defaultKeybindings;
this._defaultBoundCommands = new Map();
for (var i = 0, len = defaultKeybindings.length; i < len; i++) {
var command = defaultKeybindings[i].command;
if (command) {
this._defaultBoundCommands.set(command, true);
}
}
this._map = new Map();
this._lookupMap = new Map();
this._keybindings = KeybindingResolver.combine(defaultKeybindings, overrides);
for (var i = 0, len = this._keybindings.length; i < len; i++) {
var k = this._keybindings[i];
if (k.keypressParts.length === 0) {
// unbound
continue;
}
// TODO@chords
this._addKeyPress(k.keypressParts[0], k);
}
}
KeybindingResolver._isTargetedForRemoval = function (defaultKb, keypressFirstPart, keypressChordPart, command, when) {
if (defaultKb.command !== command) {
return false;
}
// TODO@chords
if (keypressFirstPart && defaultKb.keypressParts[0] !== keypressFirstPart) {
return false;
}
// TODO@chords
if (keypressChordPart && defaultKb.keypressParts[1] !== keypressChordPart) {
return false;
}
if (when) {
if (!defaultKb.when) {
return false;
}
if (!when.equals(defaultKb.when)) {
return false;
}
}
return true;
};
/**
* Looks for rules containing -command in `overrides` and removes them directly from `defaults`.
*/
KeybindingResolver.combine = function (defaults, rawOverrides) {
defaults = defaults.slice(0);
var overrides = [];
for (var _i = 0, rawOverrides_1 = rawOverrides; _i < rawOverrides_1.length; _i++) {
var override = rawOverrides_1[_i];
if (!override.command || override.command.length === 0 || override.command.charAt(0) !== '-') {
overrides.push(override);
continue;
}
var command = override.command.substr(1);
// TODO@chords
var keypressFirstPart = override.keypressParts[0];
var keypressChordPart = override.keypressParts[1];
var when = override.when;
for (var j = defaults.length - 1; j >= 0; j--) {
if (this._isTargetedForRemoval(defaults[j], keypressFirstPart, keypressChordPart, command, when)) {
defaults.splice(j, 1);
}
}
}
return defaults.concat(overrides);
};
KeybindingResolver.prototype._addKeyPress = function (keypress, item) {
var conflicts = this._map.get(keypress);
if (typeof conflicts === 'undefined') {
// There is no conflict so far
this._map.set(keypress, [item]);
this._addToLookupMap(item);
return;
}
for (var i = conflicts.length - 1; i >= 0; i--) {
var conflict = conflicts[i];
if (conflict.command === item.command) {
continue;
}
var conflictIsChord = (conflict.keypressParts.length > 1);
var itemIsChord = (item.keypressParts.length > 1);
// TODO@chords
if (conflictIsChord && itemIsChord && conflict.keypressParts[1] !== item.keypressParts[1]) {
// The conflict only shares the chord start with this command
continue;
}
if (KeybindingResolver.whenIsEntirelyIncluded(conflict.when, item.when)) {
// `item` completely overwrites `conflict`
// Remove conflict from the lookupMap
this._removeFromLookupMap(conflict);
}
}
conflicts.push(item);
this._addToLookupMap(item);
};
KeybindingResolver.prototype._addToLookupMap = function (item) {
if (!item.command) {
return;
}
var arr = this._lookupMap.get(item.command);
if (typeof arr === 'undefined') {
arr = [item];
this._lookupMap.set(item.command, arr);
}
else {
arr.push(item);
}
};
KeybindingResolver.prototype._removeFromLookupMap = function (item) {
if (!item.command) {
return;
}
var arr = this._lookupMap.get(item.command);
if (typeof arr === 'undefined') {
return;
}
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
return;
}
}
};
/**
* Returns true if it is provable `a` implies `b`.
*/
KeybindingResolver.whenIsEntirelyIncluded = function (a, b) {
if (!b) {
return true;
}
if (!a) {
return false;
}
return this._implies(a, b);
};
/**
* Returns true if it is provable `p` implies `q`.
*/
KeybindingResolver._implies = function (p, q) {
var notP = p.negate();
var terminals = function (node) {
if (node instanceof contextkey_1.ContextKeyOrExpr) {
return node.expr;
}
return [node];
};
var expr = terminals(notP).concat(terminals(q));
for (var i = 0; i < expr.length; i++) {
var a = expr[i];
var notA = a.negate();
for (var j = i + 1; j < expr.length; j++) {
var b = expr[j];
if (notA.equals(b)) {
return true;
}
}
}
return false;
};
KeybindingResolver.prototype.getKeybindings = function () {
return this._keybindings;
};
KeybindingResolver.prototype.lookupPrimaryKeybinding = function (commandId) {
var items = this._lookupMap.get(commandId);
if (typeof items === 'undefined' || items.length === 0) {
return null;
}
return items[items.length - 1];
};
KeybindingResolver.prototype.resolve = function (context, currentChord, keypress) {
var lookupMap = null;
if (currentChord !== null) {
// Fetch all chord bindings for `currentChord`
var candidates = this._map.get(currentChord);
if (typeof candidates === 'undefined') {
// No chords starting with `currentChord`
return null;
}
lookupMap = [];
for (var i = 0, len = candidates.length; i < len; i++) {
var candidate = candidates[i];
// TODO@chords
if (candidate.keypressParts[1] === keypress) {
lookupMap.push(candidate);
}
}
}
else {
var candidates = this._map.get(keypress);
if (typeof candidates === 'undefined') {
// No bindings with `keypress`
return null;
}
lookupMap = candidates;
}
var result = this._findCommand(context, lookupMap);
if (!result) {
return null;
}
// TODO@chords
if (currentChord === null && result.keypressParts.length > 1 && result.keypressParts[1] !== null) {
return {
enterChord: true,
commandId: null,
commandArgs: null,
bubble: false
};
}
return {
enterChord: false,
commandId: result.command,
commandArgs: result.commandArgs,
bubble: result.bubble
};
};
KeybindingResolver.prototype._findCommand = function (context, matches) {
for (var i = matches.length - 1; i >= 0; i--) {
var k = matches[i];
if (!KeybindingResolver.contextMatchesRules(context, k.when)) {
continue;
}
return k;
}
return null;
};
KeybindingResolver.contextMatchesRules = function (context, rules) {
if (!rules) {
return true;
}
return rules.evaluate(context);
};
return KeybindingResolver;
}());
exports.KeybindingResolver = KeybindingResolver;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[504/*vs/platform/keybinding/common/resolvedKeybindingItem*/], __M([0/*require*/,1/*exports*/]), function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ResolvedKeybindingItem = /** @class */ (function () {
function ResolvedKeybindingItem(resolvedKeybinding, command, commandArgs, when, isDefault) {
this.resolvedKeybinding = resolvedKeybinding;
this.keypressParts = resolvedKeybinding ? removeElementsAfterNulls(resolvedKeybinding.getDispatchParts()) : [];
this.bubble = (command ? command.charCodeAt(0) === 94 /* Caret */ : false);
this.command = this.bubble ? command.substr(1) : command;
this.commandArgs = commandArgs;
this.when = when;
this.isDefault = isDefault;
}
return ResolvedKeybindingItem;
}());
exports.ResolvedKeybindingItem = ResolvedKeybindingItem;
function removeElementsAfterNulls(arr) {
var result = [];
for (var i = 0, len = arr.length; i < len; i++) {
var element = arr[i];
if (!element) {
// stop processing at first encountered null
return result;
}
result.push(element);
}
return result;
}
exports.removeElementsAfterNulls = removeElementsAfterNulls;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[505/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/], __M([0/*require*/,1/*exports*/,36/*vs/base/common/keyCodes*/,503/*vs/platform/keybinding/common/baseResolvedKeybinding*/]), function (require, exports, keyCodes_1, baseResolvedKeybinding_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Do not instantiate. Use KeybindingService to get a ResolvedKeybinding seeded with information about the current kb layout.
*/
var USLayoutResolvedKeybinding = /** @class */ (function (_super) {
__extends(USLayoutResolvedKeybinding, _super);
function USLayoutResolvedKeybinding(actual, os) {
return _super.call(this, os, actual.parts) || this;
}
USLayoutResolvedKeybinding.prototype._keyCodeToUILabel = function (keyCode) {
if (this._os === 2 /* Macintosh */) {
switch (keyCode) {
case 15 /* LeftArrow */:
return '←';
case 16 /* UpArrow */:
return '↑';
case 17 /* RightArrow */:
return '→';
case 18 /* DownArrow */:
return '↓';
}
}
return keyCodes_1.KeyCodeUtils.toString(keyCode);
};
USLayoutResolvedKeybinding.prototype._getLabel = function (keybinding) {
if (keybinding.isDuplicateModifierCase()) {
return '';
}
return this._keyCodeToUILabel(keybinding.keyCode);
};
USLayoutResolvedKeybinding.prototype._getAriaLabel = function (keybinding) {
if (keybinding.isDuplicateModifierCase()) {
return '';
}
return keyCodes_1.KeyCodeUtils.toString(keybinding.keyCode);
};
USLayoutResolvedKeybinding.prototype._getDispatchPart = function (keybinding) {
return USLayoutResolvedKeybinding.getDispatchStr(keybinding);
};
USLayoutResolvedKeybinding.getDispatchStr = function (keybinding) {
if (keybinding.isModifierKey()) {
return null;
}
var result = '';
if (keybinding.ctrlKey) {
result += 'ctrl+';
}
if (keybinding.shiftKey) {
result += 'shift+';
}
if (keybinding.altKey) {
result += 'alt+';
}
if (keybinding.metaKey) {
result += 'meta+';
}
result += keyCodes_1.KeyCodeUtils.toString(keybinding.keyCode);
return result;
};
return USLayoutResolvedKeybinding;
}(baseResolvedKeybinding_1.BaseResolvedKeybinding));
exports.USLayoutResolvedKeybinding = USLayoutResolvedKeybinding;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[116/*vs/platform/label/common/label*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LABEL_SERVICE_ID = 'label';
exports.ILabelService = instantiation_1.createDecorator(LABEL_SERVICE_ID);
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[218/*vs/platform/layout/browser/layoutService*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ILayoutService = instantiation_1.createDecorator('layoutService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[506/*vs/platform/contextview/browser/contextViewService*/], __M([0/*require*/,1/*exports*/,265/*vs/base/browser/ui/contextview/contextview*/,2/*vs/base/common/lifecycle*/,218/*vs/platform/layout/browser/layoutService*/]), function (require, exports, contextview_1, lifecycle_1, layoutService_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ContextViewService = /** @class */ (function (_super) {
__extends(ContextViewService, _super);
function ContextViewService(layoutService) {
var _this = _super.call(this) || this;
_this.layoutService = layoutService;
_this.contextView = _this._register(new contextview_1.ContextView(layoutService.container));
_this.layout();
_this._register(layoutService.onLayout(function () { return _this.layout(); }));
return _this;
}
// ContextView
ContextViewService.prototype.setContainer = function (container) {
this.contextView.setContainer(container);
};
ContextViewService.prototype.showContextView = function (delegate) {
this.contextView.show(delegate);
};
ContextViewService.prototype.layout = function () {
this.contextView.layout();
};
ContextViewService.prototype.hideContextView = function (data) {
this.contextView.hide(data);
};
ContextViewService = __decorate([
__param(0, layoutService_1.ILayoutService)
], ContextViewService);
return ContextViewService;
}(lifecycle_1.Disposable));
exports.ContextViewService = ContextViewService;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[95/*vs/platform/log/common/log*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ILogService = instantiation_1.createDecorator('logService');
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["Trace"] = 0] = "Trace";
LogLevel[LogLevel["Debug"] = 1] = "Debug";
LogLevel[LogLevel["Info"] = 2] = "Info";
LogLevel[LogLevel["Warning"] = 3] = "Warning";
LogLevel[LogLevel["Error"] = 4] = "Error";
LogLevel[LogLevel["Critical"] = 5] = "Critical";
LogLevel[LogLevel["Off"] = 6] = "Off";
})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
var NullLogService = /** @class */ (function () {
function NullLogService() {
}
NullLogService.prototype.getLevel = function () { return LogLevel.Info; };
NullLogService.prototype.trace = function (message) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
};
NullLogService.prototype.error = function (message) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
};
NullLogService.prototype.dispose = function () { };
return NullLogService;
}());
exports.NullLogService = NullLogService;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[219/*vs/editor/common/services/editorWorkerServiceImpl*/], __M([0/*require*/,1/*exports*/,15/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,182/*vs/base/common/worker/simpleWorker*/,258/*vs/base/worker/defaultWorkerFactory*/,3/*vs/editor/common/core/range*/,17/*vs/editor/common/modes*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,365/*vs/editor/common/services/editorSimpleWorker*/,49/*vs/editor/common/services/modelService*/,114/*vs/editor/common/services/textResourceConfigurationService*/,5/*vs/base/common/strings*/,19/*vs/base/common/arrays*/,95/*vs/platform/log/common/log*/,132/*vs/base/common/stopwatch*/]), function (require, exports, async_1, lifecycle_1, simpleWorker_1, defaultWorkerFactory_1, range_1, modes, languageConfigurationRegistry_1, editorSimpleWorker_1, modelService_1, textResourceConfigurationService_1, strings_1, arrays_1, log_1, stopwatch_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Stop syncing a model to the worker if it was not needed for 1 min.
*/
var STOP_SYNC_MODEL_DELTA_TIME_MS = 60 * 1000;
/**
* Stop the worker if it was not needed for 5 min.
*/
var STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1000;
function canSyncModel(modelService, resource) {
var model = modelService.getModel(resource);
if (!model) {
return false;
}
if (model.isTooLargeForSyncing()) {
return false;
}
return true;
}
var EditorWorkerServiceImpl = /** @class */ (function (_super) {
__extends(EditorWorkerServiceImpl, _super);
function EditorWorkerServiceImpl(modelService, configurationService, logService) {
var _this = _super.call(this) || this;
_this._modelService = modelService;
_this._workerManager = _this._register(new WorkerManager(_this._modelService));
_this._logService = logService;
// todo@joh make sure this happens only once
_this._register(modes.LinkProviderRegistry.register('*', {
provideLinks: function (model, token) {
if (!canSyncModel(_this._modelService, model.uri)) {
return Promise.resolve({ links: [] }); // File too large
}
return _this._workerManager.withWorker().then(function (client) { return client.computeLinks(model.uri); }).then(function (links) {
return links && { links: links };
});
}
}));
_this._register(modes.CompletionProviderRegistry.register('*', new WordBasedCompletionItemProvider(_this._workerManager, configurationService, _this._modelService)));
return _this;
}
EditorWorkerServiceImpl.prototype.dispose = function () {
_super.prototype.dispose.call(this);
};
EditorWorkerServiceImpl.prototype.canComputeDiff = function (original, modified) {
return (canSyncModel(this._modelService, original) && canSyncModel(this._modelService, modified));
};
EditorWorkerServiceImpl.prototype.computeDiff = function (original, modified, ignoreTrimWhitespace, maxComputationTime) {
return this._workerManager.withWorker().then(function (client) { return client.computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime); });
};
EditorWorkerServiceImpl.prototype.computeMoreMinimalEdits = function (resource, edits) {
var _this = this;
if (arrays_1.isNonEmptyArray(edits)) {
if (!canSyncModel(this._modelService, resource)) {
return Promise.resolve(edits); // File too large
}
var sw_1 = stopwatch_1.StopWatch.create(true);
var result = this._workerManager.withWorker().then(function (client) { return client.computeMoreMinimalEdits(resource, edits); });
result.finally(function () { return _this._logService.trace('FORMAT#computeMoreMinimalEdits', resource.toString(true), sw_1.elapsed()); });
return result;
}
else {
return Promise.resolve(undefined);
}
};
EditorWorkerServiceImpl.prototype.canNavigateValueSet = function (resource) {
return (canSyncModel(this._modelService, resource));
};
EditorWorkerServiceImpl.prototype.navigateValueSet = function (resource, range, up) {
return this._workerManager.withWorker().then(function (client) { return client.navigateValueSet(resource, range, up); });
};
EditorWorkerServiceImpl.prototype.canComputeWordRanges = function (resource) {
return canSyncModel(this._modelService, resource);
};
EditorWorkerServiceImpl.prototype.computeWordRanges = function (resource, range) {
return this._workerManager.withWorker().then(function (client) { return client.computeWordRanges(resource, range); });
};
EditorWorkerServiceImpl = __decorate([
__param(0, modelService_1.IModelService),
__param(1, textResourceConfigurationService_1.ITextResourceConfigurationService),
__param(2, log_1.ILogService)
], EditorWorkerServiceImpl);
return EditorWorkerServiceImpl;
}(lifecycle_1.Disposable));
exports.EditorWorkerServiceImpl = EditorWorkerServiceImpl;
var WordBasedCompletionItemProvider = /** @class */ (function () {
function WordBasedCompletionItemProvider(workerManager, configurationService, modelService) {
this._debugDisplayName = 'wordbasedCompletions';
this._workerManager = workerManager;
this._configurationService = configurationService;
this._modelService = modelService;
}
WordBasedCompletionItemProvider.prototype.provideCompletionItems = function (model, position) {
return __awaiter(this, void 0, void 0, function () {
var wordBasedSuggestions, word, replace, insert, client, words;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
wordBasedSuggestions = this._configurationService.getValue(model.uri, position, 'editor').wordBasedSuggestions;
if (!wordBasedSuggestions) {
return [2 /*return*/, undefined];
}
if (!canSyncModel(this._modelService, model.uri)) {
return [2 /*return*/, undefined]; // File too large
}
word = model.getWordAtPosition(position);
replace = !word ? range_1.Range.fromPositions(position) : new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
insert = replace.setEndPosition(position.lineNumber, position.column);
return [4 /*yield*/, this._workerManager.withWorker()];
case 1:
client = _a.sent();
return [4 /*yield*/, client.textualSuggest(model.uri, position)];
case 2:
words = _a.sent();
if (!words) {
return [2 /*return*/, undefined];
}
return [2 /*return*/, {
suggestions: words.map(function (word) {
return {
kind: 18 /* Text */,
label: word,
insertText: word,
range: { insert: insert, replace: replace }
};
})
}];
}
});
});
};
return WordBasedCompletionItemProvider;
}());
var WorkerManager = /** @class */ (function (_super) {
__extends(WorkerManager, _super);
function WorkerManager(modelService) {
var _this = _super.call(this) || this;
_this._modelService = modelService;
_this._editorWorkerClient = null;
_this._lastWorkerUsedTime = (new Date()).getTime();
var stopWorkerInterval = _this._register(new async_1.IntervalTimer());
stopWorkerInterval.cancelAndSet(function () { return _this._checkStopIdleWorker(); }, Math.round(STOP_WORKER_DELTA_TIME_MS / 2));
_this._register(_this._modelService.onModelRemoved(function (_) { return _this._checkStopEmptyWorker(); }));
return _this;
}
WorkerManager.prototype.dispose = function () {
if (this._editorWorkerClient) {
this._editorWorkerClient.dispose();
this._editorWorkerClient = null;
}
_super.prototype.dispose.call(this);
};
/**
* Check if the model service has no more models and stop the worker if that is the case.
*/
WorkerManager.prototype._checkStopEmptyWorker = function () {
if (!this._editorWorkerClient) {
return;
}
var models = this._modelService.getModels();
if (models.length === 0) {
// There are no more models => nothing possible for me to do
this._editorWorkerClient.dispose();
this._editorWorkerClient = null;
}
};
/**
* Check if the worker has been idle for a while and then stop it.
*/
WorkerManager.prototype._checkStopIdleWorker = function () {
if (!this._editorWorkerClient) {
return;
}
var timeSinceLastWorkerUsedTime = (new Date()).getTime() - this._lastWorkerUsedTime;
if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) {
this._editorWorkerClient.dispose();
this._editorWorkerClient = null;
}
};
WorkerManager.prototype.withWorker = function () {
this._lastWorkerUsedTime = (new Date()).getTime();
if (!this._editorWorkerClient) {
this._editorWorkerClient = new EditorWorkerClient(this._modelService, false, 'editorWorkerService');
}
return Promise.resolve(this._editorWorkerClient);
};
return WorkerManager;
}(lifecycle_1.Disposable));
var EditorModelManager = /** @class */ (function (_super) {
__extends(EditorModelManager, _super);
function EditorModelManager(proxy, modelService, keepIdleModels) {
var _this = _super.call(this) || this;
_this._syncedModels = Object.create(null);
_this._syncedModelsLastUsedTime = Object.create(null);
_this._proxy = proxy;
_this._modelService = modelService;
if (!keepIdleModels) {
var timer = new async_1.IntervalTimer();
timer.cancelAndSet(function () { return _this._checkStopModelSync(); }, Math.round(STOP_SYNC_MODEL_DELTA_TIME_MS / 2));
_this._register(timer);
}
return _this;
}
EditorModelManager.prototype.dispose = function () {
for (var modelUrl in this._syncedModels) {
lifecycle_1.dispose(this._syncedModels[modelUrl]);
}
this._syncedModels = Object.create(null);
this._syncedModelsLastUsedTime = Object.create(null);
_super.prototype.dispose.call(this);
};
EditorModelManager.prototype.ensureSyncedResources = function (resources) {
for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
var resource = resources_1[_i];
var resourceStr = resource.toString();
if (!this._syncedModels[resourceStr]) {
this._beginModelSync(resource);
}
if (this._syncedModels[resourceStr]) {
this._syncedModelsLastUsedTime[resourceStr] = (new Date()).getTime();
}
}
};
EditorModelManager.prototype._checkStopModelSync = function () {
var currentTime = (new Date()).getTime();
var toRemove = [];
for (var modelUrl in this._syncedModelsLastUsedTime) {
var elapsedTime = currentTime - this._syncedModelsLastUsedTime[modelUrl];
if (elapsedTime > STOP_SYNC_MODEL_DELTA_TIME_MS) {
toRemove.push(modelUrl);
}
}
for (var _i = 0, toRemove_1 = toRemove; _i < toRemove_1.length; _i++) {
var e = toRemove_1[_i];
this._stopModelSync(e);
}
};
EditorModelManager.prototype._beginModelSync = function (resource) {
var _this = this;
var model = this._modelService.getModel(resource);
if (!model) {
return;
}
if (model.isTooLargeForSyncing()) {
return;
}
var modelUrl = resource.toString();
this._proxy.acceptNewModel({
url: model.uri.toString(),
lines: model.getLinesContent(),
EOL: model.getEOL(),
versionId: model.getVersionId()
});
var toDispose = new lifecycle_1.DisposableStore();
toDispose.add(model.onDidChangeContent(function (e) {
_this._proxy.acceptModelChanged(modelUrl.toString(), e);
}));
toDispose.add(model.onWillDispose(function () {
_this._stopModelSync(modelUrl);
}));
toDispose.add(lifecycle_1.toDisposable(function () {
_this._proxy.acceptRemovedModel(modelUrl);
}));
this._syncedModels[modelUrl] = toDispose;
};
EditorModelManager.prototype._stopModelSync = function (modelUrl) {
var toDispose = this._syncedModels[modelUrl];
delete this._syncedModels[modelUrl];
delete this._syncedModelsLastUsedTime[modelUrl];
lifecycle_1.dispose(toDispose);
};
return EditorModelManager;
}(lifecycle_1.Disposable));
var SynchronousWorkerClient = /** @class */ (function () {
function SynchronousWorkerClient(instance) {
this._instance = instance;
this._proxyObj = Promise.resolve(this._instance);
}
SynchronousWorkerClient.prototype.dispose = function () {
this._instance.dispose();
};
SynchronousWorkerClient.prototype.getProxyObject = function () {
return this._proxyObj;
};
return SynchronousWorkerClient;
}());
var EditorWorkerHost = /** @class */ (function () {
function EditorWorkerHost(workerClient) {
this._workerClient = workerClient;
}
// foreign host request
EditorWorkerHost.prototype.fhr = function (method, args) {
return this._workerClient.fhr(method, args);
};
return EditorWorkerHost;
}());
exports.EditorWorkerHost = EditorWorkerHost;
var EditorWorkerClient = /** @class */ (function (_super) {
__extends(EditorWorkerClient, _super);
function EditorWorkerClient(modelService, keepIdleModels, label) {
var _this = _super.call(this) || this;
_this._modelService = modelService;
_this._keepIdleModels = keepIdleModels;
_this._workerFactory = new defaultWorkerFactory_1.DefaultWorkerFactory(label);
_this._worker = null;
_this._modelManager = null;
return _this;
}
// foreign host request
EditorWorkerClient.prototype.fhr = function (method, args) {
throw new Error("Not implemented!");
};
EditorWorkerClient.prototype._getOrCreateWorker = function () {
if (!this._worker) {
try {
this._worker = this._register(new simpleWorker_1.SimpleWorkerClient(this._workerFactory, 'vs/editor/common/services/editorSimpleWorker', new EditorWorkerHost(this)));
}
catch (err) {
simpleWorker_1.logOnceWebWorkerWarning(err);
this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorker(new EditorWorkerHost(this), null));
}
}
return this._worker;
};
EditorWorkerClient.prototype._getProxy = function () {
var _this = this;
return this._getOrCreateWorker().getProxyObject().then(undefined, function (err) {
simpleWorker_1.logOnceWebWorkerWarning(err);
_this._worker = new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorker(new EditorWorkerHost(_this), null));
return _this._getOrCreateWorker().getProxyObject();
});
};
EditorWorkerClient.prototype._getOrCreateModelManager = function (proxy) {
if (!this._modelManager) {
this._modelManager = this._register(new EditorModelManager(proxy, this._modelService, this._keepIdleModels));
}
return this._modelManager;
};
EditorWorkerClient.prototype._withSyncedResources = function (resources) {
var _this = this;
return this._getProxy().then(function (proxy) {
_this._getOrCreateModelManager(proxy).ensureSyncedResources(resources);
return proxy;
});
};
EditorWorkerClient.prototype.computeDiff = function (original, modified, ignoreTrimWhitespace, maxComputationTime) {
return this._withSyncedResources([original, modified]).then(function (proxy) {
return proxy.computeDiff(original.toString(), modified.toString(), ignoreTrimWhitespace, maxComputationTime);
});
};
EditorWorkerClient.prototype.computeMoreMinimalEdits = function (resource, edits) {
return this._withSyncedResources([resource]).then(function (proxy) {
return proxy.computeMoreMinimalEdits(resource.toString(), edits);
});
};
EditorWorkerClient.prototype.computeLinks = function (resource) {
return this._withSyncedResources([resource]).then(function (proxy) {
return proxy.computeLinks(resource.toString());
});
};
EditorWorkerClient.prototype.textualSuggest = function (resource, position) {
var _this = this;
return this._withSyncedResources([resource]).then(function (proxy) {
var model = _this._modelService.getModel(resource);
if (!model) {
return null;
}
var wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
var wordDef = wordDefRegExp.source;
var wordDefFlags = strings_1.regExpFlags(wordDefRegExp);
return proxy.textualSuggest(resource.toString(), position, wordDef, wordDefFlags);
});
};
EditorWorkerClient.prototype.computeWordRanges = function (resource, range) {
var _this = this;
return this._withSyncedResources([resource]).then(function (proxy) {
var model = _this._modelService.getModel(resource);
if (!model) {
return Promise.resolve(null);
}
var wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
var wordDef = wordDefRegExp.source;
var wordDefFlags = strings_1.regExpFlags(wordDefRegExp);
return proxy.computeWordRanges(resource.toString(), range, wordDef, wordDefFlags);
});
};
EditorWorkerClient.prototype.navigateValueSet = function (resource, range, up) {
var _this = this;
return this._withSyncedResources([resource]).then(function (proxy) {
var model = _this._modelService.getModel(resource);
if (!model) {
return null;
}
var wordDefRegExp = languageConfigurationRegistry_1.LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id);
var wordDef = wordDefRegExp.source;
var wordDefFlags = strings_1.regExpFlags(wordDefRegExp);
return proxy.navigateValueSet(resource.toString(), range, up, wordDef, wordDefFlags);
});
};
return EditorWorkerClient;
}(lifecycle_1.Disposable));
exports.EditorWorkerClient = EditorWorkerClient;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[507/*vs/editor/common/services/webWorker*/], __M([0/*require*/,1/*exports*/,219/*vs/editor/common/services/editorWorkerServiceImpl*/,21/*vs/base/common/types*/]), function (require, exports, editorWorkerServiceImpl_1, types) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Create a new web worker that has model syncing capabilities built in.
* Specify an AMD module to load that will `create` an object that will be proxied.
*/
function createWebWorker(modelService, opts) {
return new MonacoWebWorkerImpl(modelService, opts);
}
exports.createWebWorker = createWebWorker;
var MonacoWebWorkerImpl = /** @class */ (function (_super) {
__extends(MonacoWebWorkerImpl, _super);
function MonacoWebWorkerImpl(modelService, opts) {
var _this = _super.call(this, modelService, opts.keepIdleModels || false, opts.label) || this;
_this._foreignModuleId = opts.moduleId;
_this._foreignModuleCreateData = opts.createData || null;
_this._foreignModuleHost = opts.host || null;
_this._foreignProxy = null;
return _this;
}
// foreign host request
MonacoWebWorkerImpl.prototype.fhr = function (method, args) {
if (!this._foreignModuleHost || typeof this._foreignModuleHost[method] !== 'function') {
return Promise.reject(new Error('Missing method ' + method + ' or missing main thread foreign host.'));
}
try {
return Promise.resolve(this._foreignModuleHost[method].apply(this._foreignModuleHost, args));
}
catch (e) {
return Promise.reject(e);
}
};
MonacoWebWorkerImpl.prototype._getForeignProxy = function () {
var _this = this;
if (!this._foreignProxy) {
this._foreignProxy = this._getProxy().then(function (proxy) {
var foreignHostMethods = _this._foreignModuleHost ? types.getAllMethodNames(_this._foreignModuleHost) : [];
return proxy.loadForeignModule(_this._foreignModuleId, _this._foreignModuleCreateData, foreignHostMethods).then(function (foreignMethods) {
_this._foreignModuleCreateData = null;
var proxyMethodRequest = function (method, args) {
return proxy.fmr(method, args);
};
var createProxyMethod = function (method, proxyMethodRequest) {
return function () {
var args = Array.prototype.slice.call(arguments, 0);
return proxyMethodRequest(method, args);
};
};
var foreignProxy = {};
for (var _i = 0, foreignMethods_1 = foreignMethods; _i < foreignMethods_1.length; _i++) {
var foreignMethod = foreignMethods_1[_i];
foreignProxy[foreignMethod] = createProxyMethod(foreignMethod, proxyMethodRequest);
}
return foreignProxy;
});
});
}
return this._foreignProxy;
};
MonacoWebWorkerImpl.prototype.getProxy = function () {
return this._getForeignProxy();
};
MonacoWebWorkerImpl.prototype.withSyncedResources = function (resources) {
var _this = this;
return this._withSyncedResources(resources).then(function (_) { return _this.getProxy(); });
};
return MonacoWebWorkerImpl;
}(editorWorkerServiceImpl_1.EditorWorkerClient));
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[72/*vs/platform/markers/common/markers*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/,475/*vs/nls!vs/platform/markers/common/markers*/,112/*vs/base/common/severity*/]), function (require, exports, instantiation_1, nls_1, severity_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MarkerSeverity;
(function (MarkerSeverity) {
MarkerSeverity[MarkerSeverity["Hint"] = 1] = "Hint";
MarkerSeverity[MarkerSeverity["Info"] = 2] = "Info";
MarkerSeverity[MarkerSeverity["Warning"] = 4] = "Warning";
MarkerSeverity[MarkerSeverity["Error"] = 8] = "Error";
})(MarkerSeverity = exports.MarkerSeverity || (exports.MarkerSeverity = {}));
(function (MarkerSeverity) {
function compare(a, b) {
return b - a;
}
MarkerSeverity.compare = compare;
var _displayStrings = Object.create(null);
_displayStrings[MarkerSeverity.Error] = nls_1.localize(0, null);
_displayStrings[MarkerSeverity.Warning] = nls_1.localize(1, null);
_displayStrings[MarkerSeverity.Info] = nls_1.localize(2, null);
function toString(a) {
return _displayStrings[a] || '';
}
MarkerSeverity.toString = toString;
function fromSeverity(severity) {
switch (severity) {
case severity_1.default.Error: return MarkerSeverity.Error;
case severity_1.default.Warning: return MarkerSeverity.Warning;
case severity_1.default.Info: return MarkerSeverity.Info;
case severity_1.default.Ignore: return MarkerSeverity.Hint;
}
}
MarkerSeverity.fromSeverity = fromSeverity;
function toSeverity(severity) {
switch (severity) {
case MarkerSeverity.Error: return severity_1.default.Error;
case MarkerSeverity.Warning: return severity_1.default.Warning;
case MarkerSeverity.Info: return severity_1.default.Info;
case MarkerSeverity.Hint: return severity_1.default.Ignore;
}
}
MarkerSeverity.toSeverity = toSeverity;
})(MarkerSeverity = exports.MarkerSeverity || (exports.MarkerSeverity = {}));
var IMarkerData;
(function (IMarkerData) {
var emptyString = '';
function makeKey(markerData) {
return makeKeyOptionalMessage(markerData, true);
}
IMarkerData.makeKey = makeKey;
function makeKeyOptionalMessage(markerData, useMessage) {
var result = [emptyString];
if (markerData.source) {
result.push(markerData.source.replace('¦', '\¦'));
}
else {
result.push(emptyString);
}
if (markerData.code) {
if (typeof markerData.code === 'string') {
result.push(markerData.code.replace('¦', '\¦'));
}
else {
result.push(markerData.code.value.replace('¦', '\¦'));
}
}
else {
result.push(emptyString);
}
if (markerData.severity !== undefined && markerData.severity !== null) {
result.push(MarkerSeverity.toString(markerData.severity));
}
else {
result.push(emptyString);
}
// Modifed to not include the message as part of the marker key to work around
// https://github.com/microsoft/vscode/issues/77475
if (markerData.message && useMessage) {
result.push(markerData.message.replace('¦', '\¦'));
}
else {
result.push(emptyString);
}
if (markerData.startLineNumber !== undefined && markerData.startLineNumber !== null) {
result.push(markerData.startLineNumber.toString());
}
else {
result.push(emptyString);
}
if (markerData.startColumn !== undefined && markerData.startColumn !== null) {
result.push(markerData.startColumn.toString());
}
else {
result.push(emptyString);
}
if (markerData.endLineNumber !== undefined && markerData.endLineNumber !== null) {
result.push(markerData.endLineNumber.toString());
}
else {
result.push(emptyString);
}
if (markerData.endColumn !== undefined && markerData.endColumn !== null) {
result.push(markerData.endColumn.toString());
}
else {
result.push(emptyString);
}
result.push(emptyString);
return result.join('¦');
}
IMarkerData.makeKeyOptionalMessage = makeKeyOptionalMessage;
})(IMarkerData = exports.IMarkerData || (exports.IMarkerData = {}));
exports.IMarkerService = instantiation_1.createDecorator('markerService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[508/*vs/platform/markers/common/markerService*/], __M([0/*require*/,1/*exports*/,19/*vs/base/common/arrays*/,46/*vs/base/common/network*/,21/*vs/base/common/types*/,4/*vs/base/common/event*/,72/*vs/platform/markers/common/markers*/]), function (require, exports, arrays_1, network_1, types_1, event_1, markers_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MapMap;
(function (MapMap) {
function get(map, key1, key2) {
if (map[key1]) {
return map[key1][key2];
}
return undefined;
}
MapMap.get = get;
function set(map, key1, key2, value) {
if (!map[key1]) {
map[key1] = Object.create(null);
}
map[key1][key2] = value;
}
MapMap.set = set;
function remove(map, key1, key2) {
if (map[key1] && map[key1][key2]) {
delete map[key1][key2];
if (types_1.isEmptyObject(map[key1])) {
delete map[key1];
}
return true;
}
return false;
}
MapMap.remove = remove;
})(MapMap || (MapMap = {}));
var MarkerStats = /** @class */ (function () {
function MarkerStats(service) {
this.errors = 0;
this.infos = 0;
this.warnings = 0;
this.unknowns = 0;
this._data = Object.create(null);
this._service = service;
this._subscription = service.onMarkerChanged(this._update, this);
}
MarkerStats.prototype.dispose = function () {
this._subscription.dispose();
this._data = undefined;
};
MarkerStats.prototype._update = function (resources) {
if (!this._data) {
return;
}
for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
var resource = resources_1[_i];
var key = resource.toString();
var oldStats = this._data[key];
if (oldStats) {
this._substract(oldStats);
}
var newStats = this._resourceStats(resource);
this._add(newStats);
this._data[key] = newStats;
}
};
MarkerStats.prototype._resourceStats = function (resource) {
var result = { errors: 0, warnings: 0, infos: 0, unknowns: 0 };
// TODO this is a hack
if (resource.scheme === network_1.Schemas.inMemory || resource.scheme === network_1.Schemas.walkThrough || resource.scheme === network_1.Schemas.walkThroughSnippet) {
return result;
}
for (var _i = 0, _a = this._service.read({ resource: resource }); _i < _a.length; _i++) {
var severity = _a[_i].severity;
if (severity === markers_1.MarkerSeverity.Error) {
result.errors += 1;
}
else if (severity === markers_1.MarkerSeverity.Warning) {
result.warnings += 1;
}
else if (severity === markers_1.MarkerSeverity.Info) {
result.infos += 1;
}
else {
result.unknowns += 1;
}
}
return result;
};
MarkerStats.prototype._substract = function (op) {
this.errors -= op.errors;
this.warnings -= op.warnings;
this.infos -= op.infos;
this.unknowns -= op.unknowns;
};
MarkerStats.prototype._add = function (op) {
this.errors += op.errors;
this.warnings += op.warnings;
this.infos += op.infos;
this.unknowns += op.unknowns;
};
return MarkerStats;
}());
var MarkerService = /** @class */ (function () {
function MarkerService() {
this._onMarkerChanged = new event_1.Emitter();
this._onMarkerChangedEvent = event_1.Event.debounce(this._onMarkerChanged.event, MarkerService._debouncer, 0);
this._byResource = Object.create(null);
this._byOwner = Object.create(null);
this._stats = new MarkerStats(this);
}
MarkerService.prototype.dispose = function () {
this._stats.dispose();
};
Object.defineProperty(MarkerService.prototype, "onMarkerChanged", {
get: function () {
return this._onMarkerChangedEvent;
},
enumerable: true,
configurable: true
});
MarkerService.prototype.remove = function (owner, resources) {
for (var _i = 0, _a = resources || []; _i < _a.length; _i++) {
var resource = _a[_i];
this.changeOne(owner, resource, []);
}
};
MarkerService.prototype.changeOne = function (owner, resource, markerData) {
if (arrays_1.isFalsyOrEmpty(markerData)) {
// remove marker for this (owner,resource)-tuple
var a = MapMap.remove(this._byResource, resource.toString(), owner);
var b = MapMap.remove(this._byOwner, owner, resource.toString());
if (a !== b) {
throw new Error('invalid marker service state');
}
if (a && b) {
this._onMarkerChanged.fire([resource]);
}
}
else {
// insert marker for this (owner,resource)-tuple
var markers = [];
for (var _i = 0, markerData_1 = markerData; _i < markerData_1.length; _i++) {
var data = markerData_1[_i];
var marker = MarkerService._toMarker(owner, resource, data);
if (marker) {
markers.push(marker);
}
}
MapMap.set(this._byResource, resource.toString(), owner, markers);
MapMap.set(this._byOwner, owner, resource.toString(), markers);
this._onMarkerChanged.fire([resource]);
}
};
MarkerService._toMarker = function (owner, resource, data) {
var code = data.code, severity = data.severity, message = data.message, source = data.source, startLineNumber = data.startLineNumber, startColumn = data.startColumn, endLineNumber = data.endLineNumber, endColumn = data.endColumn, relatedInformation = data.relatedInformation, tags = data.tags;
if (!message) {
return undefined;
}
// santize data
startLineNumber = startLineNumber > 0 ? startLineNumber : 1;
startColumn = startColumn > 0 ? startColumn : 1;
endLineNumber = endLineNumber >= startLineNumber ? endLineNumber : startLineNumber;
endColumn = endColumn > 0 ? endColumn : startColumn;
return {
resource: resource,
owner: owner,
code: code,
severity: severity,
message: message,
source: source,
startLineNumber: startLineNumber,
startColumn: startColumn,
endLineNumber: endLineNumber,
endColumn: endColumn,
relatedInformation: relatedInformation,
tags: tags,
};
};
MarkerService.prototype.read = function (filter) {
if (filter === void 0) { filter = Object.create(null); }
var owner = filter.owner, resource = filter.resource, severities = filter.severities, take = filter.take;
if (!take || take < 0) {
take = -1;
}
if (owner && resource) {
// exactly one owner AND resource
var data = MapMap.get(this._byResource, resource.toString(), owner);
if (!data) {
return [];
}
else {
var result = [];
for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
var marker = data_1[_i];
if (MarkerService._accept(marker, severities)) {
var newLen = result.push(marker);
if (take > 0 && newLen === take) {
break;
}
}
}
return result;
}
}
else if (!owner && !resource) {
// all
var result = [];
for (var key1 in this._byResource) {
for (var key2 in this._byResource[key1]) {
for (var _a = 0, _b = this._byResource[key1][key2]; _a < _b.length; _a++) {
var data = _b[_a];
if (MarkerService._accept(data, severities)) {
var newLen = result.push(data);
if (take > 0 && newLen === take) {
return result;
}
}
}
}
}
return result;
}
else {
// of one resource OR owner
var map = owner
? this._byOwner[owner]
: resource ? this._byResource[resource.toString()] : undefined;
if (!map) {
return [];
}
var result = [];
for (var key in map) {
for (var _c = 0, _d = map[key]; _c < _d.length; _c++) {
var data = _d[_c];
if (MarkerService._accept(data, severities)) {
var newLen = result.push(data);
if (take > 0 && newLen === take) {
return result;
}
}
}
}
return result;
}
};
MarkerService._accept = function (marker, severities) {
return severities === undefined || (severities & marker.severity) === marker.severity;
};
MarkerService._debouncer = function (last, event) {
if (!last) {
MarkerService._dedupeMap = Object.create(null);
last = [];
}
for (var _i = 0, event_2 = event; _i < event_2.length; _i++) {
var uri = event_2[_i];
if (MarkerService._dedupeMap[uri.toString()] === undefined) {
MarkerService._dedupeMap[uri.toString()] = true;
last.push(uri);
}
}
return last;
};
return MarkerService;
}());
exports.MarkerService = MarkerService;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[35/*vs/platform/notification/common/notification*/], __M([0/*require*/,1/*exports*/,112/*vs/base/common/severity*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, severity_1, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Severity = severity_1.default;
exports.INotificationService = instantiation_1.createDecorator('notificationService');
var NoOpNotification = /** @class */ (function () {
function NoOpNotification() {
}
return NoOpNotification;
}());
exports.NoOpNotification = NoOpNotification;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[51/*vs/platform/opener/common/opener*/], __M([0/*require*/,1/*exports*/,25/*vs/base/common/uri*/,11/*vs/platform/instantiation/common/instantiation*/,2/*vs/base/common/lifecycle*/,5/*vs/base/common/strings*/]), function (require, exports, uri_1, instantiation_1, lifecycle_1, strings_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IOpenerService = instantiation_1.createDecorator('openerService');
exports.NullOpenerService = Object.freeze({
_serviceBrand: undefined,
registerOpener: function () { return lifecycle_1.Disposable.None; },
registerValidator: function () { return lifecycle_1.Disposable.None; },
registerExternalUriResolver: function () { return lifecycle_1.Disposable.None; },
setExternalOpener: function () { },
open: function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, false];
}); });
},
resolveExternalUri: function (uri) {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, { resolved: uri, dispose: function () { } }];
}); });
},
});
function matchesScheme(target, scheme) {
if (uri_1.URI.isUri(target)) {
return strings_1.equalsIgnoreCase(target.scheme, scheme);
}
else {
return strings_1.startsWithIgnoreCase(target, scheme + ':');
}
}
exports.matchesScheme = matchesScheme;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
define(__m[509/*vs/editor/browser/services/openerService*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,76/*vs/base/common/linkedList*/,180/*vs/base/common/marshalling*/,46/*vs/base/common/network*/,39/*vs/base/common/resources*/,25/*vs/base/common/uri*/,32/*vs/editor/browser/services/codeEditorService*/,29/*vs/platform/commands/common/commands*/,51/*vs/platform/opener/common/opener*/,478/*vs/platform/editor/common/editor*/]), function (require, exports, dom, linkedList_1, marshalling_1, network_1, resources_1, uri_1, codeEditorService_1, commands_1, opener_1, editor_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CommandOpener = /** @class */ (function () {
function CommandOpener(_commandService) {
this._commandService = _commandService;
}
CommandOpener.prototype.open = function (target) {
return __awaiter(this, void 0, void 0, function () {
var args;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!opener_1.matchesScheme(target, network_1.Schemas.command)) {
return [2 /*return*/, false];
}
// run command or bail out if command isn't known
if (typeof target === 'string') {
target = uri_1.URI.parse(target);
}
if (!commands_1.CommandsRegistry.getCommand(target.path)) {
throw new Error("command '" + target.path + "' NOT known");
}
args = [];
try {
args = marshalling_1.parse(decodeURIComponent(target.query));
}
catch (_c) {
// ignore and retry
try {
args = marshalling_1.parse(target.query);
}
catch (_d) {
// ignore error
}
}
if (!Array.isArray(args)) {
args = [args];
}
return [4 /*yield*/, (_a = this._commandService).executeCommand.apply(_a, __spreadArrays([target.path], args))];
case 1:
_b.sent();
return [2 /*return*/, true];
}
});
});
};
CommandOpener = __decorate([
__param(0, commands_1.ICommandService)
], CommandOpener);
return CommandOpener;
}());
var EditorOpener = /** @class */ (function () {
function EditorOpener(_editorService) {
this._editorService = _editorService;
}
EditorOpener.prototype.open = function (target, options) {
return __awaiter(this, void 0, void 0, function () {
var selection, match;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (typeof target === 'string') {
target = uri_1.URI.parse(target);
}
selection = undefined;
match = /^L?(\d+)(?:,(\d+))?/.exec(target.fragment);
if (match) {
// support file:///some/file.js#73,84
// support file:///some/file.js#L73
selection = {
startLineNumber: parseInt(match[1]),
startColumn: match[2] ? parseInt(match[2]) : 1
};
// remove fragment
target = target.with({ fragment: '' });
}
if (target.scheme === network_1.Schemas.file) {
target = resources_1.normalizePath(target); // workaround for non-normalized paths (https://github.com/Microsoft/vscode/issues/12954)
}
return [4 /*yield*/, this._editorService.openCodeEditor({ resource: target, options: { selection: selection, context: (options === null || options === void 0 ? void 0 : options.fromUserGesture) ? editor_1.EditorOpenContext.USER : editor_1.EditorOpenContext.API } }, this._editorService.getFocusedCodeEditor(), options === null || options === void 0 ? void 0 : options.openToSide)];
case 1:
_a.sent();
return [2 /*return*/, true];
}
});
});
};
EditorOpener = __decorate([
__param(0, codeEditorService_1.ICodeEditorService)
], EditorOpener);
return EditorOpener;
}());
var OpenerService = /** @class */ (function () {
function OpenerService(editorService, commandService) {
var _this = this;
this._openers = new linkedList_1.LinkedList();
this._validators = new linkedList_1.LinkedList();
this._resolvers = new linkedList_1.LinkedList();
// Default external opener is going through window.open()
this._externalOpener = {
openExternal: function (href) {
dom.windowOpenNoOpener(href);
return Promise.resolve(true);
}
};
// Default opener: maito, http(s), command, and catch-all-editors
this._openers.push({
open: function (target, options) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!((options === null || options === void 0 ? void 0 : options.openExternal) || opener_1.matchesScheme(target, network_1.Schemas.mailto) || opener_1.matchesScheme(target, network_1.Schemas.http) || opener_1.matchesScheme(target, network_1.Schemas.https))) return [3 /*break*/, 2];
// open externally
return [4 /*yield*/, this._doOpenExternal(target, options)];
case 1:
// open externally
_a.sent();
return [2 /*return*/, true];
case 2: return [2 /*return*/, false];
}
});
}); }
});
this._openers.push(new CommandOpener(commandService));
this._openers.push(new EditorOpener(editorService));
}
OpenerService.prototype.open = function (target, options) {
return __awaiter(this, void 0, void 0, function () {
var _i, _a, validator, _b, _c, opener_2, handled;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_i = 0, _a = this._validators.toArray();
_d.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
validator = _a[_i];
return [4 /*yield*/, validator.shouldOpen(target)];
case 2:
if (!(_d.sent())) {
return [2 /*return*/, false];
}
_d.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4:
_b = 0, _c = this._openers.toArray();
_d.label = 5;
case 5:
if (!(_b < _c.length)) return [3 /*break*/, 8];
opener_2 = _c[_b];
return [4 /*yield*/, opener_2.open(target, options)];
case 6:
handled = _d.sent();
if (handled) {
return [2 /*return*/, true];
}
_d.label = 7;
case 7:
_b++;
return [3 /*break*/, 5];
case 8: return [2 /*return*/, false];
}
});
});
};
OpenerService.prototype.resolveExternalUri = function (resource, options) {
return __awaiter(this, void 0, void 0, function () {
var _i, _a, resolver, result;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_i = 0, _a = this._resolvers.toArray();
_b.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
resolver = _a[_i];
return [4 /*yield*/, resolver.resolveExternalUri(resource, options)];
case 2:
result = _b.sent();
if (result) {
return [2 /*return*/, result];
}
_b.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, { resolved: resource, dispose: function () { } }];
}
});
});
};
OpenerService.prototype._doOpenExternal = function (resource, options) {
return __awaiter(this, void 0, void 0, function () {
var uri, resolved;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
uri = typeof resource === 'string' ? uri_1.URI.parse(resource) : resource;
return [4 /*yield*/, this.resolveExternalUri(uri, options)];
case 1:
resolved = (_a.sent()).resolved;
if (typeof resource === 'string' && uri.toString() === resolved.toString()) {
// open the url-string AS IS
return [2 /*return*/, this._externalOpener.openExternal(resource)];
}
else {
// open URI using the toString(noEncode)+encodeURI-trick
return [2 /*return*/, this._externalOpener.openExternal(encodeURI(resolved.toString(true)))];
}
return [2 /*return*/];
}
});
});
};
OpenerService.prototype.dispose = function () {
this._validators.clear();
};
OpenerService = __decorate([
__param(0, codeEditorService_1.ICodeEditorService),
__param(1, commands_1.ICommandService)
], OpenerService);
return OpenerService;
}());
exports.OpenerService = OpenerService;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[117/*vs/editor/contrib/markdown/markdownRenderer*/], __M([0/*require*/,1/*exports*/,248/*vs/base/browser/markdownRenderer*/,51/*vs/platform/opener/common/opener*/,71/*vs/editor/common/services/modeService*/,10/*vs/base/common/errors*/,214/*vs/editor/common/modes/textToHtmlTokenizer*/,11/*vs/platform/instantiation/common/instantiation*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,17/*vs/editor/common/modes*/]), function (require, exports, markdownRenderer_1, opener_1, modeService_1, errors_1, textToHtmlTokenizer_1, instantiation_1, event_1, lifecycle_1, modes_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MarkdownRenderer = /** @class */ (function (_super) {
__extends(MarkdownRenderer, _super);
function MarkdownRenderer(_editor, _modeService, _openerService) {
if (_openerService === void 0) { _openerService = opener_1.NullOpenerService; }
var _this = _super.call(this) || this;
_this._editor = _editor;
_this._modeService = _modeService;
_this._openerService = _openerService;
_this._onDidRenderCodeBlock = _this._register(new event_1.Emitter());
_this.onDidRenderCodeBlock = _this._onDidRenderCodeBlock.event;
return _this;
}
MarkdownRenderer.prototype.getOptions = function (disposeables) {
var _this = this;
return {
codeBlockRenderer: function (languageAlias, value) {
// In markdown,
// it is possible that we stumble upon language aliases (e.g.js instead of javascript)
// it is possible no alias is given in which case we fall back to the current editor lang
var modeId = null;
if (languageAlias) {
modeId = _this._modeService.getModeIdForLanguageName(languageAlias);
}
else {
var model = _this._editor.getModel();
if (model) {
modeId = model.getLanguageIdentifier().language;
}
}
_this._modeService.triggerMode(modeId || '');
return Promise.resolve(true).then(function (_) {
var promise = modes_1.TokenizationRegistry.getPromise(modeId || '');
if (promise) {
return promise.then(function (support) { return textToHtmlTokenizer_1.tokenizeToString(value, support); });
}
return textToHtmlTokenizer_1.tokenizeToString(value, undefined);
}).then(function (code) {
return "" + code + "";
});
},
codeBlockRenderCallback: function () { return _this._onDidRenderCodeBlock.fire(); },
actionHandler: {
callback: function (content) {
_this._openerService.open(content, { fromUserGesture: true }).catch(errors_1.onUnexpectedError);
},
disposeables: disposeables
}
};
};
MarkdownRenderer.prototype.render = function (markdown) {
var disposeables = new lifecycle_1.DisposableStore();
var element;
if (!markdown) {
element = document.createElement('span');
}
else {
element = markdownRenderer_1.renderMarkdown(markdown, this.getOptions(disposeables));
}
return {
element: element,
dispose: function () { return disposeables.dispose(); }
};
};
MarkdownRenderer = __decorate([
__param(1, modeService_1.IModeService),
__param(2, instantiation_1.optional(opener_1.IOpenerService))
], MarkdownRenderer);
return MarkdownRenderer;
}(lifecycle_1.Disposable));
exports.MarkdownRenderer = MarkdownRenderer;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[510/*vs/editor/contrib/hover/modesGlyphHover*/], __M([0/*require*/,1/*exports*/,6/*vs/base/browser/dom*/,75/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,200/*vs/editor/contrib/hover/hoverOperation*/,201/*vs/editor/contrib/hover/hoverWidgets*/,117/*vs/editor/contrib/markdown/markdownRenderer*/,51/*vs/platform/opener/common/opener*/,19/*vs/base/common/arrays*/]), function (require, exports, dom_1, htmlContent_1, lifecycle_1, hoverOperation_1, hoverWidgets_1, markdownRenderer_1, opener_1, arrays_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MarginComputer = /** @class */ (function () {
function MarginComputer(editor) {
this._editor = editor;
this._lineNumber = -1;
this._result = [];
}
MarginComputer.prototype.setLineNumber = function (lineNumber) {
this._lineNumber = lineNumber;
this._result = [];
};
MarginComputer.prototype.clearResult = function () {
this._result = [];
};
MarginComputer.prototype.computeSync = function () {
var toHoverMessage = function (contents) {
return {
value: contents
};
};
var lineDecorations = this._editor.getLineDecorations(this._lineNumber);
var result = [];
if (!lineDecorations) {
return result;
}
for (var _i = 0, lineDecorations_1 = lineDecorations; _i < lineDecorations_1.length; _i++) {
var d = lineDecorations_1[_i];
if (!d.options.glyphMarginClassName) {
continue;
}
var hoverMessage = d.options.glyphMarginHoverMessage;
if (!hoverMessage || htmlContent_1.isEmptyMarkdownString(hoverMessage)) {
continue;
}
result.push.apply(result, arrays_1.asArray(hoverMessage).map(toHoverMessage));
}
return result;
};
MarginComputer.prototype.onResult = function (result, isFromSynchronousComputation) {
this._result = this._result.concat(result);
};
MarginComputer.prototype.getResult = function () {
return this._result;
};
MarginComputer.prototype.getResultWithLoadingMessage = function () {
return this.getResult();
};
return MarginComputer;
}());
var ModesGlyphHoverWidget = /** @class */ (function (_super) {
__extends(ModesGlyphHoverWidget, _super);
function ModesGlyphHoverWidget(editor, modeService, openerService) {
if (openerService === void 0) { openerService = opener_1.NullOpenerService; }
var _this = _super.call(this, ModesGlyphHoverWidget.ID, editor) || this;
_this._renderDisposeables = _this._register(new lifecycle_1.DisposableStore());
_this._messages = [];
_this._lastLineNumber = -1;
_this._markdownRenderer = _this._register(new markdownRenderer_1.MarkdownRenderer(_this._editor, modeService, openerService));
_this._computer = new MarginComputer(_this._editor);
_this._hoverOperation = new hoverOperation_1.HoverOperation(_this._computer, function (result) { return _this._withResult(result); }, undefined, function (result) { return _this._withResult(result); }, 300);
return _this;
}
ModesGlyphHoverWidget.prototype.dispose = function () {
this._hoverOperation.cancel();
_super.prototype.dispose.call(this);
};
ModesGlyphHoverWidget.prototype.onModelDecorationsChanged = function () {
if (this.isVisible) {
// The decorations have changed and the hover is visible,
// we need to recompute the displayed text
this._hoverOperation.cancel();
this._computer.clearResult();
this._hoverOperation.start(0 /* Delayed */);
}
};
ModesGlyphHoverWidget.prototype.startShowingAt = function (lineNumber) {
if (this._lastLineNumber === lineNumber) {
// We have to show the widget at the exact same line number as before, so no work is needed
return;
}
this._hoverOperation.cancel();
this.hide();
this._lastLineNumber = lineNumber;
this._computer.setLineNumber(lineNumber);
this._hoverOperation.start(0 /* Delayed */);
};
ModesGlyphHoverWidget.prototype.hide = function () {
this._lastLineNumber = -1;
this._hoverOperation.cancel();
_super.prototype.hide.call(this);
};
ModesGlyphHoverWidget.prototype._withResult = function (result) {
this._messages = result;
if (this._messages.length > 0) {
this._renderMessages(this._lastLineNumber, this._messages);
}
else {
this.hide();
}
};
ModesGlyphHoverWidget.prototype._renderMessages = function (lineNumber, messages) {
this._renderDisposeables.clear();
var fragment = document.createDocumentFragment();
for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) {
var msg = messages_1[_i];
var renderedContents = this._markdownRenderer.render(msg.value);
this._renderDisposeables.add(renderedContents);
fragment.appendChild(dom_1.$('div.hover-row', undefined, renderedContents.element));
}
this.updateContents(fragment);
this.showAt(lineNumber);
};
ModesGlyphHoverWidget.ID = 'editor.contrib.modesGlyphHoverWidget';
return ModesGlyphHoverWidget;
}(hoverWidgets_1.GlyphHoverWidget));
exports.ModesGlyphHoverWidget = ModesGlyphHoverWidget;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[73/*vs/platform/progress/common/progress*/], __M([0/*require*/,1/*exports*/,11/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IEditorProgressService = instantiation_1.createDecorator('editorProgressService');
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[42/*vs/platform/registry/common/platform*/], __M([0/*require*/,1/*exports*/,21/*vs/base/common/types*/,124/*vs/base/common/assert*/]), function (require, exports, Types, Assert) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var RegistryImpl = /** @class */ (function () {
function RegistryImpl() {
this.data = new Map();
}
RegistryImpl.prototype.add = function (id, data) {
Assert.ok(Types.isString(id));
Assert.ok(Types.isObject(data));
Assert.ok(!this.data.has(id), 'There is already an extension with this id');
this.data.set(id, data);
};
RegistryImpl.prototype.as = function (id) {
return this.data.get(id) || null;
};
return RegistryImpl;
}());
exports.Registry = new RegistryImpl();
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[118/*vs/editor/common/modes/modesRegistry*/], __M([0/*require*/,1/*exports*/,425/*vs/nls!vs/editor/common/modes/modesRegistry*/,4/*vs/base/common/event*/,17/*vs/editor/common/modes*/,41/*vs/editor/common/modes/languageConfigurationRegistry*/,42/*vs/platform/registry/common/platform*/]), function (require, exports, nls, event_1, modes_1, languageConfigurationRegistry_1, platform_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Define extension point ids
exports.Extensions = {
ModesRegistry: 'editor.modesRegistry'
};
var EditorModesRegistry = /** @class */ (function () {
function EditorModesRegistry() {
this._onDidChangeLanguages = new event_1.Emitter();
this.onDidChangeLanguages = this._onDidChangeLanguages.event;
this._languages = [];
this._dynamicLanguages = [];
}
// --- languages
EditorModesRegistry.prototype.registerLanguage = function (def) {
this._languages.push(def);
this._onDidChangeLanguages.fire(undefined);
};
EditorModesRegistry.prototype.getLanguages = function () {
return [].concat(this._languages).concat(this._dynamicLanguages);
};
return EditorModesRegistry;
}());
exports.EditorModesRegistry = EditorModesRegistry;
exports.ModesRegistry = new EditorModesRegistry();
platform_1.Registry.add(exports.Extensions.ModesRegistry, exports.ModesRegistry);
exports.PLAINTEXT_MODE_ID = 'plaintext';
exports.PLAINTEXT_LANGUAGE_IDENTIFIER = new modes_1.LanguageIdentifier(exports.PLAINTEXT_MODE_ID, 1 /* PlainText */);
exports.ModesRegistry.registerLanguage({
id: exports.PLAINTEXT_MODE_ID,
extensions: ['.txt', '.gitignore'],
aliases: [nls.localize(0, null), 'text'],
mimetypes: ['text/plain']
});
languageConfigurationRegistry_1.LanguageConfigurationRegistry.register(exports.PLAINTEXT_LANGUAGE_IDENTIFIER, {
brackets: [
['(', ')'],
['[', ']'],
['{', '}'],
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '<', close: '>' },
{ open: '\"', close: '\"' },
{ open: '\'', close: '\'' },
{ open: '`', close: '`' },
],
folding: {
offSide: true
}
});
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[511/*vs/editor/common/services/getIconClasses*/], __M([0/*require*/,1/*exports*/,46/*vs/base/common/network*/,39/*vs/base/common/resources*/,118/*vs/editor/common/modes/modesRegistry*/,208/*vs/platform/files/common/files*/]), function (require, exports, network_1, resources_1, modesRegistry_1, files_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getIconClasses(modelService, modeService, resource, fileKind) {
// we always set these base classes even if we do not have a path
var classes = fileKind === files_1.FileKind.ROOT_FOLDER ? ['rootfolder-icon'] : fileKind === files_1.FileKind.FOLDER ? ['folder-icon'] : ['file-icon'];
if (resource) {
// Get the path and name of the resource. For data-URIs, we need to parse specially
var name_1;
if (resource.scheme === network_1.Schemas.data) {
var metadata = resources_1.DataUri.parseMetaData(resource);
name_1 = metadata.get(resources_1.DataUri.META_DATA_LABEL);
}
else {
name_1 = cssEscape(resources_1.basenameOrAuthority(resource).toLowerCase());
}
// Folders
if (fileKind === files_1.FileKind.FOLDER) {
classes.push(name_1 + "-name-folder-icon");
}
// Files
else {
// Name & Extension(s)
if (name_1) {
classes.push(name_1 + "-name-file-icon");
var dotSegments = name_1.split('.');
for (var i = 1; i < dotSegments.length; i++) {
classes.push(dotSegments.slice(i).join('.') + "-ext-file-icon"); // add each combination of all found extensions if more than one
}
classes.push("ext-file-icon"); // extra segment to increase file-ext score
}
// Detected Mode
var detectedModeId = detectModeId(modelService, modeService, resource);
if (detectedModeId) {
classes.push(cssEscape(detectedModeId) + "-lang-file-icon");
}
}
}
return classes;
}
exports.getIconClasses = getIconClasses;
function detectModeId(modelService, modeService, resource) {
if (!resource) {
return null; // we need a resource at least
}
var modeId = null;
// Data URI: check for encoded metadata
if (resource.scheme === network_1.Schemas.data) {
var metadata = resources_1.DataUri.parseMetaData(resource);
var mime = metadata.get(resources_1.DataUri.META_DATA_MIME);
if (mime) {
modeId = modeService.getModeId(mime);
}
}
// Any other URI: check for model if existing
else {
var model = modelService.getModel(resource);
if (model) {
modeId = model.getModeId();
}
}
// only take if the mode is specific (aka no just plain text)
if (modeId && modeId !== modesRegistry_1.PLAINTEXT_MODE_ID) {
return modeId;
}
// otherwise fallback to path based detection
return modeService.getModeIdByFilepathOrFirstLine(resource);
}
exports.detectModeId = detectModeId;
function cssEscape(val) {
return val.replace(/\s/g, '\\$&'); // make sure to not introduce CSS classes from files that contain whitespace
}
exports.cssEscape = cssEscape;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[220/*vs/platform/jsonschemas/common/jsonContributionRegistry*/], __M([0/*require*/,1/*exports*/,42/*vs/platform/registry/common/platform*/,4/*vs/base/common/event*/]), function (require, exports, platform, event_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Extensions = {
JSONContribution: 'base.contributions.json'
};
function normalizeId(id) {
if (id.length > 0 && id.charAt(id.length - 1) === '#') {
return id.substring(0, id.length - 1);
}
return id;
}
var JSONContributionRegistry = /** @class */ (function () {
function JSONContributionRegistry() {
this._onDidChangeSchema = new event_1.Emitter();
this.schemasById = {};
}
JSONContributionRegistry.prototype.registerSchema = function (uri, unresolvedSchemaContent) {
this.schemasById[normalizeId(uri)] = unresolvedSchemaContent;
this._onDidChangeSchema.fire(uri);
};
JSONContributionRegistry.prototype.notifySchemaChanged = function (uri) {
this._onDidChangeSchema.fire(uri);
};
return JSONContributionRegistry;
}());
var jsonContributionRegistry = new JSONContributionRegistry();
platform.Registry.add(exports.Extensions.JSONContribution, jsonContributionRegistry);
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[85/*vs/platform/configuration/common/configurationRegistry*/], __M([0/*require*/,1/*exports*/,472/*vs/nls!vs/platform/configuration/common/configurationRegistry*/,4/*vs/base/common/event*/,42/*vs/platform/registry/common/platform*/,21/*vs/base/common/types*/,220/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,38/*vs/base/common/map*/]), function (require, exports, nls, event_1, platform_1, types, jsonContributionRegistry_1, map_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Extensions = {
Configuration: 'base.contributions.configuration'
};
exports.allSettings = { properties: {}, patternProperties: {} };
exports.applicationSettings = { properties: {}, patternProperties: {} };
exports.machineSettings = { properties: {}, patternProperties: {} };
exports.machineOverridableSettings = { properties: {}, patternProperties: {} };
exports.windowSettings = { properties: {}, patternProperties: {} };
exports.resourceSettings = { properties: {}, patternProperties: {} };
exports.resourceLanguageSettingsSchemaId = 'vscode://schemas/settings/resourceLanguage';
var contributionRegistry = platform_1.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution);
var ConfigurationRegistry = /** @class */ (function () {
function ConfigurationRegistry() {
this.overrideIdentifiers = new Set();
this._onDidSchemaChange = new event_1.Emitter();
this._onDidUpdateConfiguration = new event_1.Emitter();
this.defaultOverridesConfigurationNode = {
id: 'defaultOverrides',
title: nls.localize(0, null),
properties: {}
};
this.configurationContributors = [this.defaultOverridesConfigurationNode];
this.resourceLanguageSettingsSchema = { properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: 'Unknown editor configuration setting', allowTrailingCommas: true, allowComments: true };
this.configurationProperties = {};
this.excludedConfigurationProperties = {};
contributionRegistry.registerSchema(exports.resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
}
ConfigurationRegistry.prototype.registerConfiguration = function (configuration, validate) {
if (validate === void 0) { validate = true; }
this.registerConfigurations([configuration], validate);
};
ConfigurationRegistry.prototype.registerConfigurations = function (configurations, validate) {
var _this = this;
if (validate === void 0) { validate = true; }
var properties = [];
configurations.forEach(function (configuration) {
properties.push.apply(properties, _this.validateAndRegisterProperties(configuration, validate)); // fills in defaults
_this.configurationContributors.push(configuration);
_this.registerJSONConfiguration(configuration);
});
contributionRegistry.registerSchema(exports.resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
this._onDidSchemaChange.fire();
this._onDidUpdateConfiguration.fire(properties);
};
ConfigurationRegistry.prototype.registerOverrideIdentifiers = function (overrideIdentifiers) {
for (var _i = 0, overrideIdentifiers_1 = overrideIdentifiers; _i < overrideIdentifiers_1.length; _i++) {
var overrideIdentifier = overrideIdentifiers_1[_i];
this.overrideIdentifiers.add(overrideIdentifier);
}
this.updateOverridePropertyPatternKey();
};
ConfigurationRegistry.prototype.validateAndRegisterProperties = function (configuration, validate, scope) {
if (validate === void 0) { validate = true; }
if (scope === void 0) { scope = 3 /* WINDOW */; }
scope = types.isUndefinedOrNull(configuration.scope) ? scope : configuration.scope;
var propertyKeys = [];
var properties = configuration.properties;
if (properties) {
for (var key in properties) {
if (validate && validateProperty(key)) {
delete properties[key];
continue;
}
// fill in default values
var property = properties[key];
var defaultValue = property.default;
if (types.isUndefined(defaultValue)) {
property.default = getDefaultValue(property.type);
}
if (exports.OVERRIDE_PROPERTY_PATTERN.test(key)) {
property.scope = undefined; // No scope for overridable properties `[${identifier}]`
}
else {
property.scope = types.isUndefinedOrNull(property.scope) ? scope : property.scope;
}
// Add to properties maps
// Property is included by default if 'included' is unspecified
if (properties[key].hasOwnProperty('included') && !properties[key].included) {
this.excludedConfigurationProperties[key] = properties[key];
delete properties[key];
continue;
}
else {
this.configurationProperties[key] = properties[key];
}
propertyKeys.push(key);
}
}
var subNodes = configuration.allOf;
if (subNodes) {
for (var _i = 0, subNodes_1 = subNodes; _i < subNodes_1.length; _i++) {
var node = subNodes_1[_i];
propertyKeys.push.apply(propertyKeys, this.validateAndRegisterProperties(node, validate, scope));
}
}
return propertyKeys;
};
ConfigurationRegistry.prototype.getConfigurationProperties = function () {
return this.configurationProperties;
};
ConfigurationRegistry.prototype.registerJSONConfiguration = function (configuration) {
var _this = this;
var register = function (configuration) {
var properties = configuration.properties;
if (properties) {
for (var key in properties) {
exports.allSettings.properties[key] = properties[key];
switch (properties[key].scope) {
case 1 /* APPLICATION */:
exports.applicationSettings.properties[key] = properties[key];
break;
case 2 /* MACHINE */:
exports.machineSettings.properties[key] = properties[key];
break;
case 6 /* MACHINE_OVERRIDABLE */:
exports.machineOverridableSettings.properties[key] = properties[key];
break;
case 3 /* WINDOW */:
exports.windowSettings.properties[key] = properties[key];
break;
case 4 /* RESOURCE */:
exports.resourceSettings.properties[key] = properties[key];
break;
case 5 /* LANGUAGE_OVERRIDABLE */:
exports.resourceSettings.properties[key] = properties[key];
_this.resourceLanguageSettingsSchema.properties[key] = properties[key];
break;
}
}
}
var subNodes = configuration.allOf;
if (subNodes) {
subNodes.forEach(register);
}
};
register(configuration);
};
ConfigurationRegistry.prototype.updateOverridePropertyPatternKey = function () {
var _a;
for (var _i = 0, _b = map_1.values(this.overrideIdentifiers); _i < _b.length; _i++) {
var overrideIdentifier = _b[_i];
var overrideIdentifierProperty = "[" + overrideIdentifier + "]";
var resourceLanguagePropertiesSchema = {
type: 'object',
description: nls.localize(1, null),
errorMessage: nls.localize(2, null),
$ref: exports.resourceLanguageSettingsSchemaId,
default: (_a = this.defaultOverridesConfigurationNode.properties[overrideIdentifierProperty]) === null || _a === void 0 ? void 0 : _a.default
};
exports.allSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
exports.applicationSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
exports.machineSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
exports.machineOverridableSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
exports.windowSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
exports.resourceSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
}
this._onDidSchemaChange.fire();
};
return ConfigurationRegistry;
}());
var OVERRIDE_PROPERTY = '\\[.*\\]$';
exports.OVERRIDE_PROPERTY_PATTERN = new RegExp(OVERRIDE_PROPERTY);
function getDefaultValue(type) {
var t = Array.isArray(type) ? type[0] : type;
switch (t) {
case 'boolean':
return false;
case 'integer':
case 'number':
return 0;
case 'string':
return '';
case 'array':
return [];
case 'object':
return {};
default:
return null;
}
}
exports.getDefaultValue = getDefaultValue;
var configurationRegistry = new ConfigurationRegistry();
platform_1.Registry.add(exports.Extensions.Configuration, configurationRegistry);
function validateProperty(property) {
if (exports.OVERRIDE_PROPERTY_PATTERN.test(property)) {
return nls.localize(3, null, property);
}
if (configurationRegistry.getConfigurationProperties()[property] !== undefined) {
return nls.localize(4, null, property);
}
return null;
}
exports.validateProperty = validateProperty;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[163/*vs/editor/common/config/commonEditorConfig*/], __M([0/*require*/,1/*exports*/,422/*vs/nls!vs/editor/common/config/commonEditorConfig*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,31/*vs/base/common/objects*/,19/*vs/base/common/arrays*/,33/*vs/editor/common/config/editorOptions*/,105/*vs/editor/common/config/editorZoom*/,142/*vs/editor/common/config/fontInfo*/,85/*vs/platform/configuration/common/configurationRegistry*/,42/*vs/platform/registry/common/platform*/,87/*vs/base/common/collections*/]), function (require, exports, nls, event_1, lifecycle_1, objects, arrays, editorOptions_1, editorZoom_1, fontInfo_1, configurationRegistry_1, platform_1, collections_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TabFocus = new /** @class */ (function () {
function class_1() {
this._tabFocus = false;
this._onDidChangeTabFocus = new event_1.Emitter();
this.onDidChangeTabFocus = this._onDidChangeTabFocus.event;
}
class_1.prototype.getTabFocusMode = function () {
return this._tabFocus;
};
class_1.prototype.setTabFocusMode = function (tabFocusMode) {
if (this._tabFocus === tabFocusMode) {
return;
}
this._tabFocus = tabFocusMode;
this._onDidChangeTabFocus.fire(this._tabFocus);
};
return class_1;
}());
var hasOwnProperty = Object.hasOwnProperty;
var ComputedEditorOptions = /** @class */ (function () {
function ComputedEditorOptions() {
this._values = [];
}
ComputedEditorOptions.prototype._read = function (id) {
return this._values[id];
};
ComputedEditorOptions.prototype.get = function (id) {
return this._values[id];
};
ComputedEditorOptions.prototype._write = function (id, value) {
this._values[id] = value;
};
return ComputedEditorOptions;
}());
exports.ComputedEditorOptions = ComputedEditorOptions;
var RawEditorOptions = /** @class */ (function () {
function RawEditorOptions() {
this._values = [];
}
RawEditorOptions.prototype._read = function (id) {
return this._values[id];
};
RawEditorOptions.prototype._write = function (id, value) {
this._values[id] = value;
};
return RawEditorOptions;
}());
var EditorConfiguration2 = /** @class */ (function () {
function EditorConfiguration2() {
}
EditorConfiguration2.readOptions = function (_options) {
var options = _options;
var result = new RawEditorOptions();
for (var _i = 0, editorOptionsRegistry_2 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_2.length; _i++) {
var editorOption = editorOptionsRegistry_2[_i];
var value = (editorOption.name === '_never_' ? undefined : options[editorOption.name]);
result._write(editorOption.id, value);
}
return result;
};
EditorConfiguration2.validateOptions = function (options) {
var result = new editorOptions_1.ValidatedEditorOptions();
for (var _i = 0, editorOptionsRegistry_3 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_3.length; _i++) {
var editorOption = editorOptionsRegistry_3[_i];
result._write(editorOption.id, editorOption.validate(options._read(editorOption.id)));
}
return result;
};
EditorConfiguration2.computeOptions = function (options, env) {
var result = new ComputedEditorOptions();
for (var _i = 0, editorOptionsRegistry_4 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_4.length; _i++) {
var editorOption = editorOptionsRegistry_4[_i];
result._write(editorOption.id, editorOption.compute(env, result, options._read(editorOption.id)));
}
return result;
};
EditorConfiguration2._deepEquals = function (a, b) {
if (typeof a !== 'object' || typeof b !== 'object') {
return (a === b);
}
if (Array.isArray(a) || Array.isArray(b)) {
return (Array.isArray(a) && Array.isArray(b) ? arrays.equals(a, b) : false);
}
for (var key in a) {
if (!EditorConfiguration2._deepEquals(a[key], b[key])) {
return false;
}
}
return true;
};
EditorConfiguration2.checkEquals = function (a, b) {
var result = [];
var somethingChanged = false;
for (var _i = 0, editorOptionsRegistry_5 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_5.length; _i++) {
var editorOption = editorOptionsRegistry_5[_i];
var changed = !EditorConfiguration2._deepEquals(a._read(editorOption.id), b._read(editorOption.id));
result[editorOption.id] = changed;
if (changed) {
somethingChanged = true;
}
}
return (somethingChanged ? new editorOptions_1.ConfigurationChangedEvent(result) : null);
};
return EditorConfiguration2;
}());
/**
* Compatibility with old options
*/
function migrateOptions(options) {
var wordWrap = options.wordWrap;
if (wordWrap === true) {
options.wordWrap = 'on';
}
else if (wordWrap === false) {
options.wordWrap = 'off';
}
var lineNumbers = options.lineNumbers;
if (lineNumbers === true) {
options.lineNumbers = 'on';
}
else if (lineNumbers === false) {
options.lineNumbers = 'off';
}
var autoClosingBrackets = options.autoClosingBrackets;
if (autoClosingBrackets === false) {
options.autoClosingBrackets = 'never';
options.autoClosingQuotes = 'never';
options.autoSurround = 'never';
}
var cursorBlinking = options.cursorBlinking;
if (cursorBlinking === 'visible') {
options.cursorBlinking = 'solid';
}
var renderWhitespace = options.renderWhitespace;
if (renderWhitespace === true) {
options.renderWhitespace = 'boundary';
}
else if (renderWhitespace === false) {
options.renderWhitespace = 'none';
}
var renderLineHighlight = options.renderLineHighlight;
if (renderLineHighlight === true) {
options.renderLineHighlight = 'line';
}
else if (renderLineHighlight === false) {
options.renderLineHighlight = 'none';
}
var acceptSuggestionOnEnter = options.acceptSuggestionOnEnter;
if (acceptSuggestionOnEnter === true) {
options.acceptSuggestionOnEnter = 'on';
}
else if (acceptSuggestionOnEnter === false) {
options.acceptSuggestionOnEnter = 'off';
}
var tabCompletion = options.tabCompletion;
if (tabCompletion === false) {
options.tabCompletion = 'off';
}
else if (tabCompletion === true) {
options.tabCompletion = 'onlySnippets';
}
var suggest = options.suggest;
if (suggest && typeof suggest.filteredTypes === 'object' && suggest.filteredTypes) {
var mapping = {};
mapping['method'] = 'showMethods';
mapping['function'] = 'showFunctions';
mapping['constructor'] = 'showConstructors';
mapping['field'] = 'showFields';
mapping['variable'] = 'showVariables';
mapping['class'] = 'showClasses';
mapping['struct'] = 'showStructs';
mapping['interface'] = 'showInterfaces';
mapping['module'] = 'showModules';
mapping['property'] = 'showProperties';
mapping['event'] = 'showEvents';
mapping['operator'] = 'showOperators';
mapping['unit'] = 'showUnits';
mapping['value'] = 'showValues';
mapping['constant'] = 'showConstants';
mapping['enum'] = 'showEnums';
mapping['enumMember'] = 'showEnumMembers';
mapping['keyword'] = 'showKeywords';
mapping['text'] = 'showWords';
mapping['color'] = 'showColors';
mapping['file'] = 'showFiles';
mapping['reference'] = 'showReferences';
mapping['folder'] = 'showFolders';
mapping['typeParameter'] = 'showTypeParameters';
mapping['snippet'] = 'showSnippets';
collections_1.forEach(mapping, function (entry) {
var value = suggest.filteredTypes[entry.key];
if (value === false) {
suggest[entry.value] = value;
}
});
// delete (suggest).filteredTypes;
}
var hover = options.hover;
if (hover === true) {
options.hover = {
enabled: true
};
}
else if (hover === false) {
options.hover = {
enabled: false
};
}
var parameterHints = options.parameterHints;
if (parameterHints === true) {
options.parameterHints = {
enabled: true
};
}
else if (parameterHints === false) {
options.parameterHints = {
enabled: false
};
}
var autoIndent = options.autoIndent;
if (autoIndent === true) {
options.autoIndent = 'full';
}
else if (autoIndent === false) {
options.autoIndent = 'advanced';
}
var matchBrackets = options.matchBrackets;
if (matchBrackets === true) {
options.matchBrackets = 'always';
}
else if (matchBrackets === false) {
options.matchBrackets = 'never';
}
}
function deepCloneAndMigrateOptions(_options) {
var options = objects.deepClone(_options);
migrateOptions(options);
return options;
}
var CommonEditorConfiguration = /** @class */ (function (_super) {
__extends(CommonEditorConfiguration, _super);
function CommonEditorConfiguration(isSimpleWidget, _options) {
var _this = _super.call(this) || this;
_this._onDidChange = _this._register(new event_1.Emitter());
_this.onDidChange = _this._onDidChange.event;
_this.isSimpleWidget = isSimpleWidget;
_this._isDominatedByLongLines = false;
_this._lineNumbersDigitCount = 1;
_this._rawOptions = deepCloneAndMigrateOptions(_options);
_this._readOptions = EditorConfiguration2.readOptions(_this._rawOptions);
_this._validatedOptions = EditorConfiguration2.validateOptions(_this._readOptions);
_this._register(editorZoom_1.EditorZoom.onDidChangeZoomLevel(function (_) { return _this._recomputeOptions(); }));
_this._register(exports.TabFocus.onDidChangeTabFocus(function (_) { return _this._recomputeOptions(); }));
return _this;
}
CommonEditorConfiguration.prototype.observeReferenceElement = function (dimension) {
};
CommonEditorConfiguration.prototype.dispose = function () {
_super.prototype.dispose.call(this);
};
CommonEditorConfiguration.prototype._recomputeOptions = function () {
var oldOptions = this.options;
var newOptions = this._computeInternalOptions();
if (!oldOptions) {
this.options = newOptions;
}
else {
var changeEvent = EditorConfiguration2.checkEquals(oldOptions, newOptions);
if (changeEvent === null) {
// nothing changed!
return;
}
this.options = newOptions;
this._onDidChange.fire(changeEvent);
}
};
CommonEditorConfiguration.prototype.getRawOptions = function () {
return this._rawOptions;
};
CommonEditorConfiguration.prototype._computeInternalOptions = function () {
var partialEnv = this._getEnvConfiguration();
var bareFontInfo = fontInfo_1.BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.zoomLevel, this.isSimpleWidget);
var env = {
outerWidth: partialEnv.outerWidth,
outerHeight: partialEnv.outerHeight,
fontInfo: this.readConfiguration(bareFontInfo),
extraEditorClassName: partialEnv.extraEditorClassName,
isDominatedByLongLines: this._isDominatedByLongLines,
lineNumbersDigitCount: this._lineNumbersDigitCount,
emptySelectionClipboard: partialEnv.emptySelectionClipboard,
pixelRatio: partialEnv.pixelRatio,
tabFocusMode: exports.TabFocus.getTabFocusMode(),
accessibilitySupport: partialEnv.accessibilitySupport
};
return EditorConfiguration2.computeOptions(this._validatedOptions, env);
};
CommonEditorConfiguration._subsetEquals = function (base, subset) {
for (var key in subset) {
if (hasOwnProperty.call(subset, key)) {
var subsetValue = subset[key];
var baseValue = base[key];
if (baseValue === subsetValue) {
continue;
}
if (Array.isArray(baseValue) && Array.isArray(subsetValue)) {
if (!arrays.equals(baseValue, subsetValue)) {
return false;
}
continue;
}
if (typeof baseValue === 'object' && typeof subsetValue === 'object') {
if (!this._subsetEquals(baseValue, subsetValue)) {
return false;
}
continue;
}
return false;
}
}
return true;
};
CommonEditorConfiguration.prototype.updateOptions = function (_newOptions) {
if (typeof _newOptions === 'undefined') {
return;
}
var newOptions = deepCloneAndMigrateOptions(_newOptions);
if (CommonEditorConfiguration._subsetEquals(this._rawOptions, newOptions)) {
return;
}
this._rawOptions = objects.mixin(this._rawOptions, newOptions || {});
this._readOptions = EditorConfiguration2.readOptions(this._rawOptions);
this._validatedOptions = EditorConfiguration2.validateOptions(this._readOptions);
this._recomputeOptions();
};
CommonEditorConfiguration.prototype.setIsDominatedByLongLines = function (isDominatedByLongLines) {
this._isDominatedByLongLines = isDominatedByLongLines;
this._recomputeOptions();
};
CommonEditorConfiguration.prototype.setMaxLineNumber = function (maxLineNumber) {
var digitCount = CommonEditorConfiguration._digitCount(maxLineNumber);
if (this._lineNumbersDigitCount === digitCount) {
return;
}
this._lineNumbersDigitCount = digitCount;
this._recomputeOptions();
};
CommonEditorConfiguration._digitCount = function (n) {
var r = 0;
while (n) {
n = Math.floor(n / 10);
r++;
}
return r ? r : 1;
};
return CommonEditorConfiguration;
}(lifecycle_1.Disposable));
exports.CommonEditorConfiguration = CommonEditorConfiguration;
exports.editorConfigurationBaseNode = Object.freeze({
id: 'editor',
order: 5,
type: 'object',
title: nls.localize(0, null),
scope: 5 /* LANGUAGE_OVERRIDABLE */,
});
var configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration);
var editorConfiguration = __assign(__assign({}, exports.editorConfigurationBaseNode), { properties: {
'editor.tabSize': {
type: 'number',
default: editorOptions_1.EDITOR_MODEL_DEFAULTS.tabSize,
minimum: 1,
markdownDescription: nls.localize(1, null)
},
// 'editor.indentSize': {
// 'anyOf': [
// {
// type: 'string',
// enum: ['tabSize']
// },
// {
// type: 'number',
// minimum: 1
// }
// ],
// default: 'tabSize',
// markdownDescription: nls.localize('indentSize', "The number of spaces used for indentation or 'tabSize' to use the value from `#editor.tabSize#`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
// },
'editor.insertSpaces': {
type: 'boolean',
default: editorOptions_1.EDITOR_MODEL_DEFAULTS.insertSpaces,
markdownDescription: nls.localize(2, null)
},
'editor.detectIndentation': {
type: 'boolean',
default: editorOptions_1.EDITOR_MODEL_DEFAULTS.detectIndentation,
markdownDescription: nls.localize(3, null)
},
'editor.trimAutoWhitespace': {
type: 'boolean',
default: editorOptions_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
description: nls.localize(4, null)
},
'editor.largeFileOptimizations': {
type: 'boolean',
default: editorOptions_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
description: nls.localize(5, null)
},
'editor.wordBasedSuggestions': {
type: 'boolean',
default: true,
description: nls.localize(6, null)
},
'editor.semanticHighlighting.enabled': {
type: 'boolean',
default: false,
description: nls.localize(7, null)
},
'editor.stablePeek': {
type: 'boolean',
default: false,
markdownDescription: nls.localize(8, null)
},
'editor.maxTokenizationLineLength': {
type: 'integer',
default: 20000,
description: nls.localize(9, null)
},
'diffEditor.maxComputationTime': {
type: 'number',
default: 5000,
description: nls.localize(10, null)
},
'diffEditor.renderSideBySide': {
type: 'boolean',
default: true,
description: nls.localize(11, null)
},
'diffEditor.ignoreTrimWhitespace': {
type: 'boolean',
default: true,
description: nls.localize(12, null)
},
'diffEditor.renderIndicators': {
type: 'boolean',
default: true,
description: nls.localize(13, null)
}
} });
function isConfigurationPropertySchema(x) {
return (typeof x.type !== 'undefined' || typeof x.anyOf !== 'undefined');
}
// Add properties from the Editor Option Registry
for (var _i = 0, editorOptionsRegistry_1 = editorOptions_1.editorOptionsRegistry; _i < editorOptionsRegistry_1.length; _i++) {
var editorOption = editorOptionsRegistry_1[_i];
var schema = editorOption.schema;
if (typeof schema !== 'undefined') {
if (isConfigurationPropertySchema(schema)) {
// This is a single schema contribution
editorConfiguration.properties["editor." + editorOption.name] = schema;
}
else {
for (var key in schema) {
if (hasOwnProperty.call(schema, key)) {
editorConfiguration.properties[key] = schema[key];
}
}
}
}
}
var cachedEditorConfigurationKeys = null;
function getEditorConfigurationKeys() {
if (cachedEditorConfigurationKeys === null) {
cachedEditorConfigurationKeys = Object.create(null);
Object.keys(editorConfiguration.properties).forEach(function (prop) {
cachedEditorConfigurationKeys[prop] = true;
});
}
return cachedEditorConfigurationKeys;
}
function isEditorConfigurationKey(key) {
var editorConfigurationKeys = getEditorConfigurationKeys();
return (editorConfigurationKeys["editor." + key] || false);
}
exports.isEditorConfigurationKey = isEditorConfigurationKey;
function isDiffEditorConfigurationKey(key) {
var editorConfigurationKeys = getEditorConfigurationKeys();
return (editorConfigurationKeys["diffEditor." + key] || false);
}
exports.isDiffEditorConfigurationKey = isDiffEditorConfigurationKey;
configurationRegistry.registerConfiguration(editorConfiguration);
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[60/*vs/editor/browser/config/configuration*/], __M([0/*require*/,1/*exports*/,24/*vs/base/browser/browser*/,4/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,333/*vs/editor/browser/config/charWidthReader*/,185/*vs/editor/browser/config/elementSizeObserver*/,163/*vs/editor/common/config/commonEditorConfig*/,33/*vs/editor/common/config/editorOptions*/,142/*vs/editor/common/config/fontInfo*/]), function (require, exports, browser, event_1, lifecycle_1, platform, charWidthReader_1, elementSizeObserver_1, commonEditorConfig_1, editorOptions_1, fontInfo_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CSSBasedConfigurationCache = /** @class */ (function () {
function CSSBasedConfigurationCache() {
this._keys = Object.create(null);
this._values = Object.create(null);
}
CSSBasedConfigurationCache.prototype.has = function (item) {
var itemId = item.getId();
return !!this._values[itemId];
};
CSSBasedConfigurationCache.prototype.get = function (item) {
var itemId = item.getId();
return this._values[itemId];
};
CSSBasedConfigurationCache.prototype.put = function (item, value) {
var itemId = item.getId();
this._keys[itemId] = item;
this._values[itemId] = value;
};
CSSBasedConfigurationCache.prototype.remove = function (item) {
var itemId = item.getId();
delete this._keys[itemId];
delete this._values[itemId];
};
CSSBasedConfigurationCache.prototype.getValues = function () {
var _this = this;
return Object.keys(this._keys).map(function (id) { return _this._values[id]; });
};
return CSSBasedConfigurationCache;
}());
function clearAllFontInfos() {
CSSBasedConfiguration.INSTANCE.clearCache();
}
exports.clearAllFontInfos = clearAllFontInfos;
var CSSBasedConfiguration = /** @class */ (function (_super) {
__extends(CSSBasedConfiguration, _super);
function CSSBasedConfiguration() {
var _this = _super.call(this) || this;
_this._onDidChange = _this._register(new event_1.Emitter());
_this.onDidChange = _this._onDidChange.event;
_this._cache = new CSSBasedConfigurationCache();
_this._evictUntrustedReadingsTimeout = -1;
return _this;
}
CSSBasedConfiguration.prototype.dispose = function () {
if (this._evictUntrustedReadingsTimeout !== -1) {
clearTimeout(this._evictUntrustedReadingsTimeout);
this._evictUntrustedReadingsTimeout = -1;
}
_super.prototype.dispose.call(this);
};
CSSBasedConfiguration.prototype.clearCache = function () {
this._cache = new CSSBasedConfigurationCache();
this._onDidChange.fire();
};
CSSBasedConfiguration.prototype._writeToCache = function (item, value) {
var _this = this;
this._cache.put(item, value);
if (!value.isTrusted && this._evictUntrustedReadingsTimeout === -1) {
// Try reading again after some time
this._evictUntrustedReadingsTimeout = setTimeout(function () {
_this._evictUntrustedReadingsTimeout = -1;
_this._evictUntrustedReadings();
}, 5000);
}
};
CSSBasedConfiguration.prototype._evictUntrustedReadings = function () {
var values = this._cache.getValues();
var somethingRemoved = false;
for (var i = 0, len = values.length; i < len; i++) {
var item = values[i];
if (!item.isTrusted) {
somethingRemoved = true;
this._cache.remove(item);
}
}
if (somethingRemoved) {
this._onDidChange.fire();
}
};
CSSBasedConfiguration.prototype.readConfiguration = function (bareFontInfo) {
if (!this._cache.has(bareFontInfo)) {
var readConfig = CSSBasedConfiguration._actualReadConfiguration(bareFontInfo);
if (readConfig.typicalHalfwidthCharacterWidth <= 2 || readConfig.typicalFullwidthCharacterWidth <= 2 || readConfig.spaceWidth <= 2 || readConfig.maxDigitWidth <= 2) {
// Hey, it's Bug 14341 ... we couldn't read
readConfig = new fontInfo_1.FontInfo({
zoomLevel: browser.getZoomLevel(),
fontFamily: readConfig.fontFamily,
fontWeight: readConfig.fontWeight,
fontSize: readConfig.fontSize,
fontFeatureSettings: readConfig.fontFeatureSettings,
lineHeight: readConfig.lineHeight,
letterSpacing: readConfig.letterSpacing,
isMonospace: readConfig.isMonospace,
typicalHalfwidthCharacterWidth: Math.max(readConfig.typicalHalfwidthCharacterWidth, 5),
typicalFullwidthCharacterWidth: Math.max(readConfig.typicalFullwidthCharacterWidth, 5),
canUseHalfwidthRightwardsArrow: readConfig.canUseHalfwidthRightwardsArrow,
spaceWidth: Math.max(readConfig.spaceWidth, 5),
middotWidth: Math.max(readConfig.middotWidth, 5),
maxDigitWidth: Math.max(readConfig.maxDigitWidth, 5),
}, false);
}
this._writeToCache(bareFontInfo, readConfig);
}
return this._cache.get(bareFontInfo);
};
CSSBasedConfiguration.createRequest = function (chr, type, all, monospace) {
var result = new charWidthReader_1.CharWidthRequest(chr, type);
all.push(result);
if (monospace) {
monospace.push(result);
}
return result;
};
CSSBasedConfiguration._actualReadConfiguration = function (bareFontInfo) {
var all = [];
var monospace = [];
var typicalHalfwidthCharacter = this.createRequest('n', 0 /* Regular */, all, monospace);
var typicalFullwidthCharacter = this.createRequest('\uff4d', 0 /* Regular */, all, null);
var space = this.createRequest(' ', 0 /* Regular */, all, monospace);
var digit0 = this.createRequest('0', 0 /* Regular */, all, monospace);
var digit1 = this.createRequest('1', 0 /* Regular */, all, monospace);
var digit2 = this.createRequest('2', 0 /* Regular */, all, monospace);
var digit3 = this.createRequest('3', 0 /* Regular */, all, monospace);
var digit4 = this.createRequest('4', 0 /* Regular */, all, monospace);
var digit5 = this.createRequest('5', 0 /* Regular */, all, monospace);
var digit6 = this.createRequest('6', 0 /* Regular */, all, monospace);
var digit7 = this.createRequest('7', 0 /* Regular */, all, monospace);
var digit8 = this.createRequest('8', 0 /* Regular */, all, monospace);
var digit9 = this.createRequest('9', 0 /* Regular */, all, monospace);
// monospace test: used for whitespace rendering
var rightwardsArrow = this.createRequest('→', 0 /* Regular */, all, monospace);
var halfwidthRightwardsArrow = this.createRequest('→', 0 /* Regular */, all, null);
// middle dot character
var middot = this.createRequest('·', 0 /* Regular */, all, monospace);
// monospace test: some characters
this.createRequest('|', 0 /* Regular */, all, monospace);
this.createRequest('/', 0 /* Regular */, all, monospace);
this.createRequest('-', 0 /* Regular */, all, monospace);
this.createRequest('_', 0 /* Regular */, all, monospace);
this.createRequest('i', 0 /* Regular */, all, monospace);
this.createRequest('l', 0 /* Regular */, all, monospace);
this.createRequest('m', 0 /* Regular */, all, monospace);
// monospace italic test
this.createRequest('|', 1 /* Italic */, all, monospace);
this.createRequest('_', 1 /* Italic */, all, monospace);
this.createRequest('i', 1 /* Italic */, all, monospace);
this.createRequest('l', 1 /* Italic */, all, monospace);
this.createRequest('m', 1 /* Italic */, all, monospace);
this.createRequest('n', 1 /* Italic */, all, monospace);
// monospace bold test
this.createRequest('|', 2 /* Bold */, all, monospace);
this.createRequest('_', 2 /* Bold */, all, monospace);
this.createRequest('i', 2 /* Bold */, all, monospace);
this.createRequest('l', 2 /* Bold */, all, monospace);
this.createRequest('m', 2 /* Bold */, all, monospace);
this.createRequest('n', 2 /* Bold */, all, monospace);
charWidthReader_1.readCharWidths(bareFontInfo, all);
var maxDigitWidth = Math.max(digit0.width, digit1.width, digit2.width, digit3.width, digit4.width, digit5.width, digit6.width, digit7.width, digit8.width, digit9.width);
var isMonospace = (bareFontInfo.fontFeatureSettings === editorOptions_1.EditorFontLigatures.OFF);
var referenceWidth = monospace[0].width;
for (var i = 1, len = monospace.length; isMonospace && i < len; i++) {
var diff = referenceWidth - monospace[i].width;
if (diff < -0.001 || diff > 0.001) {
isMonospace = false;
break;
}
}
var canUseHalfwidthRightwardsArrow = true;
if (isMonospace && halfwidthRightwardsArrow.width !== referenceWidth) {
// using a halfwidth rightwards arrow would break monospace...
canUseHalfwidthRightwardsArrow = false;
}
if (halfwidthRightwardsArrow.width > rightwardsArrow.width) {
// using a halfwidth rightwards arrow would paint a larger arrow than a regular rightwards arrow
canUseHalfwidthRightwardsArrow = false;
}
// let's trust the zoom level only 2s after it was changed.
var canTrustBrowserZoomLevel = (browser.getTimeSinceLastZoomLevelChanged() > 2000);
return new fontInfo_1.FontInfo({
zoomLevel: browser.getZoomLevel(),
fontFamily: bareFontInfo.fontFamily,
fontWeight: bareFontInfo.fontWeight,
fontSize: bareFontInfo.fontSize,
fontFeatureSettings: bareFontInfo.fontFeatureSettings,
lineHeight: bareFontInfo.lineHeight,
letterSpacing: bareFontInfo.letterSpacing,
isMonospace: isMonospace,
typicalHalfwidthCharacterWidth: typicalHalfwidthCharacter.width,
typicalFullwidthCharacterWidth: typicalFullwidthCharacter.width,
canUseHalfwidthRightwardsArrow: canUseHalfwidthRightwardsArrow,
spaceWidth: space.width,
middotWidth: middot.width,
maxDigitWidth: maxDigitWidth
}, canTrustBrowserZoomLevel);
};
CSSBasedConfiguration.INSTANCE = new CSSBasedConfiguration();
return CSSBasedConfiguration;
}(lifecycle_1.Disposable));
var Configuration = /** @class */ (function (_super) {
__extends(Configuration, _super);
function Configuration(isSimpleWidget, options, referenceDomElement, accessibilityService) {
if (referenceDomElement === void 0) { referenceDomElement = null; }
var _this = _super.call(this, isSimpleWidget, options) || this;
_this.accessibilityService = accessibilityService;
_this._elementSizeObserver = _this._register(new elementSizeObserver_1.ElementSizeObserver(referenceDomElement, options.dimension, function () { return _this._onReferenceDomElementSizeChanged(); }));
_this._register(CSSBasedConfiguration.INSTANCE.onDidChange(function () { return _this._onCSSBasedConfigurationChanged(); }));
if (_this._validatedOptions.get(9 /* automaticLayout */)) {
_this._elementSizeObserver.startObserving();
}
_this._register(browser.onDidChangeZoomLevel(function (_) { return _this._recomputeOptions(); }));
_this._register(_this.accessibilityService.onDidChangeScreenReaderOptimized(function () { return _this._recomputeOptions(); }));
_this._recomputeOptions();
return _this;
}
Configuration.applyFontInfoSlow = function (domNode, fontInfo) {
domNode.style.fontFamily = fontInfo.getMassagedFontFamily();
domNode.style.fontWeight = fontInfo.fontWeight;
domNode.style.fontSize = fontInfo.fontSize + 'px';
domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
domNode.style.lineHeight = fontInfo.lineHeight + 'px';
domNode.style.letterSpacing = fontInfo.letterSpacing + 'px';
};
Configuration.applyFontInfo = function (domNode, fontInfo) {
domNode.setFontFamily(fontInfo.getMassagedFontFamily());
domNode.setFontWeight(fontInfo.fontWeight);
domNode.setFontSize(fontInfo.fontSize);
domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings);
domNode.setLineHeight(fontInfo.lineHeight);
domNode.setLetterSpacing(fontInfo.letterSpacing);
};
Configuration.prototype._onReferenceDomElementSizeChanged = function () {
this._recomputeOptions();
};
Configuration.prototype._onCSSBasedConfigurationChanged = function () {
this._recomputeOptions();
};
Configuration.prototype.observeReferenceElement = function (dimension) {
this._elementSizeObserver.observe(dimension);
};
Configuration.prototype.dispose = function () {
_super.prototype.dispose.call(this);
};
Configuration.prototype._getExtraEditorClassName = function () {
var extra = '';
if (!browser.isSafari && !browser.isWebkitWebView) {
// Use user-select: none in all browsers except Safari and native macOS WebView
extra += 'no-user-select ';
}
if (platform.isMacintosh) {
extra += 'mac ';
}
return extra;
};
Configuration.prototype._getEnvConfiguration = function () {
return {
extraEditorClassName: this._getExtraEditorClassName(),
outerWidth: this._elementSizeObserver.getWidth(),
outerHeight: this._elementSizeObserver.getHeight(),
emptySelectionClipboard: browser.isWebKit || browser.isFirefox,
pixelRatio: browser.getPixelRatio(),
zoomLevel: browser.getZoomLevel(),
accessibilitySupport: (this.accessibilityService.isScreenReaderOptimized()
? 2 /* Enabled */
: this.accessibilityService.getAccessibilitySupport())
};
};
Configuration.prototype.readConfiguration = function (bareFontInfo) {
return CSSBasedConfiguration.INSTANCE.readConfiguration(bareFontInfo);
};
return Configuration;
}(commonEditorConfig_1.CommonEditorConfiguration));
exports.Configuration = Configuration;
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[512/*vs/editor/browser/view/domLineBreaksComputer*/], __M([0/*require*/,1/*exports*/,161/*vs/editor/common/viewModel/splitLinesCollection*/,106/*vs/editor/common/core/stringBuilder*/,5/*vs/base/common/strings*/,60/*vs/editor/browser/config/configuration*/]), function (require, exports, splitLinesCollection_1, stringBuilder_1, strings, configuration_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DOMLineBreaksComputerFactory = /** @class */ (function () {
function DOMLineBreaksComputerFactory() {
}
DOMLineBreaksComputerFactory.create = function () {
return new DOMLineBreaksComputerFactory();
};
DOMLineBreaksComputerFactory.prototype.createLineBreaksComputer = function (fontInfo, tabSize, wrappingColumn, wrappingIndent) {
tabSize = tabSize | 0; //@perf
wrappingColumn = +wrappingColumn; //@perf
var requests = [];
return {
addRequest: function (lineText, previousLineBreakData) {
requests.push(lineText);
},
finalize: function () {
return createLineBreaks(requests, fontInfo, tabSize, wrappingColumn, wrappingIndent);
}
};
};
return DOMLineBreaksComputerFactory;
}());
exports.DOMLineBreaksComputerFactory = DOMLineBreaksComputerFactory;
function createLineBreaks(requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent) {
if (firstLineBreakColumn === -1) {
var result_1 = [];
for (var i = 0, len = requests.length; i < len; i++) {
result_1[i] = null;
}
return result_1;
}
var overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth);
// Cannot respect WrappingIndent.Indent and WrappingIndent.DeepIndent because that would require
// two dom layouts, in order to first set the width of the first line, and then set the width of the wrapped lines
if (wrappingIndent === 2 /* Indent */ || wrappingIndent === 3 /* DeepIndent */) {
wrappingIndent = 1 /* Same */;
}
var containerDomNode = document.createElement('div');
configuration_1.Configuration.applyFontInfoSlow(containerDomNode, fontInfo);
var sb = stringBuilder_1.createStringBuilder(10000);
var firstNonWhitespaceIndices = [];
var wrappedTextIndentLengths = [];
var renderLineContents = [];
var allCharOffsets = [];
var allVisibleColumns = [];
for (var i = 0; i < requests.length; i++) {
var lineContent = requests[i];
var firstNonWhitespaceIndex = 0;
var wrappedTextIndentLength = 0;
var width = overallWidth;
if (wrappingIndent !== 0 /* None */) {
firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
if (firstNonWhitespaceIndex === -1) {
// all whitespace line
firstNonWhitespaceIndex = 0;
}
else {
// Track existing indent
for (var i_1 = 0; i_1 < firstNonWhitespaceIndex; i_1++) {
var charWidth = (lineContent.charCodeAt(i_1) === 9 /* Tab */
? (tabSize - (wrappedTextIndentLength % tabSize))
: 1);
wrappedTextIndentLength += charWidth;
}
var indentWidth = Math.ceil(fontInfo.spaceWidth * wrappedTextIndentLength);
// Force sticking to beginning of line if no character would fit except for the indentation
if (indentWidth + fontInfo.typicalFullwidthCharacterWidth > overallWidth) {
firstNonWhitespaceIndex = 0;
wrappedTextIndentLength = 0;
}
else {
width = overallWidth - indentWidth;
}
}
}
var renderLineContent = lineContent.substr(firstNonWhitespaceIndex);
var tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width, sb);
firstNonWhitespaceIndices[i] = firstNonWhitespaceIndex;
wrappedTextIndentLengths[i] = wrappedTextIndentLength;
renderLineContents[i] = renderLineContent;
allCharOffsets[i] = tmp[0];
allVisibleColumns[i] = tmp[1];
}
containerDomNode.innerHTML = sb.build();
containerDomNode.style.position = 'absolute';
containerDomNode.style.top = '10000';
containerDomNode.style.wordWrap = 'break-word';
document.body.appendChild(containerDomNode);
var range = document.createRange();
var lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0);
var result = [];
for (var i = 0; i < requests.length; i++) {
var lineDomNode = lineDomNodes[i];
var breakOffsets = readLineBreaks(range, lineDomNode, renderLineContents[i], allCharOffsets[i]);
if (breakOffsets === null) {
result[i] = null;
continue;
}
var firstNonWhitespaceIndex = firstNonWhitespaceIndices[i];
var wrappedTextIndentLength = wrappedTextIndentLengths[i];
var visibleColumns = allVisibleColumns[i];
var breakOffsetsVisibleColumn = [];
for (var j = 0, len = breakOffsets.length; j < len; j++) {
breakOffsetsVisibleColumn[j] = visibleColumns[breakOffsets[j]];
}
if (firstNonWhitespaceIndex !== 0) {
// All break offsets are relative to the renderLineContent, make them absolute again
for (var j = 0, len = breakOffsets.length; j < len; j++) {
breakOffsets[j] += firstNonWhitespaceIndex;
}
}
result[i] = new splitLinesCollection_1.LineBreakData(breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength);
}
document.body.removeChild(containerDomNode);
return result;
}
function renderLine(lineContent, initialVisibleColumn, tabSize, width, sb) {
sb.appendASCIIString('
');
// if (containsRTL) {
// sb.appendASCIIString('" dir="ltr');
// }
var len = lineContent.length;
var visibleColumn = initialVisibleColumn;
var charOffset = 0;
var charOffsets = [];
var visibleColumns = [];
var nextCharCode = (0 < len ? lineContent.charCodeAt(0) : 0 /* Null */);
for (var charIndex = 0; charIndex < len; charIndex++) {
charOffsets[charIndex] = charOffset;
visibleColumns[charIndex] = visibleColumn;
var charCode = nextCharCode;
nextCharCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* Null */);
var producedCharacters = 1;
var charWidth = 1;
switch (charCode) {
case 9 /* Tab */:
producedCharacters = (tabSize - (visibleColumn % tabSize));
charWidth = producedCharacters;
for (var space = 1; space <= producedCharacters; space++) {
if (space < producedCharacters) {
sb.write1(0xA0); //
}
else {
sb.appendASCII(32 /* Space */);
}
}
break;
case 32 /* Space */:
if (nextCharCode === 32 /* Space */) {
sb.write1(0xA0); //
}
else {
sb.appendASCII(32 /* Space */);
}
break;
case 60 /* LessThan */:
sb.appendASCIIString('<');
break;
case 62 /* GreaterThan */:
sb.appendASCIIString('>');
break;
case 38 /* Ampersand */:
sb.appendASCIIString('&');
break;
case 0 /* Null */:
sb.appendASCIIString('');
break;
case 65279 /* UTF8_BOM */:
case 8232 /* LINE_SEPARATOR_2028 */:
sb.write1(0xFFFD);
break;
default:
if (strings.isFullWidthCharacter(charCode)) {
charWidth++;
}
// if (renderControlCharacters && charCode < 32) {
// sb.write1(9216 + charCode);
// } else {
sb.write1(charCode);
// }
}
charOffset += producedCharacters;
visibleColumn += charWidth;
}
charOffsets[lineContent.length] = charOffset;
visibleColumns[lineContent.length] = visibleColumn;
sb.appendASCIIString('
');
return [charOffsets, visibleColumns];
}
function readLineBreaks(range, lineDomNode, lineContent, charOffsets) {
if (lineContent.length <= 1) {
return null;
}
var textContentNode = lineDomNode.firstChild;
var breakOffsets = [];
discoverBreaks(range, textContentNode, charOffsets, 0, null, lineContent.length - 1, null, breakOffsets);
if (breakOffsets.length === 0) {
return null;
}
breakOffsets.push(lineContent.length);
return breakOffsets;
}
function discoverBreaks(range, textContentNode, charOffsets, low, lowRects, high, highRects, result) {
if (low === high) {
return;
}
lowRects = lowRects || readClientRect(range, textContentNode, charOffsets[low], charOffsets[low + 1]);
highRects = highRects || readClientRect(range, textContentNode, charOffsets[high], charOffsets[high + 1]);
if (Math.abs(lowRects[0].top - highRects[0].top) <= 0.1) {
// same line
return;
}
// there is at least one line break between these two offsets
if (low + 1 === high) {
// the two characters are adjacent, so the line break must be exactly between them
result.push(high);
return;
}
var mid = low + ((high - low) / 2) | 0;
var midRects = readClientRect(range, textContentNode, charOffsets[mid], charOffsets[mid + 1]);
discoverBreaks(range, textContentNode, charOffsets, low, lowRects, mid, midRects, result);
discoverBreaks(range, textContentNode, charOffsets, mid, midRects, high, highRects, result);
}
function readClientRect(range, textContentNode, startOffset, endOffset) {
range.setStart(textContentNode, startOffset);
range.setEnd(textContentNode, endOffset);
return range.getClientRects();
}
});
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(__m[513/*vs/editor/browser/view/viewOverlays*/], __M([0/*require*/,1/*exports*/,28/*vs/base/browser/fastDomNode*/,60/*vs/editor/browser/config/configuration*/,143/*vs/editor/browser/view/viewLayer*/,37/*vs/editor/browser/view/viewPart*/]), function (require, exports, fastDomNode_1, configuration_1, viewLayer_1, viewPart_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ViewOverlays = /** @class */ (function (_super) {
__extends(ViewOverlays, _super);
function ViewOverlays(context) {
var _this = _super.call(this, context) || this;
_this._visibleLines = new viewLayer_1.VisibleLinesCollection(_this);
_this.domNode = _this._visibleLines.domNode;
_this._dynamicOverlays = [];
_this._isFocused = false;
_this.domNode.setClassName('view-overlays');
return _this;
}
ViewOverlays.prototype.shouldRender = function () {
if (_super.prototype.shouldRender.call(this)) {
return true;
}
for (var i = 0, len = this._dynamicOverlays.length; i < len; i++) {
var dynamicOverlay = this._dynamicOverlays[i];
if (dynamicOverlay.shouldRender()) {
return true;
}
}
return false;
};
ViewOverlays.prototype.dispose = function () {
_super.prototype.dispose.call(this);
for (var i = 0, len = this._dynamicOverlays.length; i < len; i++) {
var dynamicOverlay = this._dynamicOverlays[i];
dynamicOverlay.dispose();
}
this._dynamicOverlays = [];
};
ViewOverlays.prototype.getDomNode = function () {
return this.domNode;
};
// ---- begin IVisibleLinesHost
ViewOverlays.prototype.createVisibleLine = function () {
return new ViewOverlayLine(this._context.configuration, this._dynamicOverlays);
};
// ---- end IVisibleLinesHost
ViewOverlays.prototype.addDynamicOverlay = function (overlay) {
this._dynamicOverlays.push(overlay);
};
// ----- event handlers
ViewOverlays.prototype.onConfigurationChanged = function (e) {
this._visibleLines.onConfigurationChanged(e);
var startLineNumber = this._visibleLines.getStartLineNumber();
var endLineNumber = this._visibleLines.getEndLineNumber();
for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
var line = this._visibleLines.getVisibleLine(lineNumber);
line.onConfigurationChanged(e);
}
return true;
};
ViewOverlays.prototype.onFlushed = function (e) {
return this._visibleLines.onFlushed(e);
};
ViewOverlays.prototype.onFocusChanged = function (e) {
this._isFocused = e.isFocused;
return true;
};
ViewOverlays.prototype.onLinesChanged = function (e) {
return this._visibleLines.onLinesChanged(e);
};
ViewOverlays.prototype.onLinesDeleted = function (e) {
return this._visibleLines.onLinesDeleted(e);
};
ViewOverlays.prototype.onLinesInserted = function (e) {
return this._visibleLines.onLinesInserted(e);
};
ViewOverlays.prototype.onScrollChanged = function (e) {
return this._visibleLines.onScrollChanged(e) || true;
};
ViewOverlays.prototype.onTokensChanged = function (e) {
return this._visibleLines.onTokensChanged(e);
};
ViewOverlays.prototype.onZonesChanged = function (e) {
return this._visibleLines.onZonesChanged(e);
};
// ----- end event handlers
ViewOverlays.prototype.prepareRender = function (ctx) {
var toRender = this._dynamicOverlays.filter(function (overlay) { return overlay.shouldRender(); });
for (var i = 0, len = toRender.length; i < len; i++) {
var dynamicOverlay = toRender[i];
dynamicOverlay.prepareRender(ctx);
dynamicOverlay.onDidRender();
}
};
ViewOverlays.prototype.render = function (ctx) {
// Overwriting to bypass `shouldRender` flag
this._viewOverlaysRender(ctx);
this.domNode.toggleClassName('focused', this._isFocused);
};
ViewOverlays.prototype._viewOverlaysRender = function (ctx) {
this._visibleLines.renderLines(ctx.viewportData);
};
return ViewOverlays;
}(viewPart_1.ViewPart));
exports.ViewOverlays = ViewOverlays;
var ViewOverlayLine = /** @class */ (function () {
function ViewOverlayLine(configuration, dynamicOverlays) {
this._configuration = configuration;
this._lineHeight = this._configuration.options.get(49 /* lineHeight */);
this._dynamicOverlays = dynamicOverlays;
this._domNode = null;
this._renderedContent = null;
}
ViewOverlayLine.prototype.getDomNode = function () {
if (!this._domNode) {
return null;
}
return this._domNode.domNode;
};
ViewOverlayLine.prototype.setDomNode = function (domNode) {
this._domNode = fastDomNode_1.createFastDomNode(domNode);
};
ViewOverlayLine.prototype.onContentChanged = function () {
// Nothing
};
ViewOverlayLine.prototype.onTokensChanged = function () {
// Nothing
};
ViewOverlayLine.prototype.onConfigurationChanged = function (e) {
this._lineHeight = this._configuration.options.get(49 /* lineHeight */);
};
ViewOverlayLine.prototype.renderLine = function (lineNumber, deltaTop, viewportData, sb) {
var result = '';
for (var i = 0, len = this._dynamicOverlays.length; i < len; i++) {
var dynamicOverlay = this._dynamicOverlays[i];
result += dynamicOverlay.render(viewportData.startLineNumber, lineNumber);
}
if (this._renderedContent === result) {
// No rendering needed
return false;
}
this._renderedContent = result;
sb.appendASCIIString('